@streamoji/aitwin 0.5.4 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aitwin.cjs +6 -6
- package/dist/aitwin.js +1922 -1914
- package/package.json +1 -1
package/dist/aitwin.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const z=require("react/jsx-runtime"),w=require("react"),Fi=require("@pipecat-ai/client-js"),Rn=require("@pipecat-ai/websocket-transport"),pe=require("pixi.js");var wn=typeof document<"u"?document.currentScript:null;const Li="https://aitwin.bubu.social",Dr={publicBase:Li},Oi="0.5.4",Ni={version:Oi},Vi={},at="https://ai.aitwin.me",Dn=`${Dr.publicBase}/custom-faces`,Ui=`${Dr.publicBase}/aitwin-workers/v${Ni.version}/visemeDiffPreview.worker.js`;function Wi(e){if(e)return e;const t=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:wn&&wn.tagName.toUpperCase()==="SCRIPT"&&wn.src||new URL("aitwin.cjs",document.baseURI).href}<"u"?Vi?.VITE_AITWIN_WORKER_URL:void 0;return t?.trim()?t.trim():Ui}const Hi="https://us-central1-streamoji-265f4.cloudfunctions.net/getAiTwin",gn=3e3,At=16,ar=3e3,$i=4e3,zi=.85,Ki=8,Bn=400,Fn="eng_a7f2b9c1",nn="eng_d4e8f3a2",ot="eng_c9b1e6d4",it=ot,Br=new Set([nn,ot]),Fr={[Fn]:"oculus_direct",[ot]:"oculus_direct",[nn]:"inworld_word"},or={google:Fn,inworld:nn,cartesia:ot};function Lr(e){return Fr[e]}function ji(e){return e===ot}function qi(e){if(e.ttsEngineId&&e.ttsEngineId in Fr)return e.ttsEngineId;const t=e.tts?.toLowerCase();return t&&t in or?or[t]:it}class Yt extends Error{constructor(t="AI twin not found"){super(t),this.name="AiTwinNotFoundError"}}async function Or(e,t=Hi){const n=new URL(t);n.searchParams.set("id",e);const r=await fetch(n.toString());if(r.status===404)throw new Yt;if(!r.ok)throw new Error(`getAiTwin failed (${r.status})`);const i=await r.json();if(!i.success)throw new Yt(i.error??"AI twin not found");const{tts:s,token:o,...a}=i.data,l=String(a.authToken??o??"").trim()||void 0;return{...a,ttsEngineId:qi(i.data),authToken:l}}const Gi="https://us-central1-streamoji-265f4.cloudfunctions.net/getAuthToken",Yi="client_6TNvp3SCs4Og0a1ijm9TommXLql1",Qi="kk8Fq8EmexzP10jMIEwY3R44M5RKUEm1",Xi="6TNvp3SCs4Og0a1ijm9TommXLql1",Ji="Swaraj Mali";async function Pt(){const e=await fetch(Gi,{method:"POST",headers:{"Content-Type":"application/json","Client-Id":Yi,"Client-Secret":Qi},body:JSON.stringify({userId:Xi,userName:Ji})});if(!e.ok)throw new Error(`getAuthToken failed (${e.status})`);const t=await e.json(),n=t.authToken??t.token??"";if(!n.trim())throw new Error("getAuthToken returned no token");return n}async function Zi(e,t=at){const n=await fetch(`${t.replace(/\/$/,"")}/api/session-value`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`/api/session-value failed (${n.status})`);const r=await n.json();if(!r.value)throw new Error("Session value response missing value");return r}function es(e){const t=e.trim();if(t.length%2!==0)throw new Error("Invalid hex key");const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function $t(e){return Uint8Array.from(e)}function ts(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}async function ns(e,t){if(!t)throw new Error("Asset key is required for encrypted assets");if(e.byteLength<28)throw new Error("Encrypted payload too small");const n=new Uint8Array(e),r=$t(n.subarray(0,12)),i=$t(n.subarray(12,28)),s=$t(n.subarray(28)),o=$t(ts(s,i)),a=await crypto.subtle.importKey("raw",es(t),{name:"AES-GCM"},!1,["decrypt"]);return crypto.subtle.decrypt({name:"AES-GCM",iv:r,tagLength:128},a,o)}let Tn=null;const kn=new Set;function zt(e){return e.includes("/custom-faces/")}function Qt(e){const t=e.binBase.trim().replace(/\/$/,""),n=e.twinBase.trim().replace(/\/$/,"");if(!(e.encrypted||zt(t)||zt(n)))return{twinBase:n,binBase:t,encrypted:!1};const i=zt(t)?t:zt(n)?n:t;return{twinBase:i,binBase:i,encrypted:!0}}function ct(e){return Qt(e).encrypted}function xn(e,t=Dn){const n=`${t.replace(/\/$/,"")}/${e}`;return{twinBase:n,binBase:n,encrypted:!0}}function Nr(e,t){return(e??t)?.trim()||void 0}function Vr(e){Tn=Qt(e);for(const t of kn)t()}function rs(e,t){const n=typeof globalThis.location<"u"?globalThis.location.href:void 0;if(!n)return Qt(e);const r=i=>{try{return new URL(i,n).href.replace(/\/$/,"")}catch{return i}};return Qt({twinBase:r(e.twinBase),binBase:r(e.binBase),encrypted:e.encrypted})}function ut(){if(!Tn)throw new Error("Twin assets not configured; call setActiveTwinAssets first");return Tn}function Ur(e){return kn.add(e),()=>kn.delete(e)}function Xt(){const e=ut();return ct(e)?`${e.binBase}/sil.bin`:`${e.twinBase}/sil.png`}function is(){const e=ut();return ct(e)?`${e.binBase}/idle.bin`:`${e.twinBase}/idle.mp4`}function Wr(){const e=ut();return ct(e)?e.binBase:e.twinBase}function Rt(){return ct(ut())}function Hr(){const e=ut();return ct(e)?`${e.binBase}/atlas.bin`:`${e.twinBase}/atlas.json`}function $r(){const e=ut();return ct(e)?`${e.binBase}/expression_atlas.bin`:`${e.twinBase}/expression_atlas.json`}function zr(e){const t=e.split(/\r?\n/);let n="",r="";for(const s of t)s.startsWith("event:")?n=s.slice(6).trim():s.startsWith("data:")&&(r=s.slice(5).trim());if(!n)return null;let i={};if(r)try{i=JSON.parse(r)}catch{i={raw:r}}return{event:n,data:i}}const Kr=["aa","CH","DD","E","FF","I","O","PP","RR","SS","TH","U","kk","nn","sil"],ss=new Map(Kr.map(e=>[e.toLowerCase(),e]));function rn(e){const t=(e??"").trim();return t?ss.get(t.toLowerCase())??"sil":"sil"}const as={aei:["aa","E","I"],o:["O","U"],ee:["I"],bmp:["PP"],fv:["FF"],l:["nn"],r:["RR"],th:["TH"],qw:["U","O"],cdgknstxyz:["DD","SS","kk","CH"]};function os(e){if(!e)return["sil"];const t=e.toLowerCase();return as[t]??["sil"]}function jr(e,t){const n=e.word.length;if(n<=0)return 0;const r=e.wduration;if(r<=0)return 0;const i=Math.max(0,Math.min(1,(t-e.wtime)/r));return Math.min(n-1,Math.floor(i*n))}function yt(e,t){const n=Math.max(0,Math.min(e.length-1,t));return e[n]??""}function sn(e,t){const n=e.toLowerCase().replace(/[^a-z']/g,"");return!n||yt(n,t)!=="w"||t>0&&yt(n,t-1)==="q"?!1:t===0&&/^w[aeiouy]/.test(n)}function cs(e,t){const n=e.toLowerCase(),r=yt(n,t),i=n.slice(Math.max(0,t-1),t+2);return r==="i"||r==="y"?"I":i.includes("ee")||r==="e"||n.includes("ea")?"E":"aa"}function us(e,t){const n=e.toLowerCase(),r=n.slice(Math.max(0,t-1),Math.min(n.length,t+3));if(/oo|ou|uw/.test(r))return"U";if(sn(n,t))return"FF";const i=yt(n,t);return i==="u"||i==="w"?"U":"O"}function ls(e,t){const n=e.toLowerCase();if(sn(n,t))return"FF";const r=n.slice(Math.max(0,t-2),t+1);if(/qu/.test(r))return"U";const i=n.slice(Math.max(0,t-1),Math.min(n.length,t+3));return/wo|wh/.test(i)||yt(n,t)==="o"?"O":"U"}const Kt={d:"DD",t:"DD",n:"DD",s:"SS",z:"SS",k:"kk",g:"kk",c:"CH",x:"CH",j:"CH"};function fs(e,t){const n=e.toLowerCase(),r=yt(n,t);if(Kt[r])return Kt[r];for(let i=0;i<n.length;i++){const s=n[i];if(Kt[s])return Kt[s]}return"DD"}function qr(e,t,n){const r=os(e);if(r.length===1)return r[0];const i=t.trim();if(!i)return r[0];const s=(e??"").toLowerCase(),o=Math.max(0,n);switch(s){case"aei":return cs(i,o);case"o":return us(i,o);case"qw":return ls(i,o);case"cdgknstxyz":return fs(i,o);default:return r[0]}}const Ln=16,En=47,Gr=new Set(["aa","E","I"]),Yr=new Set(["DD","SS","kk","CH"]),ds=[Gr,Yr];function ms(e){for(const t of ds)if(t.has(e))return t;return null}function hs(e){return ms(e)!=null}function Qr(e,t=Ln){return t<=0?e:Math.round(e/t)*t}function On(e,t=Ln){return e.map(n=>({...n,vtime:Qr(n.vtime,t)}))}function Xr(e){const t=new Map;for(const n of e)t.has(n.vtime)||t.set(n.vtime,n);return[...t.values()].sort((n,r)=>n.vtime-r.vtime)}function Nn(e){if(e.length<=2)return[...e];const t=[e[0]];for(let n=1;n<e.length-1;n++){const r=e[n],i=e[n+1],s=t[t.length-1];if(!hs(r.viseme)){t.push(r);continue}const o=r.vtime-s.vtime,a=i.vtime-r.vtime;o<En||a<En||t.push(r)}return t.push(e[e.length-1]),t}function an(e){return Nn(Xr(On(e)))}function Jr(e,t){let n="sil";for(const r of e){if(r.vtime>t)break;r.viseme!=="sil"&&(n=r.viseme)}return n}function on(e){const t=Xr(On(e)),n=Nn(t),r=new Set(n.map(s=>s.vtime)),i=[];for(const s of t)r.has(s.vtime)||i.push({viseme:s.viseme,vtime:s.vtime});return i}function ps(e){return on(e).map(t=>t.viseme)}const ws=32,cr=48;function Zr(e){let t=0;for(const n of e)t=Math.max(t,n.vtime+n.vduration);return t}function ei(e){let t=null,n=-1;for(const r of e){if(r.viseme==="sil")continue;const i=r.vtime+r.vduration;i>n&&(t=r,n=i)}return t}function gs(e){return an(e).find(n=>n.viseme!=="sil")??null}function nt(e){const t=Zr(e);return ei(e)?t+Bn:t}function ys(e){const t=[],n=gs(e);n&&n.vtime>0&&t.push({from:"sil",to:n.viseme,fromVtime:0,toVtime:n.vtime});const r=ei(e),i=Zr(e);return r&&t.push({from:r.viseme,to:"sil",fromVtime:i,toVtime:i+Bn}),t}function ti(e){const t=an(e),n=[];for(let r=0;r<t.length-1;r++){const i=t[r].viseme,s=t[r+1].viseme,o=t[r].vtime,a=t[r+1].vtime;i===s||a<=o||n.push({from:i,to:s,fromVtime:o,toVtime:a})}return n}function ni(e){return e.length===0?[]:[...ys(e),...ti(e)]}function _s(e,t){let n=null;for(const r of e){const{transStart:i,transEnd:s}=ri(r.fromVtime,r.toVtime,r.from,r.to);t>=i&&t<s&&(n=r)}return n}function ri(e,t,n,r){const i=Math.max(0,t-e);if((n==="PP"||r==="PP")&&i>cr){const f=cr,u=t,c=u-f;return{gapMs:i,effectiveGapMs:f,holdEnd:c,transStart:c,transEnd:u}}const o=i>0?Math.max(i,ws):0,a=e,l=e+o;return{gapMs:i,effectiveGapMs:o,holdEnd:e,transStart:a,transEnd:l}}function ii(e,t,n,r,i,s){r.forEach(o=>{const l=String(o.word??"").trim();if(!l)return;const f=Math.round((o.start??0)*1e3),u=o.duration!=null?Math.round(o.duration*1e3):o.end!=null?Math.max(1,Math.round((o.end-(o.start??0))*1e3)):0;t.push({word:l,wtime:i+f,wduration:u,queueIndex:t.length,gesture:o.gesture??null,emphasis:o.emphasis===!0})}),n.forEach(o=>{const a=String(o.symbol??o.viseme??"").trim();if(!a)return;const l=Math.round((o.start??0)*1e3),f=Math.max(1,Math.round((o.duration??0)*1e3)),u=i+l,c=oi(t,u),d=c?jr(c,u):0;let p;Lr(s)==="oculus_direct"?(p=rn(a),p==="U"&&c&&sn(c.word,d)&&(p="FF")):p=qr(a,c?.word??"",d),e.push({viseme:p,weight:1,vtime:u,vduration:f})})}function si(e,t){let n=t;for(const r of e){const i=Math.round((r.start??0)*1e3),s=Math.max(1,Math.round((r.duration??0)*1e3));n=Math.max(n,t+i+s)}return n}const Vn=16e3;function ai(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:Vn}function vs(e){let t=e.trim();const n=t.indexOf(",");t.startsWith("data:")&&n>=0&&(t=t.slice(n+1)),t=t.replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/");const r=t.length%4;return r!==0&&(t+="=".repeat(4-r)),t}function Ss(e){return e.length>=4&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70}function ur(e,t,n=Vn){const r=t.byteOffset%2===0?t:t.slice(),i=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),s=new Float32Array(i.length);for(let a=0;a<i.length;a++)s[a]=i[a]>=32768?-(65536-i[a])/32768:i[a]/32767;const o=e.createBuffer(1,s.length,n);return o.copyToChannel(s,0),o}function bs(e){const t=vs(e),n=window.atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}async function lr(e,t,n=Vn){const r=bs(t),i=ai(n);if(Ss(r)){const s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return e.decodeAudioData(s)}if(r.length>=2&&r.length%2===0)return ur(e,r,i);try{const s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return await e.decodeAudioData(s)}catch{return ur(e,r,i)}}function oi(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function ci(e,t){const n=[],r=[];let i=null,s=!1,o=!1,a=!1,l=!1,f=0,u=0,c=0,d=null,p=1,T=t,m=!1,P=null,C=0,E=!1,g=!1,I=0,N=null,A=null,ee=null;const fe=()=>({visemes:[],words:[],segmentOffsetMs:0}),M=()=>{g=!1,I=0},W=()=>{d!=null&&(clearTimeout(d),d=null)},K=()=>{for(const b of r){try{b.onended=null,b.stop(0)}catch{}try{b.disconnect()}catch{}}r.length=0},Q=()=>{for(const b of r)b.playbackRate.value=p},Y=()=>{if(!(m||!l||s||g||r.length>0||n.length>0)){if(a&&i&&u>0){const b=(i.currentTime-u)*1e3;if(b<C){W();const $=p>0?(C-b)/p:C-b;d=setTimeout(()=>{m||(o=!1,d=null,e.onSpeakingDone(),e.onNotify())},Math.max(0,$));return}}o=!1,W(),e.onSpeakingDone(),e.onNotify()}},de=b=>{const $=nt(b);if($<=0){e.onSpeakingDone(),e.onNotify();return}o=!0,f=performance.now(),e.onSpeakingStart(),e.onNotify(),W();const S=p>0?$/p:$;d=setTimeout(()=>{m||(o=!1,d=null,e.onSpeakingDone(),e.onNotify())},S)},F=(b,$,S,O)=>{$.length!==0&&(c=S,$.forEach(D=>{const _=String(D.word??"").trim();if(!_)return;const v=Math.round((D.start??0)*1e3),x=D.duration!=null?Math.round(D.duration*1e3):D.end!=null?Math.max(1,Math.round((D.end-(D.start??0))*1e3)):0;b.push({word:_,wtime:c+v,wduration:x,queueIndex:b.length,gesture:D.gesture??null,emphasis:D.emphasis===!0})}))},Z=(b,$,S,O,D,V)=>{S.length!==0&&(c=O,S.forEach(_=>{const v=String(_.symbol??_.viseme??"").trim();if(!v)return;const x=Math.round((_.start??0)*1e3),H=Math.max(1,Math.round((_.duration??0)*1e3)),X=c+x,se=oi($,X),Ee=se?jr(se,X):0;let _e;Lr(V)==="oculus_direct"?(_e=rn(v),_e==="U"&&se&&sn(se.word,Ee)&&(_e="FF")):_e=qr(v,se?.word??"",Ee),b.push({viseme:_e,weight:1,vtime:X,vduration:H})}),e.onNotify())},k=(b,$,S,O,D,V,_)=>{F($,O,D),Z(b,$,S,D,V,_)},q=(b,$,S)=>{ee===b&&b.visemes===$||($.length=0,S.length=0,b.visemes=$,b.words=S,b.segmentOffsetMs=0,ee=b,c=0,C=0)},re=async()=>{const b=window.AudioContext||window.webkitAudioContext;return i||(i=new b),i.state==="suspended"&&await i.resume(),P||(P=i.createMediaStreamDestination()),i},oe=(b,$)=>{if(!i)return 0;const S=i,O=S.currentTime,D=O+.02;if($.isFirstAudio){u<=0&&(u=D);const _=(D-O)*1e3;f=performance.now()+_}$.onBeforeStart?.(D);const V=S.createBufferSource();return V.buffer=b,V.playbackRate.value=p,V.connect(S.destination),P&&V.connect(P),r.push(V),m?(r.pop(),D):($.isFirstAudio&&(o=!0,e.onSpeakingStart()),V.onended=()=>{const _=r.indexOf(V);_>=0&&r.splice(_,1),e.onNotify(),!m&&(N&&A?ne(N,A):Y())},V.start(D),D)},ne=async(b,$)=>{if(m||s||r.length>0)return;if(n.length===0){Y();return}s=!0;let S=!1;try{const O=await re();if(m)return;const D=n[0];if(!D)return;const V=!o;if(E&&(e.shouldHoldForWarmup?.()??!1)&&(g||V&&D.newStream)||g){q(D.utterance,b,$);for(const x of n){if(m)return;x.audioBuffer||(x.audioBuffer=await lr(O,x.audio,x.sampleRate)),a=!0,g||(g=!0,I=0,x.newStream&&x.onNewStream?.()),x.visemesQueued||(k(b,$,x.visemes,x.words,I,!0,T),x.visemesQueued=!0,I+=Math.round(x.audioBuffer.duration*1e3),C=Math.max(C,nt(b)))}e.onNotify();return}const v=n.shift();if(!v||(v.audioBuffer||(v.audioBuffer=await lr(O,v.audio,v.sampleRate)),m))return;a=!0,W(),q(v.utterance,b,$),v.visemesQueued=!1,v.newStream&&v.onNewStream?.(),oe(v.audioBuffer,{isFirstAudio:!o,isFirstOfStream:!1,onBeforeStart:x=>{u=x,c=0,f=performance.now()+(x-O.currentTime)*1e3,b.length=0,$.length=0,k(b,$,v.visemes,v.words,0,!0,T),v.visemesQueued=!0,v.utterance.segmentOffsetMs=0}}),S=r.length>0,C=nt(b),e.onNotify()}catch(O){console.error("[avatarChunkPlayback] audio chunk failed:",O)}finally{if(s=!1,m)return;if(g){n.some(D=>!D.audioBuffer||!D.visemesQueued)&&ne(b,$);return}!S&&r.length===0&&n.length>0?ne(b,$):r.length===0&&n.length===0&&Y()}};return{setStreamTtsEngineId:b=>{T=b},setPlaybackSpeed:b=>{p=Math.max(.1,Math.min(1,b)),Q()},getPlaybackSpeed:()=>p,setLipsyncWarmupHoldEnabled:b=>{E=b,b||M()},isWarmingUp:()=>g,releaseWarmupHold:()=>{if(g){g=!1,I=0;for(const b of n)b.newStream=!1;N&&A&&ne(N,A),e.onNotify()}},resetForNewStream:b=>{m=!1,l=!1,T=b,C=0},resumeBotStream:()=>{m=!1,l=!1},clearAborted:()=>{m=!1},primeAudioContext:async()=>{const b=window.AudioContext||window.webkitAudioContext;i||(i=new b),i.state==="suspended"&&await i.resume(),i&&!P&&(P=i.createMediaStreamDestination())},stop:()=>{m=!0,W(),K(),n.length=0,s=!1,o=!1,a=!1,l=!1,c=0,u=0,f=0,C=0,N=null,A=null,ee=null,M()},markStreamComplete:b=>{if(C=Math.max(C,nt(b)),l=!0,!a&&b.length>0){de(b);return}Y()},playAudioChunk:async(b,$,S,O,D,V,_)=>{if(m)return;N=b,A=$;const v=ai(_?.sampleRate),x=_?.newStream===!0,H=fe();if(!S?.trim()){if(O.length===0&&D.length===0)return;q(H,b,$),x&&_?.onNewStream?.(),k(b,$,O,D,0,!0,T),C=nt(b),!o&&C>0&&de(b),e.onNotify();return}n.push({audio:S,audioBuffer:null,utterance:H,visemes:O,words:D,isNewSegment:V,sampleRate:v,newStream:x,onNewStream:_?.onNewStream,visemesQueued:!1}),await ne(b,$)},queueTimingsOnly:(b,$,S,O,D,V)=>{if(m)return;const _=fe();q(_,b,$),k(b,$,S,O,0,!0,T),_.segmentOffsetMs=0,C=nt(b)},getPlaybackElapsedMs:()=>a&&i&&u>0?Math.max(0,(i.currentTime-u)*1e3*p):o?Math.max(0,(performance.now()-f)*p):0,isSpeaking:()=>o?!0:!a||!i||u<=0?!1:(i.currentTime-u)*1e3<C,getVoiceStream:()=>P?P.stream:null,getPlaybackStartPerf:()=>f,bargeIn:()=>{m=!0,l=!1,W(),K(),n.length=0,s=!1,o=!1,a=!1,c=0,u=0,f=0,C=0,N=null,A=null,ee=null,M()},interrupt:()=>{m=!0,l=!1,W(),K(),n.length=0,s=!1,o=!1,a=!1,c=0,u=0,f=0,C=0,N=null,A=null,ee=null,M()}}}function Dt(e,t){let n=null;for(const r of e)t<r.vtime||t>=r.vtime+r.vduration||(!n||r.vtime>=n.vtime)&&(n=r);return n?n.viseme:"sil"}function ui(e,t,n=120){const r=Dt(e,t);if(r!=="sil")return r;let i=null;for(const s of e){if(s.vtime>t)break;const o=s.vtime+s.vduration;o<=t&&t-o<=n&&(i=s)}return i?.viseme??"sil"}function Ts(e,t,n=400){const r=t-n;let i=0;for(const s of e)if(s.vtime+s.vduration<r)i+=1;else break;i>0&&e.splice(0,i)}function ks(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function fr(e,t){const n=e.trim();if(!n)return null;try{const r=n.replace(/\s+/g,""),i=atob(r).length,s=Number.isFinite(t)&&(t??0)>0?Number(t):16e3;return i/2/s*1e3}catch{return null}}const cn=.5,un=1.5,Un="Olivia",Wn="f786b574-daa5-4673-aa0c-cbe3e8534c02",Bt=.85;function In(e,t=at,n={}){const r=`${t.replace(/\/$/,"")}/avatar_ttsWithPoses`,i=[],s=[],o=[],a=[];let l=0;const f=[],u=[];let c="",d="neutral",p="",T=it;const m=new Set;let P=0,C=null,E=0,g=null;const I=()=>m.forEach(F=>F());let N=()=>!1;const A=ci({onSpeakingStart:()=>e("speaking"),onSpeakingDone:()=>e("done"),onNotify:I,shouldHoldForWarmup:()=>N()},it),ee=()=>A.getPlaybackElapsedMs(),fe=(F,Z=c)=>{if(!n.onLipsyncDebug)return;const k=ee(),q=i,re=on(o).map(oe=>({viseme:oe.viseme,vtimeMs:oe.vtime}));n.onLipsyncDebug({event:F,spokenText:Z,mood:d,playbackAnchorPerf:A.getPlaybackStartPerf(),playbackElapsedMs:k,queueLength:q.length,activeViseme:Dt(q,k),segments:u.map(oe=>({...oe,visemes:[...oe.visemes]})),fullQueueLength:o.length,compactionSkipped:re})},M=(F,Z)=>{n.onLipsyncDebug&&(C={event:F,spokenText:Z},P===0&&(P=requestAnimationFrame(()=>{P=0;const k=C;C=null,k&&fe(k.event,k.spokenText)})))},W=(F,Z,k,q,re)=>{if(!n.onLipsyncDebug)return;const oe=i.slice(Z),ne=k.filter(te=>String(te.symbol??te.viseme??"").trim());u.push({spokenText:F,audioOffsetMs:oe[0]?.vtime??0,isNewSegment:q,chunkDurationMs:re,receivedAtMs:performance.now(),visemes:oe.map((te,ie)=>{const we=ne[ie];return{rawSymbol:String(we?.symbol??we?.viseme??te.viseme).trim(),viseme:te.viseme,startSec:Number(we?.start??0),durationSec:Number(we?.duration??0),vtimeMs:te.vtime,vdurationMs:te.vduration}})})},K=()=>{o.length=0,a.length=0,l=0},Q=(F,Z,k,q,re)=>{if(F.length===0&&Z.length===0)return;ii(o,a,F,Z,l,re);const oe=si(F,l),ne=k?fr(k,q):null;l=Math.max(oe,ne!=null?l+ne:l)},Y=()=>{E+=1,g?.abort(),g=null,A.stop(),i.length=0,s.length=0,K(),f.length=0,d="neutral",u.length=0,c="",e("idle"),M("reset"),I()};return{setDeveloperToken:F=>{p=F},setTtsEngineId:F=>{T=F},getTtsEngineId:()=>T,speak:async(F,Z)=>{Y();const k=E;g=new AbortController,e("loading"),c=F,u.length=0,K();const q=p.trim();if(!q)throw new Error("Developer token required for avatar_ttsWithPoses");const re=Z?.ttsEngineId??T??it;A.resetForNewStream(re),A.setStreamTtsEngineId(re);const oe=Z?.voiceId??Un,ne=Z?.speakingRate??Bt,te=Math.max(cn,Math.min(un,ne)),ie={user_query:F,ttsEngineId:re,speakingRate:te,tenant:"aiTwin"};Br.has(re)&&(ie.voice_id=oe);try{const we=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${q}`},body:JSON.stringify(ie),signal:g.signal});if(!we.ok)throw new Error(`avatar_ttsWithPoses failed (${we.status})`);const b=we.body;if(!b)throw new Error("No response body");const $=b.getReader(),S=new TextDecoder;let O="",D=!0;const V=async _=>{if(k!==E)return;const v=zr(_);if(v){if(v.event==="audio"){const x=v.data.chunk,H=v.data.visemes??[],X=v.data.words??[],se=v.data.is_new_segment??!1,Ee=v.data.sample_rate,_e=Number(v.data.audio_offset_ms??0),Ve=i.length;if(Q(H,X,x,Ee,re),x){const Ue=D;D=!1,await A.playAudioChunk(i,s,x,H,X,se,{sampleRate:Ee,newStream:Ue,audioOffsetMs:_e}),W(F,Ve,H,se,fr(x,Ee)),M("audio_chunk",F)}else(H.length>0||X.length>0)&&(A.queueTimingsOnly(i,s,H,X,se,{audioOffsetMs:_e,newStream:D}),W(F,Ve,H,se,null),M("audio_chunk",F))}else if(v.event==="metadata"){const x=v.data.mood;typeof x=="string"&&x.trim()&&(d=x.trim());const H=v.data.sentence_emotions;if(Array.isArray(H)){f.length=0;for(const X of H){if(!X||typeof X!="object")continue;const se=X;f.push({sentence_index:Number(se.sentence_index??0),text:String(se.text??""),sentiment:typeof se.sentiment=="string"?se.sentiment:void 0,emotion:String(se.emotion??d),start_word:Number(se.start_word??0),end_word:Number(se.end_word??0)})}}I(),M("metadata",F)}else if(v.event==="error")throw new Error(String(v.data.message??"avatar_ttsWithPoses stream error"))}};for(;k===E;){const{done:_,value:v}=await $.read();v&&(O+=S.decode(v,{stream:!0}));const x=O.split(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const z=require("react/jsx-runtime"),w=require("react"),Li=require("@pipecat-ai/client-js"),Cn=require("@pipecat-ai/websocket-transport"),he=require("pixi.js");var wn=typeof document<"u"?document.currentScript:null;const Oi="https://aitwin.bubu.social",Br={publicBase:Oi},Ni="0.5.5",Vi={version:Ni},Ui={},ot="https://ai.aitwin.me",Rn=`${Br.publicBase}/custom-faces`,Wi=`${Br.publicBase}/aitwin-workers/v${Vi.version}/visemeDiffPreview.worker.js`;function Hi(e){if(e)return e;const t=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:wn&&wn.tagName.toUpperCase()==="SCRIPT"&&wn.src||new URL("aitwin.cjs",document.baseURI).href}<"u"?Ui?.VITE_AITWIN_WORKER_URL:void 0;return t?.trim()?t.trim():Wi}const $i="https://us-central1-streamoji-265f4.cloudfunctions.net/getAiTwin",gn=3e3,Pt=16,ar=3e3,zi=4e3,Ki=.85,ji=8,Dn=400,Bn="eng_a7f2b9c1",tn="eng_d4e8f3a2",ct="eng_c9b1e6d4",st=ct,Fr=new Set([tn,ct]),Lr={[Bn]:"oculus_direct",[ct]:"oculus_direct",[tn]:"inworld_word"},or={google:Bn,inworld:tn,cartesia:ct};function Or(e){return Lr[e]}function qi(e){return e===ct}function Gi(e){if(e.ttsEngineId&&e.ttsEngineId in Lr)return e.ttsEngineId;const t=e.tts?.toLowerCase();return t&&t in or?or[t]:st}class Gt extends Error{constructor(t="AI twin not found"){super(t),this.name="AiTwinNotFoundError"}}async function Nr(e,t=$i){const n=new URL(t);n.searchParams.set("id",e);const r=await fetch(n.toString());if(r.status===404)throw new Gt;if(!r.ok)throw new Error(`getAiTwin failed (${r.status})`);const i=await r.json();if(!i.success)throw new Gt(i.error??"AI twin not found");const{tts:s,token:o,...a}=i.data,l=String(a.authToken??o??"").trim()||void 0;return{...a,ttsEngineId:Gi(i.data),authToken:l}}const Yi="https://us-central1-streamoji-265f4.cloudfunctions.net/getAuthToken",Qi="client_6TNvp3SCs4Og0a1ijm9TommXLql1",Xi="kk8Fq8EmexzP10jMIEwY3R44M5RKUEm1",Ji="6TNvp3SCs4Og0a1ijm9TommXLql1",Zi="Swaraj Mali";async function Mt(){const e=await fetch(Yi,{method:"POST",headers:{"Content-Type":"application/json","Client-Id":Qi,"Client-Secret":Xi},body:JSON.stringify({userId:Ji,userName:Zi})});if(!e.ok)throw new Error(`getAuthToken failed (${e.status})`);const t=await e.json(),n=t.authToken??t.token??"";if(!n.trim())throw new Error("getAuthToken returned no token");return n}async function es(e,t=ot){const n=await fetch(`${t.replace(/\/$/,"")}/api/session-value`,{headers:{Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`/api/session-value failed (${n.status})`);const r=await n.json();if(!r.value)throw new Error("Session value response missing value");return r}function ts(e){const t=e.trim();if(t.length%2!==0)throw new Error("Invalid hex key");const n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function Ht(e){return Uint8Array.from(e)}function ns(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}async function rs(e,t){if(!t)throw new Error("Asset key is required for encrypted assets");if(e.byteLength<28)throw new Error("Encrypted payload too small");const n=new Uint8Array(e),r=Ht(n.subarray(0,12)),i=Ht(n.subarray(12,28)),s=Ht(n.subarray(28)),o=Ht(ns(s,i)),a=await crypto.subtle.importKey("raw",ts(t),{name:"AES-GCM"},!1,["decrypt"]);return crypto.subtle.decrypt({name:"AES-GCM",iv:r,tagLength:128},a,o)}let bn=null;const Tn=new Set;function $t(e){return e.includes("/custom-faces/")}function Yt(e){const t=e.binBase.trim().replace(/\/$/,""),n=e.twinBase.trim().replace(/\/$/,"");if(!(e.encrypted||$t(t)||$t(n)))return{twinBase:n,binBase:t,encrypted:!1};const i=$t(t)?t:$t(n)?n:t;return{twinBase:i,binBase:i,encrypted:!0}}function ut(e){return Yt(e).encrypted}function kn(e,t=Rn){const n=`${t.replace(/\/$/,"")}/${e}`;return{twinBase:n,binBase:n,encrypted:!0}}function Vr(e,t){return(e??t)?.trim()||void 0}function Ur(e){bn=Yt(e);for(const t of Tn)t()}function is(e,t){const n=typeof globalThis.location<"u"?globalThis.location.href:void 0;if(!n)return Yt(e);const r=i=>{try{return new URL(i,n).href.replace(/\/$/,"")}catch{return i}};return Yt({twinBase:r(e.twinBase),binBase:r(e.binBase),encrypted:e.encrypted})}function lt(){if(!bn)throw new Error("Twin assets not configured; call setActiveTwinAssets first");return bn}function Wr(e){return Tn.add(e),()=>Tn.delete(e)}function Qt(){const e=lt();return ut(e)?`${e.binBase}/sil.bin`:`${e.twinBase}/sil.png`}function ss(){const e=lt();return ut(e)?`${e.binBase}/idle.bin`:`${e.twinBase}/idle.mp4`}function Hr(){const e=lt();return ut(e)?e.binBase:e.twinBase}function Dt(){return ut(lt())}function $r(){const e=lt();return ut(e)?`${e.binBase}/atlas.bin`:`${e.twinBase}/atlas.json`}function zr(){const e=lt();return ut(e)?`${e.binBase}/expression_atlas.bin`:`${e.twinBase}/expression_atlas.json`}function Kr(e){const t=e.split(/\r?\n/);let n="",r="";for(const s of t)s.startsWith("event:")?n=s.slice(6).trim():s.startsWith("data:")&&(r=s.slice(5).trim());if(!n)return null;let i={};if(r)try{i=JSON.parse(r)}catch{i={raw:r}}return{event:n,data:i}}const jr=["aa","CH","DD","E","FF","I","O","PP","RR","SS","TH","U","kk","nn","sil"],as=new Map(jr.map(e=>[e.toLowerCase(),e]));function nn(e){const t=(e??"").trim();return t?as.get(t.toLowerCase())??"sil":"sil"}const os={aei:["aa","E","I"],o:["O","U"],ee:["I"],bmp:["PP"],fv:["FF"],l:["nn"],r:["RR"],th:["TH"],qw:["U","O"],cdgknstxyz:["DD","SS","kk","CH"]};function cs(e){if(!e)return["sil"];const t=e.toLowerCase();return os[t]??["sil"]}function qr(e,t){const n=e.word.length;if(n<=0)return 0;const r=e.wduration;if(r<=0)return 0;const i=Math.max(0,Math.min(1,(t-e.wtime)/r));return Math.min(n-1,Math.floor(i*n))}function yt(e,t){const n=Math.max(0,Math.min(e.length-1,t));return e[n]??""}function rn(e,t){const n=e.toLowerCase().replace(/[^a-z']/g,"");return!n||yt(n,t)!=="w"||t>0&&yt(n,t-1)==="q"?!1:t===0&&/^w[aeiouy]/.test(n)}function us(e,t){const n=e.toLowerCase(),r=yt(n,t),i=n.slice(Math.max(0,t-1),t+2);return r==="i"||r==="y"?"I":i.includes("ee")||r==="e"||n.includes("ea")?"E":"aa"}function ls(e,t){const n=e.toLowerCase(),r=n.slice(Math.max(0,t-1),Math.min(n.length,t+3));if(/oo|ou|uw/.test(r))return"U";if(rn(n,t))return"FF";const i=yt(n,t);return i==="u"||i==="w"?"U":"O"}function fs(e,t){const n=e.toLowerCase();if(rn(n,t))return"FF";const r=n.slice(Math.max(0,t-2),t+1);if(/qu/.test(r))return"U";const i=n.slice(Math.max(0,t-1),Math.min(n.length,t+3));return/wo|wh/.test(i)||yt(n,t)==="o"?"O":"U"}const zt={d:"DD",t:"DD",n:"DD",s:"SS",z:"SS",k:"kk",g:"kk",c:"CH",x:"CH",j:"CH"};function ds(e,t){const n=e.toLowerCase(),r=yt(n,t);if(zt[r])return zt[r];for(let i=0;i<n.length;i++){const s=n[i];if(zt[s])return zt[s]}return"DD"}function Gr(e,t,n){const r=cs(e);if(r.length===1)return r[0];const i=t.trim();if(!i)return r[0];const s=(e??"").toLowerCase(),o=Math.max(0,n);switch(s){case"aei":return us(i,o);case"o":return ls(i,o);case"qw":return fs(i,o);case"cdgknstxyz":return ds(i,o);default:return r[0]}}const Fn=16,xn=47,Yr=new Set(["aa","E","I"]),Qr=new Set(["DD","SS","kk","CH"]),ms=[Yr,Qr];function hs(e){for(const t of ms)if(t.has(e))return t;return null}function ps(e){return hs(e)!=null}function Xr(e,t=Fn){return t<=0?e:Math.round(e/t)*t}function Ln(e,t=Fn){return e.map(n=>({...n,vtime:Xr(n.vtime,t)}))}function Jr(e){const t=new Map;for(const n of e)t.has(n.vtime)||t.set(n.vtime,n);return[...t.values()].sort((n,r)=>n.vtime-r.vtime)}function On(e){if(e.length<=2)return[...e];const t=[e[0]];for(let n=1;n<e.length-1;n++){const r=e[n],i=e[n+1],s=t[t.length-1];if(!ps(r.viseme)){t.push(r);continue}const o=r.vtime-s.vtime,a=i.vtime-r.vtime;o<xn||a<xn||t.push(r)}return t.push(e[e.length-1]),t}function sn(e){return On(Jr(Ln(e)))}function Zr(e,t){let n="sil";for(const r of e){if(r.vtime>t)break;r.viseme!=="sil"&&(n=r.viseme)}return n}function an(e){const t=Jr(Ln(e)),n=On(t),r=new Set(n.map(s=>s.vtime)),i=[];for(const s of t)r.has(s.vtime)||i.push({viseme:s.viseme,vtime:s.vtime});return i}function ws(e){return an(e).map(t=>t.viseme)}const gs=32,cr=48;function ei(e){let t=0;for(const n of e)t=Math.max(t,n.vtime+n.vduration);return t}function ti(e){let t=null,n=-1;for(const r of e){if(r.viseme==="sil")continue;const i=r.vtime+r.vduration;i>n&&(t=r,n=i)}return t}function ys(e){return sn(e).find(n=>n.viseme!=="sil")??null}function rt(e){const t=ei(e);return ti(e)?t+Dn:t}function _s(e){const t=[],n=ys(e);n&&n.vtime>0&&t.push({from:"sil",to:n.viseme,fromVtime:0,toVtime:n.vtime});const r=ti(e),i=ei(e);return r&&t.push({from:r.viseme,to:"sil",fromVtime:i,toVtime:i+Dn}),t}function ni(e){const t=sn(e),n=[];for(let r=0;r<t.length-1;r++){const i=t[r].viseme,s=t[r+1].viseme,o=t[r].vtime,a=t[r+1].vtime;i===s||a<=o||n.push({from:i,to:s,fromVtime:o,toVtime:a})}return n}function ri(e){return e.length===0?[]:[..._s(e),...ni(e)]}function vs(e,t){let n=null;for(const r of e){const{transStart:i,transEnd:s}=ii(r.fromVtime,r.toVtime,r.from,r.to);t>=i&&t<s&&(n=r)}return n}function ii(e,t,n,r){const i=Math.max(0,t-e);if((n==="PP"||r==="PP")&&i>cr){const f=cr,u=t,c=u-f;return{gapMs:i,effectiveGapMs:f,holdEnd:c,transStart:c,transEnd:u}}const o=i>0?Math.max(i,gs):0,a=e,l=e+o;return{gapMs:i,effectiveGapMs:o,holdEnd:e,transStart:a,transEnd:l}}function si(e,t,n,r,i,s){r.forEach(o=>{const l=String(o.word??"").trim();if(!l)return;const f=Math.round((o.start??0)*1e3),u=o.duration!=null?Math.round(o.duration*1e3):o.end!=null?Math.max(1,Math.round((o.end-(o.start??0))*1e3)):0;t.push({word:l,wtime:i+f,wduration:u,queueIndex:t.length,gesture:o.gesture??null,emphasis:o.emphasis===!0})}),n.forEach(o=>{const a=String(o.symbol??o.viseme??"").trim();if(!a)return;const l=Math.round((o.start??0)*1e3),f=Math.max(1,Math.round((o.duration??0)*1e3)),u=i+l,c=ci(t,u),d=c?qr(c,u):0;let p;Or(s)==="oculus_direct"?(p=nn(a),p==="U"&&c&&rn(c.word,d)&&(p="FF")):p=Gr(a,c?.word??"",d),e.push({viseme:p,weight:1,vtime:u,vduration:f})})}function ai(e,t){let n=t;for(const r of e){const i=Math.round((r.start??0)*1e3),s=Math.max(1,Math.round((r.duration??0)*1e3));n=Math.max(n,t+i+s)}return n}const Nn=16e3;function oi(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:Nn}function Ss(e){let t=e.trim();const n=t.indexOf(",");t.startsWith("data:")&&n>=0&&(t=t.slice(n+1)),t=t.replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/");const r=t.length%4;return r!==0&&(t+="=".repeat(4-r)),t}function bs(e){return e.length>=4&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70}function ur(e,t,n=Nn){const r=t.byteOffset%2===0?t:t.slice(),i=new Int16Array(r.buffer,r.byteOffset,r.byteLength/2),s=new Float32Array(i.length);for(let a=0;a<i.length;a++)s[a]=i[a]>=32768?-(65536-i[a])/32768:i[a]/32767;const o=e.createBuffer(1,s.length,n);return o.copyToChannel(s,0),o}function Ts(e){const t=Ss(e),n=window.atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}async function lr(e,t,n=Nn){const r=Ts(t),i=oi(n);if(bs(r)){const s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return e.decodeAudioData(s)}if(r.length>=2&&r.length%2===0)return ur(e,r,i);try{const s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return await e.decodeAudioData(s)}catch{return ur(e,r,i)}}function ci(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function ui(e,t){const n=[],r=[];let i=null,s=!1,o=!1,a=!1,l=!1,f=0,u=0,c=0,d=null,p=1,T=t,m=!1,A=null,C=0,x=!1,g=!1,E=0,N=null,I=null,te=null;const de=()=>({visemes:[],words:[],segmentOffsetMs:0}),P=()=>{g=!1,E=0},W=()=>{d!=null&&(clearTimeout(d),d=null)},K=()=>{for(const S of r){try{S.onended=null,S.stop(0)}catch{}try{S.disconnect()}catch{}}r.length=0},X=()=>{for(const S of r)S.playbackRate.value=p},Y=()=>{if(!(m||!l||s||g||r.length>0||n.length>0)){if(a&&i&&u>0){const S=(i.currentTime-u)*1e3;if(S<C){W();const $=p>0?(C-S)/p:C-S;d=setTimeout(()=>{m||(o=!1,d=null,e.onSpeakingDone(),e.onNotify())},Math.max(0,$));return}}o=!1,W(),e.onSpeakingDone(),e.onNotify()}},pe=S=>{const $=rt(S);if($<=0){e.onSpeakingDone(),e.onNotify();return}o=!0,f=performance.now(),e.onSpeakingStart(),e.onNotify(),W();const b=p>0?$/p:$;d=setTimeout(()=>{m||(o=!1,d=null,e.onSpeakingDone(),e.onNotify())},b)},j=(S,$,b,L)=>{$.length!==0&&(c=b,$.forEach(B=>{const _=String(B.word??"").trim();if(!_)return;const v=Math.round((B.start??0)*1e3),k=B.duration!=null?Math.round(B.duration*1e3):B.end!=null?Math.max(1,Math.round((B.end-(B.start??0))*1e3)):0;S.push({word:_,wtime:c+v,wduration:k,queueIndex:S.length,gesture:B.gesture??null,emphasis:B.emphasis===!0})}))},Z=(S,$,b,L,B,O)=>{b.length!==0&&(c=L,b.forEach(_=>{const v=String(_.symbol??_.viseme??"").trim();if(!v)return;const k=Math.round((_.start??0)*1e3),H=Math.max(1,Math.round((_.duration??0)*1e3)),J=c+k,ie=ci($,J),xe=ie?qr(ie,J):0;let be;Or(O)==="oculus_direct"?(be=nn(v),be==="U"&&ie&&rn(ie.word,xe)&&(be="FF")):be=Gr(v,ie?.word??"",xe),S.push({viseme:be,weight:1,vtime:J,vduration:H})}),e.onNotify())},M=(S,$,b,L,B,O,_)=>{j($,L,B),Z(S,$,b,B,O,_)},G=(S,$,b)=>{te===S&&S.visemes===$||($.length=0,b.length=0,S.visemes=$,S.words=b,S.segmentOffsetMs=0,te=S,c=0,C=0)},V=async()=>{const S=window.AudioContext||window.webkitAudioContext;return i||(i=new S),i.state==="suspended"&&await i.resume(),A||(A=i.createMediaStreamDestination()),i},ue=(S,$)=>{if(!i)return 0;const b=i,L=b.currentTime,B=L+.02;if($.isFirstAudio){u<=0&&(u=B);const _=(B-L)*1e3;f=performance.now()+_}$.onBeforeStart?.(B);const O=b.createBufferSource();return O.buffer=S,O.playbackRate.value=p,O.connect(b.destination),A&&O.connect(A),r.push(O),m?(r.pop(),B):($.isFirstAudio&&(o=!0,e.onSpeakingStart()),O.onended=()=>{const _=r.indexOf(O);_>=0&&r.splice(_,1),e.onNotify(),!m&&(N&&I?ne(N,I):Y())},O.start(B),B)},ne=async(S,$)=>{if(m||s||r.length>0)return;if(n.length===0){Y();return}s=!0;let b=!1;try{const L=await V();if(m)return;const B=n[0];if(!B)return;const O=!o;if(x&&(e.shouldHoldForWarmup?.()??!1)&&(g||O&&B.newStream)||g){G(B.utterance,S,$);for(const k of n){if(m)return;k.audioBuffer||(k.audioBuffer=await lr(L,k.audio,k.sampleRate)),a=!0,g||(g=!0,E=0,k.newStream&&k.onNewStream?.()),k.visemesQueued||(M(S,$,k.visemes,k.words,E,!0,T),k.visemesQueued=!0,E+=Math.round(k.audioBuffer.duration*1e3),C=Math.max(C,rt(S)))}e.onNotify();return}const v=n.shift();if(!v||(v.audioBuffer||(v.audioBuffer=await lr(L,v.audio,v.sampleRate)),m))return;a=!0,W(),G(v.utterance,S,$),v.visemesQueued=!1,v.newStream&&v.onNewStream?.(),ue(v.audioBuffer,{isFirstAudio:!o,isFirstOfStream:!1,onBeforeStart:k=>{u=k,c=0,f=performance.now()+(k-L.currentTime)*1e3,S.length=0,$.length=0,M(S,$,v.visemes,v.words,0,!0,T),v.visemesQueued=!0,v.utterance.segmentOffsetMs=0}}),b=r.length>0,C=rt(S),e.onNotify()}catch(L){console.error("[avatarChunkPlayback] audio chunk failed:",L)}finally{if(s=!1,m)return;if(g){n.some(B=>!B.audioBuffer||!B.visemesQueued)&&ne(S,$);return}!b&&r.length===0&&n.length>0?ne(S,$):r.length===0&&n.length===0&&Y()}};return{setStreamTtsEngineId:S=>{T=S},setPlaybackSpeed:S=>{p=Math.max(.1,Math.min(1,S)),X()},getPlaybackSpeed:()=>p,setLipsyncWarmupHoldEnabled:S=>{x=S,S||P()},isWarmingUp:()=>g,releaseWarmupHold:()=>{if(g){g=!1,E=0;for(const S of n)S.newStream=!1;N&&I&&ne(N,I),e.onNotify()}},resetForNewStream:S=>{m=!1,l=!1,T=S,C=0},resumeBotStream:()=>{m=!1,l=!1},clearAborted:()=>{m=!1},primeAudioContext:async()=>{const S=window.AudioContext||window.webkitAudioContext;i||(i=new S),i.state==="suspended"&&await i.resume(),i&&!A&&(A=i.createMediaStreamDestination())},stop:()=>{m=!0,W(),K(),n.length=0,s=!1,o=!1,a=!1,l=!1,c=0,u=0,f=0,C=0,N=null,I=null,te=null,P()},markStreamComplete:S=>{if(C=Math.max(C,rt(S)),l=!0,!a&&S.length>0){pe(S);return}Y()},playAudioChunk:async(S,$,b,L,B,O,_)=>{if(m)return;N=S,I=$;const v=oi(_?.sampleRate),k=_?.newStream===!0,H=de();if(!b?.trim()){if(L.length===0&&B.length===0)return;G(H,S,$),k&&_?.onNewStream?.(),M(S,$,L,B,0,!0,T),C=rt(S),!o&&C>0&&pe(S),e.onNotify();return}n.push({audio:b,audioBuffer:null,utterance:H,visemes:L,words:B,isNewSegment:O,sampleRate:v,newStream:k,onNewStream:_?.onNewStream,visemesQueued:!1}),await ne(S,$)},queueTimingsOnly:(S,$,b,L,B,O)=>{if(m)return;const _=de();G(_,S,$),M(S,$,b,L,0,!0,T),_.segmentOffsetMs=0,C=rt(S)},getPlaybackElapsedMs:()=>a&&i&&u>0?Math.max(0,(i.currentTime-u)*1e3*p):o?Math.max(0,(performance.now()-f)*p):0,isSpeaking:()=>o?!0:!a||!i||u<=0?!1:(i.currentTime-u)*1e3<C,getVoiceStream:()=>A?A.stream:null,getPlaybackStartPerf:()=>f,bargeIn:()=>{m=!0,l=!1,W(),K(),n.length=0,s=!1,o=!1,a=!1,c=0,u=0,f=0,C=0,N=null,I=null,te=null,P()},interrupt:()=>{m=!0,l=!1,W(),K(),n.length=0,s=!1,o=!1,a=!1,c=0,u=0,f=0,C=0,N=null,I=null,te=null,P()}}}function Bt(e,t){let n=null;for(const r of e)t<r.vtime||t>=r.vtime+r.vduration||(!n||r.vtime>=n.vtime)&&(n=r);return n?n.viseme:"sil"}function li(e,t,n=120){const r=Bt(e,t);if(r!=="sil")return r;let i=null;for(const s of e){if(s.vtime>t)break;const o=s.vtime+s.vduration;o<=t&&t-o<=n&&(i=s)}return i?.viseme??"sil"}function ks(e,t,n=400){const r=t-n;let i=0;for(const s of e)if(s.vtime+s.vduration<r)i+=1;else break;i>0&&e.splice(0,i)}function xs(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function fr(e,t){const n=e.trim();if(!n)return null;try{const r=n.replace(/\s+/g,""),i=atob(r).length,s=Number.isFinite(t)&&(t??0)>0?Number(t):16e3;return i/2/s*1e3}catch{return null}}const on=.5,cn=1.5,Vn="Olivia",Un="f786b574-daa5-4673-aa0c-cbe3e8534c02",Ft=.85;function En(e,t=ot,n={}){const r=`${t.replace(/\/$/,"")}/avatar_ttsWithPoses`,i=[],s=[],o=[],a=[];let l=0;const f=[],u=[];let c="",d="neutral",p="",T=st;const m=new Set;let A=0,C=null,x=0,g=null;const E=()=>m.forEach(j=>j());let N=()=>!1;const I=ui({onSpeakingStart:()=>e("speaking"),onSpeakingDone:()=>e("done"),onNotify:E,shouldHoldForWarmup:()=>N()},st),te=()=>I.getPlaybackElapsedMs(),de=(j,Z=c)=>{if(!n.onLipsyncDebug)return;const M=te(),G=i,V=an(o).map(ue=>({viseme:ue.viseme,vtimeMs:ue.vtime}));n.onLipsyncDebug({event:j,spokenText:Z,mood:d,playbackAnchorPerf:I.getPlaybackStartPerf(),playbackElapsedMs:M,queueLength:G.length,activeViseme:Bt(G,M),segments:u.map(ue=>({...ue,visemes:[...ue.visemes]})),fullQueueLength:o.length,compactionSkipped:V})},P=(j,Z)=>{n.onLipsyncDebug&&(C={event:j,spokenText:Z},A===0&&(A=requestAnimationFrame(()=>{A=0;const M=C;C=null,M&&de(M.event,M.spokenText)})))},W=(j,Z,M,G,V)=>{if(!n.onLipsyncDebug)return;const ue=i.slice(Z),ne=M.filter(ae=>String(ae.symbol??ae.viseme??"").trim());u.push({spokenText:j,audioOffsetMs:ue[0]?.vtime??0,isNewSegment:G,chunkDurationMs:V,receivedAtMs:performance.now(),visemes:ue.map((ae,we)=>{const oe=ne[we];return{rawSymbol:String(oe?.symbol??oe?.viseme??ae.viseme).trim(),viseme:ae.viseme,startSec:Number(oe?.start??0),durationSec:Number(oe?.duration??0),vtimeMs:ae.vtime,vdurationMs:ae.vduration}})})},K=()=>{o.length=0,a.length=0,l=0},X=(j,Z,M,G,V)=>{if(j.length===0&&Z.length===0)return;si(o,a,j,Z,l,V);const ue=ai(j,l),ne=M?fr(M,G):null;l=Math.max(ue,ne!=null?l+ne:l)},Y=()=>{x+=1,g?.abort(),g=null,I.stop(),i.length=0,s.length=0,K(),f.length=0,d="neutral",u.length=0,c="",e("idle"),P("reset"),E()};return{setDeveloperToken:j=>{p=j},setTtsEngineId:j=>{T=j},getTtsEngineId:()=>T,speak:async(j,Z)=>{Y();const M=x;g=new AbortController,e("loading"),c=j,u.length=0,K();const G=p.trim();if(!G)throw new Error("Developer token required for avatar_ttsWithPoses");const V=Z?.ttsEngineId??T??st;I.resetForNewStream(V),I.setStreamTtsEngineId(V);const ue=Z?.voiceId??Vn,ne=Z?.speakingRate??Ft,ae=Math.max(on,Math.min(cn,ne)),we={user_query:j,ttsEngineId:V,speakingRate:ae,tenant:"aiTwin"};Fr.has(V)&&(we.voice_id=ue);try{const oe=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${G}`},body:JSON.stringify(we),signal:g.signal});if(!oe.ok)throw new Error(`avatar_ttsWithPoses failed (${oe.status})`);const S=oe.body;if(!S)throw new Error("No response body");const $=S.getReader(),b=new TextDecoder;let L="",B=!0;const O=async _=>{if(M!==x)return;const v=Kr(_);if(v){if(v.event==="audio"){const k=v.data.chunk,H=v.data.visemes??[],J=v.data.words??[],ie=v.data.is_new_segment??!1,xe=v.data.sample_rate,be=Number(v.data.audio_offset_ms??0),Re=i.length;if(X(H,J,k,xe,V),k){const De=B;B=!1,await I.playAudioChunk(i,s,k,H,J,ie,{sampleRate:xe,newStream:De,audioOffsetMs:be}),W(j,Re,H,ie,fr(k,xe)),P("audio_chunk",j)}else(H.length>0||J.length>0)&&(I.queueTimingsOnly(i,s,H,J,ie,{audioOffsetMs:be,newStream:B}),W(j,Re,H,ie,null),P("audio_chunk",j))}else if(v.event==="metadata"){const k=v.data.mood;typeof k=="string"&&k.trim()&&(d=k.trim());const H=v.data.sentence_emotions;if(Array.isArray(H)){f.length=0;for(const J of H){if(!J||typeof J!="object")continue;const ie=J;f.push({sentence_index:Number(ie.sentence_index??0),text:String(ie.text??""),sentiment:typeof ie.sentiment=="string"?ie.sentiment:void 0,emotion:String(ie.emotion??d),start_word:Number(ie.start_word??0),end_word:Number(ie.end_word??0)})}}E(),P("metadata",j)}else if(v.event==="error")throw new Error(String(v.data.message??"avatar_ttsWithPoses stream error"))}};for(;M===x;){const{done:_,value:v}=await $.read();v&&(L+=b.decode(v,{stream:!0}));const k=L.split(`
|
|
2
2
|
|
|
3
|
-
`);
|
|
3
|
+
`);L=k.pop()??"";for(const H of k)await O(H);if(_){L.trim()&&await O(L.trim()),I.markStreamComplete(i),P("bot_stopped",j);break}}}catch(oe){if(M!==x||oe instanceof DOMException&&oe.name==="AbortError")return;throw console.error("[avatarTtsLipsync]",oe),Y(),e("error"),oe}},stop:Y,getVisemeQueue:()=>i,getWordQueue:()=>s,getFullVisemeQueue:()=>o,getFullWordQueue:()=>a,getSentenceEmotions:()=>f,getStreamMood:()=>d,getPlaybackElapsedMs:()=>I.getPlaybackElapsedMs(),isSpeaking:()=>I.isSpeaking(),isWarmingUp:()=>I.isWarmingUp(),releaseWarmupHold:()=>I.releaseWarmupHold(),setLipsyncWarmupHold:(j,Z)=>{Z&&(N=Z),I.setLipsyncWarmupHoldEnabled(j)},getVoiceStream:()=>I.getVoiceStream(),setPlaybackSpeed:j=>{I.setPlaybackSpeed(j)},getPlaybackSpeed:()=>I.getPlaybackSpeed(),subscribe:j=>(m.add(j),()=>m.delete(j))}}const Wn=16e3,Hn=16e3;class Es extends Cn.ProtobufFrameSerializer{async deserialize(t){try{return await super.deserialize(t)}catch(n){if(n instanceof Error&&n.message==="Unknown frame kind")return{type:"raw",message:null};throw n}}}class Is extends Cn.DailyMediaManager{constructor(){super(!0,!0,void 0,void 0,512,Wn,Hn)}bufferBotAudio(t,n){}}const As=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ps(e){return As.test(e.trim())}function Ms(e){const t=e.replace(/\/$/,"");return t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t}function fi(e){if(e.wsUrl?.trim())return e.wsUrl.trim();const t=e.authToken?.trim();if(!t)throw new Error("Voice connect requires authToken (same JWT as SSE Authorization Bearer).");const n=e.apiBase??ot,r=new URL(`${Ms(n)}/ws/voice`);r.searchParams.set("authToken",t),r.searchParams.set("tenant","aiTwin");const i=e.voiceId?.trim();i&&Ps(i)&&r.searchParams.set("voiceId",i);const s=e.personaId?.trim();s&&r.searchParams.set("personaId",s);const o=e.speakingRate??Ft;return r.searchParams.set("speaking_rate",String(Math.max(on,Math.min(cn,o)))),e.ttsStream===!1?r.searchParams.set("tts_stream","false"):r.searchParams.set("tts_stream","true"),r.toString()}function yn(e,t){if(!Array.isArray(e))return[];const n=[];for(const r of e)!r||typeof r!="object"||n.push({sentence_index:Number(r.sentence_index??0),text:String(r.text??""),sentiment:typeof r.sentiment=="string"?r.sentiment:void 0,emotion:String(r.emotion??t),start_word:Number(r.start_word??0),end_word:Number(r.end_word??0)});return n}function Cs(e){if(!e||typeof e!="object")return null;const t=e,r=(t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:null)||t;return{...r,type:String(r.type??t.type??"server-message")}}function dr(e){return e.is_new_segment===!0||Number(e.audio_offset_ms??-1)===0?!0:Number(e.chunk_index??-1)===0}function Rs(e){return e?.transport?._mediaManager?._wavStreamPlayer??null}function di(e,t={}){const n=[],r=[],i=[],s=[];let o=0;const a=[],l=[];let f="",u="neutral",c=ct,d=!1,p=null,T=null,m={...t},A=0,C=null;const x=new Set,g=[];let E=!1,N=null,I=!0,te="default";const de=new Set;let P=null,W=0,K=!1,X=!1,Y=null,pe=!1;const j=()=>{Y!=null&&(clearTimeout(Y),Y=null)},Z=()=>{j(),Y=setTimeout(()=>{Y=null,I&&(V.markStreamComplete(n),oe("bot_stopped"))},450)},M=()=>x.forEach(h=>h());let G=()=>!1;const V=ui({onSpeakingStart:()=>e("speaking"),onSpeakingDone:()=>{pe=!1,X=!1,e("done")},onNotify:M,shouldHoldForWarmup:()=>G()},c),ue=()=>{if(N)return N;const h=new MessageChannel;return h.port1.onmessage=()=>{const R=g.shift();R!==void 0&&Re(R),g.length>0?h.port2.postMessage(null):E=!1},N=h,h},ne=h=>{g.push(h),!E&&(E=!0,ue().port2.postMessage(null))},ae=()=>V.getPlaybackElapsedMs(),we=(h,R=f)=>{if(!m.onLipsyncDebug)return;const ee=ae(),le=n,ve=an(i).map(ge=>({viseme:ge.viseme,vtimeMs:ge.vtime}));m.onLipsyncDebug({event:h,spokenText:R,mood:u,playbackAnchorPerf:V.getPlaybackStartPerf(),playbackElapsedMs:ee,queueLength:le.length,activeViseme:Bt(le,ee),segments:l.map(ge=>({...ge,visemes:[...ge.visemes]})),fullQueueLength:i.length,compactionSkipped:ve})},oe=(h,R)=>{m.onLipsyncDebug&&(C={event:h,spokenText:R},A===0&&(A=requestAnimationFrame(()=>{A=0;const ee=C;C=null,ee&&we(ee.event,ee.spokenText)})))},S=()=>{I=!0,de.clear(),V.clearAborted()},$=()=>{const h=Rs(p);if(h){te=`bot-${Date.now()}`,h.interruptedTrackIds={[te]:!0};try{h.interrupt?.()}catch{}}const R=T;try{R?.interrupt?.()}catch{}},b=h=>{if(pe&&V.isSpeaking())return!0;const R=h.context_id?.trim();return R&&de.has(R)?!0:I?!1:!(h.type==="avatar_metadata"||dr(h))},L=h=>{I=!1,pe=!1;const R=h.context_id?.trim();R&&de.add(R),j(),K=!1,X=!1,g.length=0,E=!1,P?.abort(),P=null,W+=1,$(),V.bargeIn(),B(),e("idle"),oe("interrupt"),M()},B=()=>{n.length=0,r.length=0,i.length=0,s.length=0,o=0,l.length=0,f="",u="neutral",a.length=0},O=()=>{j(),X=!1,K=!1,V.stop(),B(),oe("reset"),M()},_=()=>{O(),e("idle"),M()},v=(h,R)=>{typeof h.mood=="string"&&h.mood.trim()&&(u=h.mood.trim()),Array.isArray(h.sentence_emotions)&&h.sentence_emotions.length>0&&(R&&(a.length=0),a.push(...yn(h.sentence_emotions,u)))},k=h=>{if(b({...h,type:"avatar_metadata"}))return;S(),K=!0;const R=String(h.spoken_text??h.text??"").trim();R&&(f=R),V.resetForNewStream(c),typeof h.mood=="string"&&h.mood.trim()&&(u=h.mood.trim()),a.length=0,a.push(...yn(h.sentence_emotions,u)),Array.isArray(h.gestures)&&h.gestures,oe("metadata",R),M()},H=(h,R,ee,le)=>{if(!m.onLipsyncDebug)return;const ve=n.slice(ee),ge=le.filter(ye=>String(ye.symbol??ye.viseme??"").trim());l.push({spokenText:R,audioOffsetMs:ve[0]?.vtime??0,isNewSegment:!!h.is_new_segment,chunkDurationMs:h.chunk_duration_ms!=null?Number(h.chunk_duration_ms):null,receivedAtMs:performance.now(),visemes:ve.map((ye,Be)=>{const _e=ge[Be];return{rawSymbol:String(_e?.symbol??_e?.viseme??ye.viseme).trim(),viseme:ye.viseme,startSec:Number(_e?.start??0),durationSec:Number(_e?.duration??0),vtimeMs:ye.vtime,vdurationMs:ye.vduration}})})},J=(h,R,ee,le)=>{if(h.length===0&&R.length===0)return;si(i,s,h,R,o,c);const ve=ai(h,o);let ge=null;const ye=ee.trim();if(ye)try{const Be=atob(ye.replace(/\s+/g,"")).length,_e=Number.isFinite(le)&&(le??0)>0?Number(le):16e3;ge=Be/2/_e*1e3}catch{ge=null}o=Math.max(ve,ge!=null?o+ge:o)},ie=h=>{if(b(h))return;const R=dr(h);R&&(j(),S());const ee=String(h.spoken_text??h.text??"").trim(),le=h.visemes??[],ve=h.words??[],ge=String(h.chunk??"").trim(),ye=K||R||!X;K&&(K=!1),ye&&(X=!0),ee&&(f=ee),v(h,R),ye?(V.resetForNewStream(c),i.length=0,s.length=0,o=0):R&&V.resumeBotStream(),J(le,ve,ge,h.sample_rate);const Be=n.length;V.playAudioChunk(n,r,ge,le,ve,R,{sampleRate:h.sample_rate,newStream:ye,audioOffsetMs:Number(h.audio_offset_ms??0),onNewStream:()=>{l.length=0}}).then(()=>{H(h,ee,Be,le),oe("audio_chunk",ee),Z()})},xe=h=>{if(b(h))return;(h.is_new_segment||Number(h.audio_offset_ms??-1)===0)&&S(),console.warn("[realtimeVoice] avatar_lipsync is deprecated — expect avatar_audio_chunk");const R=String(h.spoken_text??h.text??"").trim();R&&(f=R),v(h,!!h.is_new_segment),J(h.visemes??[],h.words??[],"",void 0);const ee=n.length;V.queueTimingsOnly(n,r,h.visemes??[],h.words??[],!!h.is_new_segment,{audioOffsetMs:Number(h.audio_offset_ms??0)}),H(h,R,ee,h.visemes??[]),oe("lipsync",R),M()},be=async h=>{const R=String(h.text??"").trim();if(!R)return;const ee=m.authToken?.trim();if(!ee){console.error("[realtimeVoice] avatar_speak requires authToken");return}P?.abort();const le=new AbortController;P=le;const ve=++W;S(),V.resetForNewStream(c),f=R;const ye=`${(m.apiBase??ot).replace(/\/$/,"")}/avatar_ttsWithPoses`,Be=m.voiceId?.trim()||Un,_e=m.speakingRate??Ft,ze=Math.max(on,Math.min(cn,_e)),Xe={user_query:R,ttsEngineId:c,speakingRate:ze,tenant:"aiTwin"};Fr.has(c)&&(Xe.voice_id=Be);try{const Fe=await fetch(ye,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ee}`},body:JSON.stringify(Xe),signal:le.signal});if(!Fe.ok)throw new Error(`avatar_ttsWithPoses failed (${Fe.status})`);const Tt=Fe.body;if(!Tt)throw new Error("No response body");const Je=Tt.getReader(),Ue=new TextDecoder;let Ee="",Ze=!0;const et=async tt=>{if(ve!==W||le.signal.aborted||!I)return;const Se=Kr(tt);if(Se){if(Se.event==="audio"){const re=Se.data.chunk,Ne=Se.data.visemes??[],ft=Se.data.words??[],kt=Se.data.is_new_segment??!1,dt=Se.data.sample_rate,xt=Number(Se.data.audio_offset_ms??0);if(re){const qe=Ze;Ze=!1,await V.playAudioChunk(n,r,re,Ne,ft,kt,{sampleRate:dt,newStream:qe,audioOffsetMs:xt})}else(Ne.length>0||ft.length>0)&&V.queueTimingsOnly(n,r,Ne,ft,kt,{audioOffsetMs:xt,newStream:Ze})}else if(Se.event==="metadata"){const re=Se.data.mood;typeof re=="string"&&re.trim()&&(u=re.trim());const Ne=Se.data.sentence_emotions;Array.isArray(Ne)&&(a.length=0,a.push(...yn(Ne,u))),M()}else if(Se.event==="error")throw new Error(String(Se.data.message??"avatar_ttsWithPoses stream error"))}};for(;!(ve!==W||le.signal.aborted||!I);){const{done:tt,value:Se}=await Je.read();Se&&(Ee+=Ue.decode(Se,{stream:!0}));const re=Ee.split(`
|
|
4
4
|
|
|
5
|
-
`);We=Me.pop()??"";for(const He of Me)await Le(He);if(et){We.trim()&&await Le(We.trim()),Se===W&&!ce.signal.aborted&&A&&k.markStreamComplete(n);break}}}catch(Pe){if(ce.signal.aborted||!A)return;console.error("[realtimeVoice] avatar_speak failed:",Pe),e("error"),F()}finally{M===ce&&(M=null)}},Ee=h=>{const L=Ms(h);if(!L){console.warn("[realtimeVoice] server message with no payload",h);return}const J=String(L.type??"unknown");switch(J!=="avatar_metadata"&&J!=="avatar_audio_chunk"&&J!=="avatar_lipsync"&&J!=="avatar_interrupt"&&J!=="error"&&console.debug("[realtimeVoice] server message",J,L),J){case"avatar_metadata":_(L);break;case"avatar_audio_chunk":H(L);break;case"avatar_lipsync":X(L);break;case"avatar_interrupt":$(L);break;case"error":{const ce=String(L.message??"Voice session error");console.error("[realtimeVoice] server error:",ce),e("error"),F();break}case"avatar_speak":se(L);break}},_e=()=>p||(T=new Es,p=new Fi.PipecatClient({transport:new Rn.WebSocketTransport({mediaManager:T,serializer:new xs,recorderSampleRate:Hn,playerSampleRate:$n}),enableCam:!1,enableMic:!0,callbacks:{onBotReady:()=>{d=!0,e("idle"),F()},onDisconnected:()=>{d=!1,D()},onError:h=>{const L=typeof h=="object"&&h!==null&&"data"in h?String(h.data??h):String(h);console.error("[realtimeVoice]",L,h),e("error"),F()},onTransportStateChanged:h=>{h==="error"&&(e("error"),F())},onServerMessage:h=>{re(h)},onUserStartedSpeaking:()=>{},onBotStartedSpeaking:()=>{ie(),te("bot_started")},onBotStoppedSpeaking:()=>{A&&(de(),Q=setTimeout(()=>{Q=null,A&&(k.markStreamComplete(n),te("bot_stopped"))},450))},onUserTranscript:h=>{String(h.text??""),m.onUserTranscript?.(h.text,!!h.final)},onBotOutput:h=>{m.onBotOutput?.(h.text)}}}),p);return{setDeveloperToken:h=>{},setTtsEngineId:h=>{c=h,k.setStreamTtsEngineId(h)},getTtsEngineId:()=>c,speak:async(h,L)=>{const J=h.trim();if(J){if(!p||!d)throw new Error("Realtime voice is not connected. Call connect() first.");O(),await p.sendText(J)}},stop:()=>{M?.abort(),M=null,W+=1,ie(),O(),e("idle"),F()},connect:async h=>{if(h&&(m={...m,...h}),!m.authToken?.trim())throw new Error("Voice connect requires authToken (same JWT as SSE Authorization Bearer).");e("loading");const L=_e();await L.initDevices();const J=li(m);console.info("[realtimeVoice] connecting (avatar_audio_chunk RTVI):",J);try{await L.connect({wsUrl:J})}catch(ce){d=!1,e("error"),F();const Se=ce instanceof Error?ce.message:"Realtime voice connect failed (WebSocket 101 only means upgrade OK — check authToken/origin/RTVI handshake)";throw new Error(`${Se} — ${J}`)}d=!0,e("idle"),F()},disconnect:async()=>{if(de(),K=!1,g.length=0,I=!1,M?.abort(),M=null,W+=1,ie(),p)try{await p.disconnect()}catch(h){console.error("[realtimeVoice] disconnect failed:",h)}d=!1,D()},isConnected:()=>d,unlockAudio:async()=>{await k.primeAudioContext()},getVisemeQueue:()=>n,getWordQueue:()=>r,getFullVisemeQueue:()=>i,getFullWordQueue:()=>s,getSentenceEmotions:()=>a,getStreamMood:()=>u,getPlaybackElapsedMs:oe,isSpeaking:()=>k.isSpeaking(),isWarmingUp:()=>k.isWarmingUp(),releaseWarmupHold:()=>k.releaseWarmupHold(),setLipsyncWarmupHold:(h,L)=>{L&&(Z=L),k.setLipsyncWarmupHoldEnabled(h)},getVoiceStream:()=>k.getVoiceStream(),setPlaybackSpeed:h=>{k.setPlaybackSpeed(h)},getPlaybackSpeed:()=>k.getPlaybackSpeed(),subscribe:h=>(E.add(h),()=>E.delete(h))}}function di(e,t,n){return{width:e.crop?.source_width??t,height:e.crop?.source_height??n}}function mi(e,t){const n=e.crop;return{x:t?.source_x??n?.x??0,y:t?.source_y??n?.y??0,width:t?.source_w??n?.width??e.frame_width??0,height:t?.source_h??n?.height??e.frame_height??0}}function hi(e){return e?(e.w??0)>0&&(e.h??0)>0:!1}async function bt(e,t){const n=await fetch(e);if(!n.ok)throw new Error(`Failed to load encrypted asset: ${e}`);const r=await n.arrayBuffer();return ns(r,t)}async function pi(e,t){if(!t)throw new Error("Missing asset key for encrypted JSON");const n=await bt(e,t),r=new TextDecoder().decode(n);return JSON.parse(r)}async function Rs(e){const t=new Blob([e],{type:"image/webp"});return createImageBitmap(t)}async function Ds(e){const t=new Blob([e],{type:"image/webp"}),n=URL.createObjectURL(t);return new Promise((r,i)=>{const s=new Image;s.decoding="async",s.onload=()=>{URL.revokeObjectURL(n),r(s)},s.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to decode decrypted image"))},s.src=n})}async function Bs(e){const t=new Blob([e],{type:"image/png"});return createImageBitmap(t)}async function Fs(e){const t=new Blob([e],{type:"image/png"}),n=URL.createObjectURL(t);return new Promise((r,i)=>{const s=new Image;s.decoding="async",s.onload=()=>{URL.revokeObjectURL(n),r(s)},s.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to decode decrypted PNG"))},s.src=n})}function Ls(e){const t=new Blob([e],{type:"video/mp4"});return URL.createObjectURL(t)}async function Os(e){const t=is();if(!Rt())return t;if(!e)throw new Error("Missing asset key for encrypted idle video");const n=await bt(t,e);return Ls(n)}function gt(e,t){return`${e}/${t}_minus_sil.png`}const wi=5;function ln(e){const t=e?.composite_threshold;if(typeof t=="number"&&t>0)return t;const n=e?.crop?.content_threshold;return typeof n=="number"&&n>0?n:wi}const Ns=["aa","E","I","O","U","PP","FF","DD","SS","TH","CH","RR","kk","nn"],An=["t01_0.25","t02_0.50","t03_0.75"],Vs=An.length,dr=new Set(["aa__kk","aa__nn","aa__sil","CH__aa","CH__DD","CH__E","CH__FF","CH__I","CH__kk","CH__nn","CH__O","CH__PP","CH__RR","CH__sil","CH__SS","CH__TH","CH__U","DD__aa","DD__E","DD__FF","DD__I","DD__kk","DD__nn","DD__O","DD__PP","DD__RR","DD__sil","DD__SS","DD__TH","DD__U","E__aa","E__FF","E__I","E__kk","E__nn","E__O","E__PP","E__RR","E__sil","E__SS","E__TH","E__U","FF__aa","FF__I","FF__kk","FF__nn","FF__O","FF__PP","FF__RR","FF__sil","FF__SS","FF__TH","FF__U","I__aa","I__kk","I__nn","I__O","I__PP","I__RR","I__sil","I__SS","I__TH","I__U","kk__nn","kk__sil","nn__sil","O__aa","O__kk","O__nn","O__PP","O__RR","O__sil","O__SS","O__TH","O__U","PP__aa","PP__kk","PP__nn","PP__RR","PP__sil","PP__SS","PP__TH","PP__U","RR__aa","RR__kk","RR__nn","RR__sil","RR__SS","RR__TH","RR__U","SS__aa","SS__kk","SS__nn","SS__sil","SS__TH","SS__U","TH__aa","TH__kk","TH__nn","TH__sil","TH__U","U__aa","U__kk","U__nn","U__sil"]);function mr(e,t){return`${e}__${t}`}function hr(e,t){return`pairs/${e}/${t}_minus_sil.png`}function _t(e){return`${e}_minus_sil.png`}function zn(e,t){if(t.has(e))return e;const n=/^pairs\/([^/]+)\//.exec(e);if(!n)return null;const r=n[1].split("__")[1];if(!r||r==="sil")return null;const i=_t(r);return t.has(i)?i:null}function gi(e,t){return e.filter(n=>t.has(n))}function Us(e,t,n){const r=Kn(e,t);return gi(r,n).length>0}function Kn(e,t){if(e===t)return[];const n=[],r=mr(e,t);if(dr.has(r)){for(const s of An)n.push(hr(r,s));return n}const i=mr(t,e);if(dr.has(i)){for(let s=Vs-1;s>=0;s--)n.push(hr(i,An[s]));return n}return[]}function Ws(e){return e<16?[1]:e<24?[1]:e<35?[0,1,2]:[0,1,2]}function Hs(e,t){return Ws(t).map(r=>e[r]).filter(r=>r!=null)}function $s(e,t,n,r){if(r<=0)return 0;const s=Math.max(1,n-t)/r,o=e-t,a=Math.floor(o/s);return Math.min(r-1,Math.max(0,a))}function yi(e,t,n){if(!n)return`${e}/${t}`;const r=t.split("/").pop()??t,i=r.includes(".")?r.slice(0,r.lastIndexOf(".")):r;return`${e}/${i}.bin`}const zs=[.32,.24,.16,.08,0],Ks=zs.map(e=>`eyes_${e.toFixed(2)}`),js=["eyes_0.32","eyes_0.16","eyes_0.00"],qs=["eyes_0.32","eyes_0.16","eyes_0.08","eyes_0.00"],$e=2,Gs=-20,Jt=16,_i={fear:-20,anger:-20,sad:-10,neutral:0,love:0,happy:0,disgust:10};function Mt(e){return`brow_${e}`}function st(e){return _i[e]}function je(e){return Math.max(Gs,Math.min(Jt,e))}function Ys(e,t){if(e===t)return[];const n=e<t,r=n?$e:-$e,i=[];let s=e;if(s%$e!==0){const o=n?Math.ceil(s/$e)*$e:Math.floor(s/$e)*$e,a=je(o);if(n?a>=t:a<=t)return[t];s=a,i.push(s)}for(;;){const o=s+r;if(n?o>=t:o<=t){t!==s&&i.push(t);break}s=o,i.push(s)}return i}function pr(e){const t=je(e);if(t%$e===0)return[t];const n=Math.floor(t/$e)*$e,r=Math.min(Jt,n+$e),i=je(n);return t-i<=r-t?i===r?[i]:[i,r]:i===r?[r]:[r,i]}const Qs=["fear","anger","sad","neutral","love","happy","disgust"],Xs={fear:"fear",afraid:"fear",anxiety:"fear",anger:"anger",angry:"anger",mad:"anger",sad:"sad",sadness:"sad",sorrow:"sad",neutral:"neutral",calm:"neutral",love:"love",loving:"love",affection:"love",happy:"happy",happiness:"happy",joy:"happy",joyful:"happy",excited:"happy",disgust:"disgust",disgusted:"disgust"};function Ge(e,t="neutral"){const n=String(e??"").trim().toLowerCase();return n?Xs[n]??t:t}function vi(e){return e===0?null:gt(Mt(e),"eyes_standard")}function Si(e){return vi(st(e))}const Js={[-20]:"anger",[-10]:"sad",0:"neutral",10:"disgust"};function jn(e,t){if(!e)return null;if(t(e))return e;const n=e.match(/^brow_(-?\d+)\/(eyes_[^/]+)_minus_sil\.png$/);if(n){const i=Number(n[1]),s=n[2];for(const a of pr(i)){if(a===i)continue;const l=gt(Mt(a),s);if(t(l))return l}const o=Js[i];if(o){const a=gt(o,s);if(t(a))return a}return null}const r=e.match(/^(fear|anger|sad|neutral|love|happy|disgust)\/(eyes_[^/]+)_minus_sil\.png$/);if(r){const i=r[1],s=r[2],o=st(i);for(const a of[o,...pr(o)]){const l=gt(Mt(a),s);if(t(l))return l}}return null}function wr(e,t){const n=Mt(st(e));return!t||t==="eyes_standard"?Si(e):e==="neutral"&&t==="eyes_standard"?null:gt(n,t)}function Zs(e,t){const n=[];for(const r of t)n.push(wr(e,r));for(let r=t.length-2;r>=0;r--)n.push(wr(e,t[r]));return n.push(Si(e)),n}function ea(e){return gt(Mt(e),"eyes_standard")}function ta(e,t){return Ys(e,t).map(ea)}const na=6;function ra(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function ia(e){const t=je(e);return t>=Jt?Jt:je(t+na)}function sa(e,t,n){const r=je(n);return ra(t,e)?.emphasis?ia(r):r}function gr(e){if(!e)return 0;const t=e.match(/^brow_(-?\d+)\//);if(!t?.[1])return null;const n=Number.parseInt(t[1],10);return Number.isFinite(n)?je(n):null}function wt(e,t){return e+Math.random()*(t-e)}function jt(){return wt(14,32)}function aa(e={}){const{initialDelayMs:t=800+Math.random()*1200,intervalMinMs:n=2200,intervalMaxMs:r=5800,doubleBlinkChance:i=.18,doubleBlinkGapMinMs:s=120,doubleBlinkGapMaxMs:o=220,fullBlinkChance:a=.75,postEmotionChangeDelayMs:l=380,minDwellMs:f=550}=e;let u="neutral",c="neutral",d=0,p=0,T=0,m={kind:"idle",nextBlinkAt:performance.now()+t},P=null,C="__eyes_open__|neutral|brow:0";function E(M=u){C=`${P??"__eyes_open__"}|${M}|brow:${p}`}function g(M,W=u){P=M;const K=gr(M);K!=null?p=K:M==null&&(p=0),E(W)}function I(M){return vi(M)}function N(M,W,K){const Q=je(W),Y=je(K);if(d=Y,Q===Y){g(I(Y));return}const de=[...ta(Q,Y),I(Y)];m={kind:"browBlend",paths:de,index:0,holdUntil:M+jt(),targetBrow:Y},g(de[0]??null)}function A(M,W){m={kind:"idle",nextBlinkAt:M+wt(n,r)},c=W,g(I(d),W)}function ee(M,W,K){const Q=K?js:Math.random()<a?Ks:qs;m={kind:"playing",paths:Zs(W,Q),index:0,holdUntil:M+jt(),after:"idle",blinkEmotion:W},c=W,g(m.paths[0]??null,W)}function fe(M){if(m.kind==="browBlend"){for(;M>=m.holdUntil&&m.index<m.paths.length-1;)m.index+=1,m.holdUntil=M+jt();const W=m.paths[m.index]??null;g(W),M>=m.holdUntil&&m.index>=m.paths.length-1&&(p=m.targetBrow,d=m.targetBrow,g(I(m.targetBrow)),m={kind:"idle",nextBlinkAt:M+l});return}if(m.kind==="idle"){g(I(d),c),M>=m.nextBlinkAt&&ee(M,c,!1);return}if(m.kind==="doublePause"){g(I(d),m.blinkEmotion),M>=m.resumeAt&&ee(M,m.blinkEmotion,!0);return}if(m.kind==="playing"){for(;M>=m.holdUntil&&m.index<m.paths.length-1;)m.index+=1,m.holdUntil=M+jt();if(g(m.paths[m.index]??null,m.blinkEmotion),M>=m.holdUntil&&m.index>=m.paths.length-1){if(m.after==="resumeIdle"){A(M+l,u);return}if(m.after==="doublePause"){m={kind:"doublePause",resumeAt:M+wt(s,o),blinkEmotion:m.blinkEmotion},g(I(d),m.blinkEmotion);return}if(m.after==="idle"&&Math.random()<i){m={kind:"doublePause",resumeAt:M+wt(s,o),blinkEmotion:m.blinkEmotion},g(I(d),m.blinkEmotion);return}A(M,m.blinkEmotion)}}}return{advance:fe,setTargetEmotion(M,W){const K=Ge(M,u);if(K===u)return;const Q=performance.now();!W?.force&&f>0&&!(u==="neutral"&&K!=="neutral")&&Q-T<f||(u=K,c=K,T=Q)},setTargetEyebrow(M){const W=je(M);if(W===d)return;const K=performance.now(),Q=m.kind==="browBlend"?gr(P)??p:p;d=W,!(W===Q&&m.kind!=="browBlend")&&(m.kind==="playing"||m.kind==="doublePause"||N(K,Q,W))},snapToEmotion(M){const W=Ge(M),K=st(W);u=W,c=W,d=K,p=K,T=performance.now(),m={kind:"idle",nextBlinkAt:performance.now()+wt(4e3,7e3)},g(I(K),W)},getTargetEmotion:()=>u,getTargetEyebrow:()=>d,getExpressionPath:()=>P,getDrawKey:()=>C,reset(){u="neutral",c="neutral",d=0,p=0,T=0,A(performance.now()+wt(n,r),"neutral")}}}function oa(){const e=document.createElement("video");e.muted=!0,e.playsInline=!0,e.preload="auto",e.setAttribute("playsinline",""),e.loop=!0;let t=!1,n=null,r="";const i=()=>{n&&(URL.revokeObjectURL(n),n=null)};return{async load(s){t&&r===s||(i(),t=!1,r=s,s.startsWith("blob:")&&(n=s),await new Promise((o,a)=>{const l=()=>{const f=e.duration;if(!Number.isFinite(f)||f<=0){a(new Error(`Idle video has invalid duration: ${s}`));return}t=!0,e.currentTime=0,o()};e.addEventListener("loadeddata",l,{once:!0}),e.addEventListener("error",()=>a(new Error(`Failed to load idle video: ${s}`)),{once:!0}),e.src=s,e.load()}))},isReady(){return t},getVideo(){return e},setActive(s){t&&(s?e.paused&&e.play().catch(()=>{}):e.paused||e.pause())},restart(){t&&(e.currentTime=0)},dispose(){e.pause(),e.removeAttribute("src"),e.load(),i(),t=!1,r=""}}}const ca=50,bi=400;function ua(e,t,n){return e.filter(r=>{const i=r.queueIndex??-1;return i>=t&&i<=n})}function la(e,t){const n=[];for(const r of e){const i=ua(t,r.start_word,r.end_word);if(i.length===0)continue;const s=i[0],o=i[i.length-1];n.push({sentence:r,startMs:Math.max(0,s.wtime-ca),endMs:o.wtime+o.wduration+bi})}return n.sort((r,i)=>r.startMs-i.startMs)}function fa(e,t,n,r="neutral"){const i=Ge(r);if(t.length===0)return i;if(n.length===0||e<n[0].wtime)return Ge(t[0]?.emotion,i);const s=la(t,n);let o=null;for(const f of s)e>=f.startMs&&e<=f.endMs&&(o=f);if(o)return Ge(o.sentence.emotion,i);const a=n[n.length-1],l=a.wtime+a.wduration;return e>l+bi?Ge(t[t.length-1]?.emotion,i):i}function qn(e,t,n,r,i=wi){const s=new OffscreenCanvas(n,r),o=s.getContext("2d",{willReadFrequently:!0});o.drawImage(e,0,0,n,r);const a=o.getImageData(0,0,n,r),l=o.createImageData(n,r);l.data.set(a.data);const u=new OffscreenCanvas(n,r).getContext("2d",{willReadFrequently:!0});for(const c of t){u.clearRect(0,0,n,r),u.drawImage(c,0,0,n,r);const d=u.getImageData(0,0,n,r);for(let p=0;p<l.data.length;p+=4){const T=d.data[p],m=d.data[p+1],P=d.data[p+2];Math.max(T,m,P)>i&&(l.data[p]=T,l.data[p+1]=m,l.data[p+2]=P,l.data[p+3]=255)}}return o.putImageData(l,0,0),s}let rt=null,vt=null;const Zt=new Map;function da(){rt=null,vt=null,Zt.clear()}Ur(da);function ma(e){return e??vt??void 0}function Gn(e){return new Promise((t,n)=>{const r=new Image;r.decoding="async",r.onload=()=>t(r),r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}async function ha(e){return Rt()?Fs(await bt(Xt(),e??"")):Gn(Xt())}async function yr(e,t,n,r){const i=n?await pi(e,r):await fetch(e).then(f=>{if(!f.ok)throw new Error(`Failed to load ${e}`);return f.json()}),s=i.sheets?.[0];if(!s?.path)throw new Error(`${e} has no sheets[0].path`);const o=n?await Ds(await bt(yi(t,s.path,n),r??"")):await Gn(`${t}/${s.path}`),a=new Map;for(const f of i.cells??[])f.path&&a.set(f.path,f);const l=new Map;for(const f of i.sheets??[])l.set(f.index,f);return{atlas:o,atlasMeta:i,cellByPath:a,sheetByIndex:l,diffBase:t}}async function Pn(e){const t=ma(e),n=Rt();if(n&&!t)throw new Error("Encrypted assets enabled but no key provided");if(rt&&(!n||vt===(t??null))){const s=await rt;return{...St(s),visemePaths:[...s.viseme.cellByPath.keys()]}}vt=t??null,Zt.clear();const r=Wr();rt=(async()=>{const s=await ha(t),o=await yr(Hr(),r,n,t);let a=null;try{a=await yr($r(),r,n,t)}catch{a=null}return{sil:s,viseme:o,expression:a}})();const i=await rt;return{...St(i),visemePaths:[...i.viseme.cellByPath.keys()]}}async function Yn(e){if(await Pn(e),!rt)throw new Error("Assets not loaded");return rt}function St(e){return di(e.viseme.atlasMeta,e.sil.naturalWidth,e.sil.naturalHeight)}function pa(e,t){const n=document.createElement("canvas");return n.width=t.w,n.height=t.h,n.getContext("2d",{willReadFrequently:!0}).drawImage(e.atlas,t.x,t.y,t.w,t.h,0,0,t.w,t.h),n}async function en(e,t,n){const r=`${t.diffBase}::${n}`,i=Zt.get(r);if(i)return i;const s=(async()=>{const o=t.cellByPath.get(n);if(!o)throw new Error(`No atlas cell for path: ${n}`);const a=mi(t.atlasMeta,o),l=St(e);if(hi(o)){const c=pa(t,o),d=document.createElement("canvas");d.width=l.width,d.height=l.height;const p=d.getContext("2d");return p.fillStyle="#000",p.fillRect(0,0,l.width,l.height),p.drawImage(c,a.x,a.y),d}const f=`${t.diffBase}/${n}`,u=await Gn(f);if(u.naturalWidth===l.width&&u.naturalHeight===l.height)return u;throw new Error(`Diff PNG wrong size for ${n}`)})();return Zt.set(r,s),s}async function vn(e,t,n,r,i,s){if(i){const{width:p,height:T}=i;if(s&&!s()||t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)return;const m=document.createElement("canvas");m.width=p,m.height=T;const P=m.getContext("2d");if(P.clearRect(0,0,p,T),P.drawImage(t,0,0,p,T),s&&!s())return;(e.width!==p||e.height!==T)&&(e.width=p,e.height=T);const C=e.getContext("2d");C.clearRect(0,0,p,T),C.drawImage(m,0,0);return}const o=await Yn(),a=ln(o.viseme.atlasMeta),{width:l,height:f}=St(o);(e.width!==l||e.height!==f)&&(e.width=l,e.height=f);const u=[],c=e.getContext("2d");if(c.clearRect(0,0,l,f),t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){const p=o.sil;c.drawImage(p,0,0,l,f);return}if(u.length===0){c.drawImage(t,0,0,l,f);return}const d=qn(t,u,l,f,a);c.drawImage(d,0,0)}async function Mn(e,t,n){const r=await Yn(vt??void 0),i=ln(r.viseme.atlasMeta),{width:s,height:o}=St(r);(e.width!==s||e.height!==o)&&(e.width=s,e.height=o);const a=[];if(t.mouthPath){const u=new Set(r.viseme.cellByPath.keys()),c=zn(t.mouthPath,u)??(u.has(t.mouthPath)?t.mouthPath:null);c&&a.push(await en(r,r.viseme,c))}if(t.expressionPath&&r.expression){const u=jn(t.expressionPath,c=>r.expression.cellByPath.has(c));u&&a.push(await en(r,r.expression,u))}const l=e.getContext("2d");if(l.clearRect(0,0,s,o),a.length===0){l.drawImage(r.sil,0,0,s,o);return}const f=qn(r.sil,a,s,o,i);l.drawImage(f,0,0)}async function wa(e,t){const n=await Yn(vt??void 0),r=ln(n.viseme.atlasMeta),{width:i,height:s}=St(n),o=[];if(e.mouthPath){const u=new Set(n.viseme.cellByPath.keys()),c=zn(e.mouthPath,u)??(u.has(e.mouthPath)?e.mouthPath:null);c&&o.push(await en(n,n.viseme,c))}if(e.expressionPath&&n.expression){const u=jn(e.expressionPath,c=>n.expression.cellByPath.has(c));u&&o.push(await en(n,n.expression,u))}const a=new OffscreenCanvas(i,s),l=a.getContext("2d");if(o.length===0)return l.drawImage(n.sil,0,0,i,s),a.transferToImageBitmap();const f=qn(n.sil,o,i,s,r);return l.drawImage(f,0,0),a.transferToImageBitmap()}async function ga(e){await Mn(e,{mouthPath:null,expressionPath:null})}const qt={fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"clamp(0.875rem, 2.5vw, 1.125rem)",color:"rgba(255,255,255,0.85)"};function ya(e){return e.length===0?"":e.map(t=>t.word).join(" ")}function _a(e){if(!e)return{enabled:!1,style:qt};const t=e===!0?{}:e;return{enabled:!0,style:{fontFamily:t.fontFamily??qt.fontFamily,fontSize:t.fontSize??qt.fontSize,color:t.color??qt.color}}}const va={position:"absolute",bottom:0,left:0,right:0,display:"flex",justifyContent:"center",padding:"0.75rem 1rem",pointerEvents:"none"},Sa={display:"inline-block",maxWidth:"100%",padding:"0.45rem 0.85rem",borderRadius:"0.75rem",background:"rgba(0,0,0,0.55)",lineHeight:1.4,textAlign:"center"},ba={display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",maxWidth:"100%",margin:0};function Ta({text:e,style:t}){return z.jsx("div",{style:va,"aria-live":"polite","aria-atomic":"true",children:z.jsx("div",{style:{...Sa,fontFamily:t.fontFamily,fontSize:t.fontSize,color:t.color},children:z.jsx("p",{style:ba,children:e})})})}let Ti=null;function _r(e){Ti=e}function Je(){return Ti}function ka(e){return`${e.from}→${e.to}@${e.fromVtime}`}function vr(){return{rafTicksSpeaking:0,rafTicksDeduped:0,drawsRequested:0,drawsDisplayed:0,queueSuperseded:0,workerStale:0,rifeFramesOmittedByGap:0,transitionFramesSampled:0,transitionFramesDisplayed:0,transitionFramesMissed:0,bufferTicks:0,bufferHits:0,bufferUnderruns:0,bufferPrefetched:0}}function xa(){let e=vr();const t=new Set,n=new Set,r=new Set;let i="",s=-1,o="";const a=()=>{e=vr(),t.clear(),n.clear(),r.clear(),i="",s=-1,o=""},l=u=>{t.add(u)},f=u=>{u&&r.add(u)};return{reset:a,onRafTickSpeaking(){e.rafTicksSpeaking+=1},onDrawDeduped(){e.rafTicksDeduped+=1},onDrawRequested(){e.drawsRequested+=1},onQueueSuperseded(){e.queueSuperseded+=1},onWorkerStale(){e.workerStale+=1},onTransitionSample(u,c){const d=ka(u);e.transitionFramesSampled+=1,d!==i&&(i=d,s=-1,o!==d&&(o=d,e.rifeFramesOmittedByGap+=u.omittedByGap)),c&&n.add(c),s>=0&&u.frameIdx>s+1&&(e.transitionFramesMissed+=u.frameIdx-s-1),s=u.frameIdx},onBufferTick(){e.bufferTicks+=1},onBufferHit(){e.bufferHits+=1},onBufferUnderrun(){e.bufferUnderruns+=1},onBufferPrefetched(){e.bufferPrefetched+=1},onBufferReset(){},onDrawDisplayed(u,c){if(e.drawsDisplayed+=1,u.transitionMeta){e.transitionFramesDisplayed+=1;const p=u.transitionMeta;l(p.fromVtime),l(p.toVtime),f(u.mouthPath);return}if(u.label.includes("→")){e.transitionFramesDisplayed+=1;return}const d=u.label.trim();if(!(!d||d==="sil")){for(const p of c)if(p.viseme===d&&u.elapsedMs>=p.vtime&&u.elapsedMs<p.vtime+p.vduration){l(p.vtime);break}}},snapshot(u,c){let d=0,p=0;for(const E of u)if(E.viseme!=="sil"){if(E.vtime>=c)break;d+=1,t.has(E.vtime)&&(p+=1)}const T=d>0?Math.round(p/d*100):100,m=e.queueSuperseded+e.workerStale+Math.max(0,e.drawsRequested-e.drawsDisplayed),P=d-p,C=e.bufferTicks>0?Math.round(e.bufferHits/e.bufferTicks*100):100;return{...e,bufferHitRate:C,renderLoss:m,visemeSlotsTotal:d,visemeSlotsCovered:p,visemeCoveragePct:T,transitionFramesUniqueSampled:n.size,transitionFramesUniquePainted:r.size,drawsDeduped:e.rafTicksDeduped,renderSkips:e.rafTicksDeduped+m,visemesShown:p,visemesSkipped:P,rifeTransitionFramesSkipped:e.transitionFramesMissed}}}}const ki=Bn,Ea=200,Sr=300,Ia=100,Aa=600,xi="__sil__";function br(e){return e.lastDrawnKey?e.lastDrawnKey.split("|")[0]===xi:!1}function Qn(){return{lastDrawnKey:""}}function Be(e){e.lastDrawnKey="",e.transitionCache=void 0}function Pa(e,t){if(t?.transitionCache&&t.transitionCache.queueLength===e.length)return t.transitionCache.transitions;const n=ni(e);return t&&(t.transitionCache={queueLength:e.length,transitions:n}),n}function Ma(e,t){let n="sil";for(const r of e)r.viseme!=="sil"&&(t!=null&&r.vtime>t||(n=r.viseme));return n}function Ca(e,t,n,r=120){if(n!=="sil")return n;const i=ui(e,t,r);return i!=="sil"?i:Ma(e,t)}function Ra(e,t){return e==="sil"?!1:t?Us(e,"sil",t):Kn(e,"sil").length>0}function Da(){return ki+Aa}function tn(e){return e??xi}function Xn(e,t,n,r,i=Ia){if(e.length===0)return{diffPath:null,label:"sil"};if(t>=nt(e))return{diffPath:null,label:"sil"};const s=Pa(e,r),o=_s(s,t);if(o){const f=ri(o.fromVtime,o.toVtime,o.from,o.to);if(t>=f.transStart&&t<f.transEnd){let u=Kn(o.from,o.to);n&&(u=gi(u,n));const c=Hs(u,f.effectiveGapMs);if(c.length>0){const d=$s(t,f.transStart,f.transEnd,c.length);return{diffPath:c[d]??c[c.length-1],label:`${o.from}→${o.to}`,transitionMeta:{from:o.from,to:o.to,fromVtime:o.fromVtime,toVtime:o.toVtime,frameIdx:d,frameCount:c.length,fullFrameCount:u.length,omittedByGap:Math.max(0,u.length-c.length)}}}return{diffPath:_t(o.to),label:o.to}}}const a=an(e);let l=Jr(a,t);return l==="sil"&&(l=ui(e,t,i)),l==="sil"?{diffPath:null,label:"sil"}:{diffPath:_t(l),label:l}}function Ct(e,t){const n=t??tn(e.expressionPath);return`${tn(e.mouthPath)}|${n}`}function Tr(e,t,n,r,i,s,o,a,l,f){const u=Xn(t,n,l,s),c={mouthPath:u.diffPath,expressionPath:r},d=Ct(c,i),p=Je();if(u.transitionMeta&&p?.onTransitionSample(u.transitionMeta,u.diffPath),d===s.lastDrawnKey){p?.onDrawDeduped();return}p?.onDrawRequested(),a(u),s.lastDrawnKey=d,o(e,c,d,T=>{T===d&&(s.lastDrawnKey=d)})}function Sn(e,t,n,r,i,s,o=null,a=null){const l={mouthPath:a,expressionPath:t},f=o!=null?`|idle@${Math.round(o*1e3)}`:"",u=Ct(l,n)+f;!(o!=null)&&u===r.lastDrawnKey||(s(o!=null?t?"idle · blink":"idle":t?"blink":"sil"),i(e,l,u,d=>{d===u&&(r.lastDrawnKey=u)}))}function Ei(e,t,n,r,i=At,s){if(n<=t||e.length===0)return[];const o=s??Qn(),a=[];let l="";for(let f=t;f<n;f+=i){const u=Xn(e,f,r,o),c=tn(u.diffPath);c!==l&&(l=c,a.push({displayAtMs:f,mouthPath:u.diffPath,mouthKey:c,label:u.label}))}return a}const Ba=3;function Jn(e){let t=0;const n=[];let r=!1,i=!1;const s=async()=>{if(!r){r=!0;try{for(;n.length>0;){const a=n.shift(),l=++t;await e(a.diffs,l,a)&&l===t&&a.onDisplayed?.(a.drawKey)}}finally{r=!1,n.length>0&&s()}}},o=()=>{i||(i=!0,queueMicrotask(()=>{i=!1,s()}))};return{enqueue(a,l,f){const u=n.findIndex(c=>c.drawKey===l);u>=0?n[u]={diffs:a,drawKey:l,onDisplayed:f}:(n.length>=Ba&&(n.shift(),Je()?.onQueueSuperseded()),n.push({diffs:a,drawKey:l,onDisplayed:f})),o()},reset(){t+=1,n.length=0},isLatestSeq(a){return a===t},getLatestSeq(){return t}}}function Fa(e,t=2){const n=[],r=new Set;let i=0,s=!1,o=0;const a=(f,u)=>`${f}|${u}`,l=async()=>{if(!s){s=!0;try{for(;i<t&&n.length>0;){const f=n.shift(),u=a(f.displayAtMs,f.drawKey);if(r.has(u))continue;r.add(u),i+=1;const c=o;try{await e(f)}finally{if(r.delete(u),i-=1,c!==o)return}}}finally{s=!1,n.length>0&&i<t&&l()}}};return{enqueue(f){const u=a(f.displayAtMs,f.drawKey);r.has(u)||n.some(c=>a(c.displayAtMs,c.drawKey)===u)||(n.push(f),l())},isQueuedOrInflight(f,u){const c=a(f,u);return r.has(c)?!0:n.some(d=>a(d.displayAtMs,d.drawKey)===c)},reset(){o+=1,n.length=0,r.clear(),i=0},pendingCount(){return n.length+i}}}function La(){const e=new Map,t=n=>{n.bitmap.close()};return{has(n,r){return e.has(r)},markRendered(n,r,i,s,o){const a=e.get(r);a&&t(a),e.set(r,{displayAtMs:n,mouthKey:r,label:i,mouthPath:s,bitmap:o})},findForMouthKey(n){return e.get(n)??null},removeThrough(n){},pruneBefore(n){},reset(){for(const n of e.values())t(n);e.clear()},size(){return e.size}}}function Oa(e,t,n,r,i,s){const o=Ei(t,n,r,i,At,s);if(o.length===0)return{ready:0,total:0};let a=0;for(const l of o)e.has(l.displayAtMs,l.mouthKey)&&(a+=1);return{ready:a,total:o.length}}function Na(e){const t=La(),n=Qn(),r=new Set;let i="",s=null;const o=Fa(async c=>{try{if(!e.supportsBufferedPlayback)return;const d=await e.compositePrefetchFrame(c.diffs,c.mouthKey);if(!d)return;t.markRendered(c.displayAtMs,c.mouthKey,c.label,c.mouthPath,d),Je()?.onBufferPrefetched()}finally{r.delete(c.mouthKey)}},Ki),a=c=>{for(const d of c)t.has(d.displayAtMs,d.mouthKey)||r.has(d.mouthKey)||o.isQueuedOrInflight(0,d.mouthKey)||(r.add(d.mouthKey),o.enqueue({...d,displayAtMs:0,drawKey:d.mouthKey,diffs:{mouthPath:d.mouthPath,expressionPath:null}}))},l=(c,d,p,T=gn)=>{if(!e.supportsBufferedPlayback)return;const m=Math.max(0,d-At*4),P=Ei(c,m,d+T,p,At,n);a(P)},f=(c,d)=>{i=c,s=d},u=(c,d)=>!(i!==c||s!==d);return{reset(){t.reset(),o.reset(),r.clear(),Be(n),i="",s=null,Je()?.onBufferReset()},markExternallyDisplayed(c,d){f(c.split("|")[0]??c,d)},warmupTick(c){e.supportsBufferedPlayback&&l(c.queue,0,c.availablePaths,Math.max(ar,gn))},isWarmupReady(c,d=ar){if(!e.supportsBufferedPlayback)return!0;const{ready:p,total:T}=Oa(t,c.queue,0,d,c.availablePaths,n);return T===0?!1:p/T>=zi},getBufferedFrameCount:()=>t.size(),tick(c){const d=Je();d?.onBufferTick(),l(c.queue,c.elapsedMs,c.availablePaths),t.pruneBefore(c.elapsedMs-gn);const p=Xn(c.queue,c.elapsedMs,c.availablePaths,n),T=tn(p.diffPath),m=Ct({mouthPath:p.diffPath,expressionPath:c.expressionPath},c.expressionDrawKey),P=()=>(f(T,c.expressionPath),d?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!0});if(u(T,c.expressionPath)||c.playbackState.lastDrawnKey===m)return P();const C=t.findForMouthKey(T,c.elapsedMs,At);return C&&c.expressionPath!=null?(d?.onBufferHit(),{usedBuffer:!1,underrun:!1,held:!1}):C?(e.blitBitmap(c.canvas,C.bitmap),f(C.mouthKey,c.expressionPath),c.playbackState.lastDrawnKey=m,c.onStatus({diffPath:C.mouthPath,label:C.label}),c.onDisplayed(m,C.mouthPath,C.label),d?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!1}):(d?.onBufferUnderrun(),{usedBuffer:!1,underrun:!0,held:!1})}}}const Va=`
|
|
5
|
+
`);Ee=re.pop()??"";for(const Ne of re)await et(Ne);if(tt){Ee.trim()&&await et(Ee.trim()),ve===W&&!le.signal.aborted&&I&&V.markStreamComplete(n);break}}}catch(Fe){if(le.signal.aborted||!I)return;console.error("[realtimeVoice] avatar_speak failed:",Fe),e("error"),M()}finally{P===le&&(P=null)}},Re=h=>{const R=Cs(h);if(!R){console.warn("[realtimeVoice] server message with no payload",h);return}const ee=String(R.type??"unknown");switch(ee!=="avatar_metadata"&&ee!=="avatar_audio_chunk"&&ee!=="avatar_lipsync"&&ee!=="avatar_interrupt"&&ee!=="error"&&console.debug("[realtimeVoice] server message",ee,R),ee){case"avatar_metadata":k(R);break;case"avatar_audio_chunk":ie(R);break;case"avatar_lipsync":xe(R);break;case"avatar_interrupt":L(R);break;case"error":{const le=String(R.message??"Voice session error");console.error("[realtimeVoice] server error:",le),e("error"),M();break}case"avatar_speak":be(R);break}},De=()=>p||(T=new Is,p=new Li.PipecatClient({transport:new Cn.WebSocketTransport({mediaManager:T,serializer:new Es,recorderSampleRate:Wn,playerSampleRate:Hn}),enableCam:!1,enableMic:!0,callbacks:{onBotReady:()=>{d=!0,e("idle"),M()},onDisconnected:()=>{d=!1,_()},onError:h=>{const R=typeof h=="object"&&h!==null&&"data"in h?String(h.data??h):String(h);console.error("[realtimeVoice]",R,h),e("error"),M()},onTransportStateChanged:h=>{h==="error"&&(e("error"),M())},onServerMessage:h=>{ne(h)},onUserStartedSpeaking:()=>{},onBotStartedSpeaking:()=>{S(),oe("bot_started")},onBotStoppedSpeaking:()=>{I&&Z()},onUserTranscript:h=>{String(h.text??""),m.onUserTranscript?.(h.text,!!h.final)},onBotOutput:h=>{m.onBotOutput?.(h.text)}}}),p);return{setDeveloperToken:h=>{},setTtsEngineId:h=>{c=h,V.setStreamTtsEngineId(h)},getTtsEngineId:()=>c,speak:async(h,R)=>{const ee=h.trim();if(ee){if(!p||!d)throw new Error("Realtime voice is not connected. Call connect() first.");O(),await p.sendText(ee)}},stop:()=>{P?.abort(),P=null,W+=1,S(),O(),e("idle"),M()},connect:async h=>{if(h&&(m={...m,...h}),!m.authToken?.trim())throw new Error("Voice connect requires authToken (same JWT as SSE Authorization Bearer).");e("loading");const R=De();await R.initDevices();const ee=fi(m);console.info("[realtimeVoice] connecting (avatar_audio_chunk RTVI):",ee);try{await R.connect({wsUrl:ee})}catch(le){d=!1,e("error"),M();const ve=le instanceof Error?le.message:"Realtime voice connect failed (WebSocket 101 only means upgrade OK — check authToken/origin/RTVI handshake)";throw new Error(`${ve} — ${ee}`)}d=!0,e("idle"),M()},disconnect:async()=>{if(j(),K=!1,X=!1,g.length=0,E=!1,P?.abort(),P=null,W+=1,S(),p)try{await p.disconnect()}catch(h){console.error("[realtimeVoice] disconnect failed:",h)}d=!1,_()},isConnected:()=>d,unlockAudio:async()=>{await V.primeAudioContext()},getVisemeQueue:()=>n,getWordQueue:()=>r,getFullVisemeQueue:()=>i,getFullWordQueue:()=>s,getSentenceEmotions:()=>a,getStreamMood:()=>u,getPlaybackElapsedMs:ae,isSpeaking:()=>V.isSpeaking(),isWarmingUp:()=>V.isWarmingUp(),releaseWarmupHold:()=>V.releaseWarmupHold(),setLipsyncWarmupHold:(h,R)=>{R&&(G=R),V.setLipsyncWarmupHoldEnabled(h)},getVoiceStream:()=>V.getVoiceStream(),setPlaybackSpeed:h=>{V.setPlaybackSpeed(h)},getPlaybackSpeed:()=>V.getPlaybackSpeed(),subscribe:h=>(x.add(h),()=>x.delete(h))}}function mi(e,t,n){return{width:e.crop?.source_width??t,height:e.crop?.source_height??n}}function hi(e,t){const n=e.crop;return{x:t?.source_x??n?.x??0,y:t?.source_y??n?.y??0,width:t?.source_w??n?.width??e.frame_width??0,height:t?.source_h??n?.height??e.frame_height??0}}function pi(e){return e?(e.w??0)>0&&(e.h??0)>0:!1}async function bt(e,t){const n=await fetch(e);if(!n.ok)throw new Error(`Failed to load encrypted asset: ${e}`);const r=await n.arrayBuffer();return rs(r,t)}async function wi(e,t){if(!t)throw new Error("Missing asset key for encrypted JSON");const n=await bt(e,t),r=new TextDecoder().decode(n);return JSON.parse(r)}async function Ds(e){const t=new Blob([e],{type:"image/webp"});return createImageBitmap(t)}async function Bs(e){const t=new Blob([e],{type:"image/webp"}),n=URL.createObjectURL(t);return new Promise((r,i)=>{const s=new Image;s.decoding="async",s.onload=()=>{URL.revokeObjectURL(n),r(s)},s.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to decode decrypted image"))},s.src=n})}async function Fs(e){const t=new Blob([e],{type:"image/png"});return createImageBitmap(t)}async function Ls(e){const t=new Blob([e],{type:"image/png"}),n=URL.createObjectURL(t);return new Promise((r,i)=>{const s=new Image;s.decoding="async",s.onload=()=>{URL.revokeObjectURL(n),r(s)},s.onerror=()=>{URL.revokeObjectURL(n),i(new Error("Failed to decode decrypted PNG"))},s.src=n})}function Os(e){const t=new Blob([e],{type:"video/mp4"});return URL.createObjectURL(t)}async function Ns(e){const t=ss();if(!Dt())return t;if(!e)throw new Error("Missing asset key for encrypted idle video");const n=await bt(t,e);return Os(n)}function gt(e,t){return`${e}/${t}_minus_sil.png`}const gi=5;function un(e){const t=e?.composite_threshold;if(typeof t=="number"&&t>0)return t;const n=e?.crop?.content_threshold;return typeof n=="number"&&n>0?n:gi}const Vs=["aa","E","I","O","U","PP","FF","DD","SS","TH","CH","RR","kk","nn"],In=["t01_0.25","t02_0.50","t03_0.75"],Us=In.length,mr=new Set(["aa__kk","aa__nn","aa__sil","CH__aa","CH__DD","CH__E","CH__FF","CH__I","CH__kk","CH__nn","CH__O","CH__PP","CH__RR","CH__sil","CH__SS","CH__TH","CH__U","DD__aa","DD__E","DD__FF","DD__I","DD__kk","DD__nn","DD__O","DD__PP","DD__RR","DD__sil","DD__SS","DD__TH","DD__U","E__aa","E__FF","E__I","E__kk","E__nn","E__O","E__PP","E__RR","E__sil","E__SS","E__TH","E__U","FF__aa","FF__I","FF__kk","FF__nn","FF__O","FF__PP","FF__RR","FF__sil","FF__SS","FF__TH","FF__U","I__aa","I__kk","I__nn","I__O","I__PP","I__RR","I__sil","I__SS","I__TH","I__U","kk__nn","kk__sil","nn__sil","O__aa","O__kk","O__nn","O__PP","O__RR","O__sil","O__SS","O__TH","O__U","PP__aa","PP__kk","PP__nn","PP__RR","PP__sil","PP__SS","PP__TH","PP__U","RR__aa","RR__kk","RR__nn","RR__sil","RR__SS","RR__TH","RR__U","SS__aa","SS__kk","SS__nn","SS__sil","SS__TH","SS__U","TH__aa","TH__kk","TH__nn","TH__sil","TH__U","U__aa","U__kk","U__nn","U__sil"]);function hr(e,t){return`${e}__${t}`}function pr(e,t){return`pairs/${e}/${t}_minus_sil.png`}function _t(e){return`${e}_minus_sil.png`}function $n(e,t){if(t.has(e))return e;const n=/^pairs\/([^/]+)\//.exec(e);if(!n)return null;const r=n[1].split("__")[1];if(!r||r==="sil")return null;const i=_t(r);return t.has(i)?i:null}function yi(e,t){return e.filter(n=>t.has(n))}function Ws(e,t,n){const r=zn(e,t);return yi(r,n).length>0}function zn(e,t){if(e===t)return[];const n=[],r=hr(e,t);if(mr.has(r)){for(const s of In)n.push(pr(r,s));return n}const i=hr(t,e);if(mr.has(i)){for(let s=Us-1;s>=0;s--)n.push(pr(i,In[s]));return n}return[]}function Hs(e){return e<16?[1]:e<24?[1]:e<35?[0,1,2]:[0,1,2]}function $s(e,t){return Hs(t).map(r=>e[r]).filter(r=>r!=null)}function zs(e,t,n,r){if(r<=0)return 0;const s=Math.max(1,n-t)/r,o=e-t,a=Math.floor(o/s);return Math.min(r-1,Math.max(0,a))}function _i(e,t,n){if(!n)return`${e}/${t}`;const r=t.split("/").pop()??t,i=r.includes(".")?r.slice(0,r.lastIndexOf(".")):r;return`${e}/${i}.bin`}const Ks=[.32,.24,.16,.08,0],js=Ks.map(e=>`eyes_${e.toFixed(2)}`),qs=["eyes_0.32","eyes_0.16","eyes_0.00"],Gs=["eyes_0.32","eyes_0.16","eyes_0.08","eyes_0.00"],Ve=2,Ys=-20,Xt=16,vi={fear:-20,anger:-20,sad:-10,neutral:0,love:0,happy:0,disgust:10};function Ct(e){return`brow_${e}`}function at(e){return vi[e]}function $e(e){return Math.max(Ys,Math.min(Xt,e))}function Qs(e,t){if(e===t)return[];const n=e<t,r=n?Ve:-Ve,i=[];let s=e;if(s%Ve!==0){const o=n?Math.ceil(s/Ve)*Ve:Math.floor(s/Ve)*Ve,a=$e(o);if(n?a>=t:a<=t)return[t];s=a,i.push(s)}for(;;){const o=s+r;if(n?o>=t:o<=t){t!==s&&i.push(t);break}s=o,i.push(s)}return i}function wr(e){const t=$e(e);if(t%Ve===0)return[t];const n=Math.floor(t/Ve)*Ve,r=Math.min(Xt,n+Ve),i=$e(n);return t-i<=r-t?i===r?[i]:[i,r]:i===r?[r]:[r,i]}const Xs=["fear","anger","sad","neutral","love","happy","disgust"],Js={fear:"fear",afraid:"fear",anxiety:"fear",anger:"anger",angry:"anger",mad:"anger",sad:"sad",sadness:"sad",sorrow:"sad",neutral:"neutral",calm:"neutral",love:"love",loving:"love",affection:"love",happy:"happy",happiness:"happy",joy:"happy",joyful:"happy",excited:"happy",disgust:"disgust",disgusted:"disgust"};function je(e,t="neutral"){const n=String(e??"").trim().toLowerCase();return n?Js[n]??t:t}function Si(e){return e===0?null:gt(Ct(e),"eyes_standard")}function bi(e){return Si(at(e))}const Zs={[-20]:"anger",[-10]:"sad",0:"neutral",10:"disgust"};function Kn(e,t){if(!e)return null;if(t(e))return e;const n=e.match(/^brow_(-?\d+)\/(eyes_[^/]+)_minus_sil\.png$/);if(n){const i=Number(n[1]),s=n[2];for(const a of wr(i)){if(a===i)continue;const l=gt(Ct(a),s);if(t(l))return l}const o=Zs[i];if(o){const a=gt(o,s);if(t(a))return a}return null}const r=e.match(/^(fear|anger|sad|neutral|love|happy|disgust)\/(eyes_[^/]+)_minus_sil\.png$/);if(r){const i=r[1],s=r[2],o=at(i);for(const a of[o,...wr(o)]){const l=gt(Ct(a),s);if(t(l))return l}}return null}function gr(e,t){const n=Ct(at(e));return!t||t==="eyes_standard"?bi(e):e==="neutral"&&t==="eyes_standard"?null:gt(n,t)}function ea(e,t){const n=[];for(const r of t)n.push(gr(e,r));for(let r=t.length-2;r>=0;r--)n.push(gr(e,t[r]));return n.push(bi(e)),n}function ta(e){return gt(Ct(e),"eyes_standard")}function na(e,t){return Qs(e,t).map(ta)}const ra=6;function ia(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function sa(e){const t=$e(e);return t>=Xt?Xt:$e(t+ra)}function aa(e,t,n){const r=$e(n);return ia(t,e)?.emphasis?sa(r):r}function yr(e){if(!e)return 0;const t=e.match(/^brow_(-?\d+)\//);if(!t?.[1])return null;const n=Number.parseInt(t[1],10);return Number.isFinite(n)?$e(n):null}function wt(e,t){return e+Math.random()*(t-e)}function Kt(){return wt(14,32)}function oa(e={}){const{initialDelayMs:t=800+Math.random()*1200,intervalMinMs:n=2200,intervalMaxMs:r=5800,doubleBlinkChance:i=.18,doubleBlinkGapMinMs:s=120,doubleBlinkGapMaxMs:o=220,fullBlinkChance:a=.75,postEmotionChangeDelayMs:l=380,minDwellMs:f=550}=e;let u="neutral",c="neutral",d=0,p=0,T=0,m={kind:"idle",nextBlinkAt:performance.now()+t},A=null,C="__eyes_open__|neutral|brow:0";function x(P=u){C=`${A??"__eyes_open__"}|${P}|brow:${p}`}function g(P,W=u){A=P;const K=yr(P);K!=null?p=K:P==null&&(p=0),x(W)}function E(P){return Si(P)}function N(P,W,K){const X=$e(W),Y=$e(K);if(d=Y,X===Y){g(E(Y));return}const pe=[...na(X,Y),E(Y)];m={kind:"browBlend",paths:pe,index:0,holdUntil:P+Kt(),targetBrow:Y},g(pe[0]??null)}function I(P,W){m={kind:"idle",nextBlinkAt:P+wt(n,r)},c=W,g(E(d),W)}function te(P,W,K){const X=K?qs:Math.random()<a?js:Gs;m={kind:"playing",paths:ea(W,X),index:0,holdUntil:P+Kt(),after:"idle",blinkEmotion:W},c=W,g(m.paths[0]??null,W)}function de(P){if(m.kind==="browBlend"){for(;P>=m.holdUntil&&m.index<m.paths.length-1;)m.index+=1,m.holdUntil=P+Kt();const W=m.paths[m.index]??null;g(W),P>=m.holdUntil&&m.index>=m.paths.length-1&&(p=m.targetBrow,d=m.targetBrow,g(E(m.targetBrow)),m={kind:"idle",nextBlinkAt:P+l});return}if(m.kind==="idle"){g(E(d),c),P>=m.nextBlinkAt&&te(P,c,!1);return}if(m.kind==="doublePause"){g(E(d),m.blinkEmotion),P>=m.resumeAt&&te(P,m.blinkEmotion,!0);return}if(m.kind==="playing"){for(;P>=m.holdUntil&&m.index<m.paths.length-1;)m.index+=1,m.holdUntil=P+Kt();if(g(m.paths[m.index]??null,m.blinkEmotion),P>=m.holdUntil&&m.index>=m.paths.length-1){if(m.after==="resumeIdle"){I(P+l,u);return}if(m.after==="doublePause"){m={kind:"doublePause",resumeAt:P+wt(s,o),blinkEmotion:m.blinkEmotion},g(E(d),m.blinkEmotion);return}if(m.after==="idle"&&Math.random()<i){m={kind:"doublePause",resumeAt:P+wt(s,o),blinkEmotion:m.blinkEmotion},g(E(d),m.blinkEmotion);return}I(P,m.blinkEmotion)}}}return{advance:de,setTargetEmotion(P,W){const K=je(P,u);if(K===u)return;const X=performance.now();!W?.force&&f>0&&!(u==="neutral"&&K!=="neutral")&&X-T<f||(u=K,c=K,T=X)},setTargetEyebrow(P){const W=$e(P);if(W===d)return;const K=performance.now(),X=m.kind==="browBlend"?yr(A)??p:p;d=W,!(W===X&&m.kind!=="browBlend")&&(m.kind==="playing"||m.kind==="doublePause"||N(K,X,W))},snapToEmotion(P){const W=je(P),K=at(W);u=W,c=W,d=K,p=K,T=performance.now(),m={kind:"idle",nextBlinkAt:performance.now()+wt(4e3,7e3)},g(E(K),W)},getTargetEmotion:()=>u,getTargetEyebrow:()=>d,getExpressionPath:()=>A,getDrawKey:()=>C,reset(){u="neutral",c="neutral",d=0,p=0,T=0,I(performance.now()+wt(n,r),"neutral")}}}function ca(){const e=document.createElement("video");e.muted=!0,e.playsInline=!0,e.preload="auto",e.setAttribute("playsinline",""),e.loop=!0;let t=!1,n=null,r="";const i=()=>{n&&(URL.revokeObjectURL(n),n=null)};return{async load(s){t&&r===s||(i(),t=!1,r=s,s.startsWith("blob:")&&(n=s),await new Promise((o,a)=>{const l=()=>{const f=e.duration;if(!Number.isFinite(f)||f<=0){a(new Error(`Idle video has invalid duration: ${s}`));return}t=!0,e.currentTime=0,o()};e.addEventListener("loadeddata",l,{once:!0}),e.addEventListener("error",()=>a(new Error(`Failed to load idle video: ${s}`)),{once:!0}),e.src=s,e.load()}))},isReady(){return t},getVideo(){return e},setActive(s){t&&(s?e.paused&&e.play().catch(()=>{}):e.paused||e.pause())},restart(){t&&(e.currentTime=0)},dispose(){e.pause(),e.removeAttribute("src"),e.load(),i(),t=!1,r=""}}}const ua=50,Ti=400;function la(e,t,n){return e.filter(r=>{const i=r.queueIndex??-1;return i>=t&&i<=n})}function fa(e,t){const n=[];for(const r of e){const i=la(t,r.start_word,r.end_word);if(i.length===0)continue;const s=i[0],o=i[i.length-1];n.push({sentence:r,startMs:Math.max(0,s.wtime-ua),endMs:o.wtime+o.wduration+Ti})}return n.sort((r,i)=>r.startMs-i.startMs)}function da(e,t,n,r="neutral"){const i=je(r);if(t.length===0)return i;if(n.length===0||e<n[0].wtime)return je(t[0]?.emotion,i);const s=fa(t,n);let o=null;for(const f of s)e>=f.startMs&&e<=f.endMs&&(o=f);if(o)return je(o.sentence.emotion,i);const a=n[n.length-1],l=a.wtime+a.wduration;return e>l+Ti?je(t[t.length-1]?.emotion,i):i}function jn(e,t,n,r,i=gi){const s=new OffscreenCanvas(n,r),o=s.getContext("2d",{willReadFrequently:!0});o.drawImage(e,0,0,n,r);const a=o.getImageData(0,0,n,r),l=o.createImageData(n,r);l.data.set(a.data);const u=new OffscreenCanvas(n,r).getContext("2d",{willReadFrequently:!0});for(const c of t){u.clearRect(0,0,n,r),u.drawImage(c,0,0,n,r);const d=u.getImageData(0,0,n,r);for(let p=0;p<l.data.length;p+=4){const T=d.data[p],m=d.data[p+1],A=d.data[p+2];Math.max(T,m,A)>i&&(l.data[p]=T,l.data[p+1]=m,l.data[p+2]=A,l.data[p+3]=255)}}return o.putImageData(l,0,0),s}let it=null,vt=null;const Jt=new Map;function ma(){it=null,vt=null,Jt.clear()}Wr(ma);function ha(e){return e??vt??void 0}function qn(e){return new Promise((t,n)=>{const r=new Image;r.decoding="async",r.onload=()=>t(r),r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}async function pa(e){return Dt()?Ls(await bt(Qt(),e??"")):qn(Qt())}async function _r(e,t,n,r){const i=n?await wi(e,r):await fetch(e).then(f=>{if(!f.ok)throw new Error(`Failed to load ${e}`);return f.json()}),s=i.sheets?.[0];if(!s?.path)throw new Error(`${e} has no sheets[0].path`);const o=n?await Bs(await bt(_i(t,s.path,n),r??"")):await qn(`${t}/${s.path}`),a=new Map;for(const f of i.cells??[])f.path&&a.set(f.path,f);const l=new Map;for(const f of i.sheets??[])l.set(f.index,f);return{atlas:o,atlasMeta:i,cellByPath:a,sheetByIndex:l,diffBase:t}}async function An(e){const t=ha(e),n=Dt();if(n&&!t)throw new Error("Encrypted assets enabled but no key provided");if(it&&(!n||vt===(t??null))){const s=await it;return{...St(s),visemePaths:[...s.viseme.cellByPath.keys()]}}vt=t??null,Jt.clear();const r=Hr();it=(async()=>{const s=await pa(t),o=await _r($r(),r,n,t);let a=null;try{a=await _r(zr(),r,n,t)}catch{a=null}return{sil:s,viseme:o,expression:a}})();const i=await it;return{...St(i),visemePaths:[...i.viseme.cellByPath.keys()]}}async function Gn(e){if(await An(e),!it)throw new Error("Assets not loaded");return it}function St(e){return mi(e.viseme.atlasMeta,e.sil.naturalWidth,e.sil.naturalHeight)}function wa(e,t){const n=document.createElement("canvas");return n.width=t.w,n.height=t.h,n.getContext("2d",{willReadFrequently:!0}).drawImage(e.atlas,t.x,t.y,t.w,t.h,0,0,t.w,t.h),n}async function Zt(e,t,n){const r=`${t.diffBase}::${n}`,i=Jt.get(r);if(i)return i;const s=(async()=>{const o=t.cellByPath.get(n);if(!o)throw new Error(`No atlas cell for path: ${n}`);const a=hi(t.atlasMeta,o),l=St(e);if(pi(o)){const c=wa(t,o),d=document.createElement("canvas");d.width=l.width,d.height=l.height;const p=d.getContext("2d");return p.fillStyle="#000",p.fillRect(0,0,l.width,l.height),p.drawImage(c,a.x,a.y),d}const f=`${t.diffBase}/${n}`,u=await qn(f);if(u.naturalWidth===l.width&&u.naturalHeight===l.height)return u;throw new Error(`Diff PNG wrong size for ${n}`)})();return Jt.set(r,s),s}async function _n(e,t,n,r,i,s){if(i){const{width:p,height:T}=i;if(s&&!s()||t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)return;const m=document.createElement("canvas");m.width=p,m.height=T;const A=m.getContext("2d");if(A.clearRect(0,0,p,T),A.drawImage(t,0,0,p,T),s&&!s())return;(e.width!==p||e.height!==T)&&(e.width=p,e.height=T);const C=e.getContext("2d");C.clearRect(0,0,p,T),C.drawImage(m,0,0);return}const o=await Gn(),a=un(o.viseme.atlasMeta),{width:l,height:f}=St(o);(e.width!==l||e.height!==f)&&(e.width=l,e.height=f);const u=[],c=e.getContext("2d");if(c.clearRect(0,0,l,f),t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){const p=o.sil;c.drawImage(p,0,0,l,f);return}if(u.length===0){c.drawImage(t,0,0,l,f);return}const d=jn(t,u,l,f,a);c.drawImage(d,0,0)}async function Pn(e,t,n){const r=await Gn(vt??void 0),i=un(r.viseme.atlasMeta),{width:s,height:o}=St(r);(e.width!==s||e.height!==o)&&(e.width=s,e.height=o);const a=[];if(t.mouthPath){const u=new Set(r.viseme.cellByPath.keys()),c=$n(t.mouthPath,u)??(u.has(t.mouthPath)?t.mouthPath:null);c&&a.push(await Zt(r,r.viseme,c))}if(t.expressionPath&&r.expression){const u=Kn(t.expressionPath,c=>r.expression.cellByPath.has(c));u&&a.push(await Zt(r,r.expression,u))}const l=e.getContext("2d");if(l.clearRect(0,0,s,o),a.length===0){l.drawImage(r.sil,0,0,s,o);return}const f=jn(r.sil,a,s,o,i);l.drawImage(f,0,0)}async function ga(e,t){const n=await Gn(vt??void 0),r=un(n.viseme.atlasMeta),{width:i,height:s}=St(n),o=[];if(e.mouthPath){const u=new Set(n.viseme.cellByPath.keys()),c=$n(e.mouthPath,u)??(u.has(e.mouthPath)?e.mouthPath:null);c&&o.push(await Zt(n,n.viseme,c))}if(e.expressionPath&&n.expression){const u=Kn(e.expressionPath,c=>n.expression.cellByPath.has(c));u&&o.push(await Zt(n,n.expression,u))}const a=new OffscreenCanvas(i,s),l=a.getContext("2d");if(o.length===0)return l.drawImage(n.sil,0,0,i,s),a.transferToImageBitmap();const f=jn(n.sil,o,i,s,r);return l.drawImage(f,0,0),a.transferToImageBitmap()}async function ya(e){await Pn(e,{mouthPath:null,expressionPath:null})}const jt={fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"clamp(0.875rem, 2.5vw, 1.125rem)",color:"rgba(255,255,255,0.85)"};function _a(e){return e.length===0?"":e.map(t=>t.word).join(" ")}function va(e){if(!e)return{enabled:!1,style:jt};const t=e===!0?{}:e;return{enabled:!0,style:{fontFamily:t.fontFamily??jt.fontFamily,fontSize:t.fontSize??jt.fontSize,color:t.color??jt.color}}}const Sa={position:"absolute",bottom:0,left:0,right:0,display:"flex",justifyContent:"center",padding:"0.75rem 1rem",pointerEvents:"none"},ba={display:"inline-block",maxWidth:"100%",padding:"0.45rem 0.85rem",borderRadius:"0.75rem",background:"rgba(0,0,0,0.55)",lineHeight:1.4,textAlign:"center"},Ta={display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",maxWidth:"100%",margin:0};function ka({text:e,style:t}){return z.jsx("div",{style:Sa,"aria-live":"polite","aria-atomic":"true",children:z.jsx("div",{style:{...ba,fontFamily:t.fontFamily,fontSize:t.fontSize,color:t.color},children:z.jsx("p",{style:Ta,children:e})})})}let ki=null;function vr(e){ki=e}function Qe(){return ki}function xa(e){return`${e.from}→${e.to}@${e.fromVtime}`}function Sr(){return{rafTicksSpeaking:0,rafTicksDeduped:0,drawsRequested:0,drawsDisplayed:0,queueSuperseded:0,workerStale:0,rifeFramesOmittedByGap:0,transitionFramesSampled:0,transitionFramesDisplayed:0,transitionFramesMissed:0,bufferTicks:0,bufferHits:0,bufferUnderruns:0,bufferPrefetched:0}}function Ea(){let e=Sr();const t=new Set,n=new Set,r=new Set;let i="",s=-1,o="";const a=()=>{e=Sr(),t.clear(),n.clear(),r.clear(),i="",s=-1,o=""},l=u=>{t.add(u)},f=u=>{u&&r.add(u)};return{reset:a,onRafTickSpeaking(){e.rafTicksSpeaking+=1},onDrawDeduped(){e.rafTicksDeduped+=1},onDrawRequested(){e.drawsRequested+=1},onQueueSuperseded(){e.queueSuperseded+=1},onWorkerStale(){e.workerStale+=1},onTransitionSample(u,c){const d=xa(u);e.transitionFramesSampled+=1,d!==i&&(i=d,s=-1,o!==d&&(o=d,e.rifeFramesOmittedByGap+=u.omittedByGap)),c&&n.add(c),s>=0&&u.frameIdx>s+1&&(e.transitionFramesMissed+=u.frameIdx-s-1),s=u.frameIdx},onBufferTick(){e.bufferTicks+=1},onBufferHit(){e.bufferHits+=1},onBufferUnderrun(){e.bufferUnderruns+=1},onBufferPrefetched(){e.bufferPrefetched+=1},onBufferReset(){},onDrawDisplayed(u,c){if(e.drawsDisplayed+=1,u.transitionMeta){e.transitionFramesDisplayed+=1;const p=u.transitionMeta;l(p.fromVtime),l(p.toVtime),f(u.mouthPath);return}if(u.label.includes("→")){e.transitionFramesDisplayed+=1;return}const d=u.label.trim();if(!(!d||d==="sil")){for(const p of c)if(p.viseme===d&&u.elapsedMs>=p.vtime&&u.elapsedMs<p.vtime+p.vduration){l(p.vtime);break}}},snapshot(u,c){let d=0,p=0;for(const x of u)if(x.viseme!=="sil"){if(x.vtime>=c)break;d+=1,t.has(x.vtime)&&(p+=1)}const T=d>0?Math.round(p/d*100):100,m=e.queueSuperseded+e.workerStale+Math.max(0,e.drawsRequested-e.drawsDisplayed),A=d-p,C=e.bufferTicks>0?Math.round(e.bufferHits/e.bufferTicks*100):100;return{...e,bufferHitRate:C,renderLoss:m,visemeSlotsTotal:d,visemeSlotsCovered:p,visemeCoveragePct:T,transitionFramesUniqueSampled:n.size,transitionFramesUniquePainted:r.size,drawsDeduped:e.rafTicksDeduped,renderSkips:e.rafTicksDeduped+m,visemesShown:p,visemesSkipped:A,rifeTransitionFramesSkipped:e.transitionFramesMissed}}}}const xi=Dn,Ia=200,br=300,Aa=100,Pa=600,Ei="__sil__";function Tr(e){return e.lastDrawnKey?e.lastDrawnKey.split("|")[0]===Ei:!1}function Yn(){return{lastDrawnKey:""}}function Ce(e){e.lastDrawnKey="",e.transitionCache=void 0}function Ma(e,t){if(t?.transitionCache&&t.transitionCache.queueLength===e.length)return t.transitionCache.transitions;const n=ri(e);return t&&(t.transitionCache={queueLength:e.length,transitions:n}),n}function Ca(e,t){let n="sil";for(const r of e)r.viseme!=="sil"&&(t!=null&&r.vtime>t||(n=r.viseme));return n}function Ra(e,t,n,r=120){if(n!=="sil")return n;const i=li(e,t,r);return i!=="sil"?i:Ca(e,t)}function Da(e,t){return e==="sil"?!1:t?Ws(e,"sil",t):zn(e,"sil").length>0}function Ba(){return xi+Pa}function en(e){return e??Ei}function Qn(e,t,n,r,i=Aa){if(e.length===0)return{diffPath:null,label:"sil"};if(t>=rt(e))return{diffPath:null,label:"sil"};const s=Ma(e,r),o=vs(s,t);if(o){const f=ii(o.fromVtime,o.toVtime,o.from,o.to);if(t>=f.transStart&&t<f.transEnd){let u=zn(o.from,o.to);n&&(u=yi(u,n));const c=$s(u,f.effectiveGapMs);if(c.length>0){const d=zs(t,f.transStart,f.transEnd,c.length);return{diffPath:c[d]??c[c.length-1],label:`${o.from}→${o.to}`,transitionMeta:{from:o.from,to:o.to,fromVtime:o.fromVtime,toVtime:o.toVtime,frameIdx:d,frameCount:c.length,fullFrameCount:u.length,omittedByGap:Math.max(0,u.length-c.length)}}}return{diffPath:_t(o.to),label:o.to}}}const a=sn(e);let l=Zr(a,t);return l==="sil"&&(l=li(e,t,i)),l==="sil"?{diffPath:null,label:"sil"}:{diffPath:_t(l),label:l}}function Rt(e,t){const n=t??en(e.expressionPath);return`${en(e.mouthPath)}|${n}`}function kr(e,t,n,r,i,s,o,a,l,f){const u=Qn(t,n,l,s),c={mouthPath:u.diffPath,expressionPath:r},d=Rt(c,i),p=Qe();if(u.transitionMeta&&p?.onTransitionSample(u.transitionMeta,u.diffPath),d===s.lastDrawnKey){p?.onDrawDeduped();return}p?.onDrawRequested(),a(u),s.lastDrawnKey=d,o(e,c,d,T=>{T===d&&(s.lastDrawnKey=d)})}function vn(e,t,n,r,i,s,o=null,a=null){const l={mouthPath:a,expressionPath:t},f=o!=null?`|idle@${Math.round(o*1e3)}`:"",u=Rt(l,n)+f;!(o!=null)&&u===r.lastDrawnKey||(s(o!=null?t?"idle · blink":"idle":t?"blink":"sil"),i(e,l,u,d=>{d===u&&(r.lastDrawnKey=u)}))}function Ii(e,t,n,r,i=Pt,s){if(n<=t||e.length===0)return[];const o=s??Yn(),a=[];let l="";for(let f=t;f<n;f+=i){const u=Qn(e,f,r,o),c=en(u.diffPath);c!==l&&(l=c,a.push({displayAtMs:f,mouthPath:u.diffPath,mouthKey:c,label:u.label}))}return a}const Fa=3;function Xn(e){let t=0;const n=[];let r=!1,i=!1;const s=async()=>{if(!r){r=!0;try{for(;n.length>0;){const a=n.shift(),l=++t;await e(a.diffs,l,a)&&l===t&&a.onDisplayed?.(a.drawKey)}}finally{r=!1,n.length>0&&s()}}},o=()=>{i||(i=!0,queueMicrotask(()=>{i=!1,s()}))};return{enqueue(a,l,f){const u=n.findIndex(c=>c.drawKey===l);u>=0?n[u]={diffs:a,drawKey:l,onDisplayed:f}:(n.length>=Fa&&(n.shift(),Qe()?.onQueueSuperseded()),n.push({diffs:a,drawKey:l,onDisplayed:f})),o()},reset(){t+=1,n.length=0},isLatestSeq(a){return a===t},getLatestSeq(){return t}}}function La(e,t=2){const n=[],r=new Set;let i=0,s=!1,o=0;const a=(f,u)=>`${f}|${u}`,l=async()=>{if(!s){s=!0;try{for(;i<t&&n.length>0;){const f=n.shift(),u=a(f.displayAtMs,f.drawKey);if(r.has(u))continue;r.add(u),i+=1;const c=o;try{await e(f)}finally{if(r.delete(u),i-=1,c!==o)return}}}finally{s=!1,n.length>0&&i<t&&l()}}};return{enqueue(f){const u=a(f.displayAtMs,f.drawKey);r.has(u)||n.some(c=>a(c.displayAtMs,c.drawKey)===u)||(n.push(f),l())},isQueuedOrInflight(f,u){const c=a(f,u);return r.has(c)?!0:n.some(d=>a(d.displayAtMs,d.drawKey)===c)},reset(){o+=1,n.length=0,r.clear(),i=0},pendingCount(){return n.length+i}}}function Oa(){const e=new Map,t=n=>{n.bitmap.close()};return{has(n,r){return e.has(r)},markRendered(n,r,i,s,o){const a=e.get(r);a&&t(a),e.set(r,{displayAtMs:n,mouthKey:r,label:i,mouthPath:s,bitmap:o})},findForMouthKey(n){return e.get(n)??null},removeThrough(n){},pruneBefore(n){},reset(){for(const n of e.values())t(n);e.clear()},size(){return e.size}}}function Na(e,t,n,r,i,s){const o=Ii(t,n,r,i,Pt,s);if(o.length===0)return{ready:0,total:0};let a=0;for(const l of o)e.has(l.displayAtMs,l.mouthKey)&&(a+=1);return{ready:a,total:o.length}}function Va(e){const t=Oa(),n=Yn(),r=new Set;let i="",s=null;const o=La(async c=>{try{if(!e.supportsBufferedPlayback)return;const d=await e.compositePrefetchFrame(c.diffs,c.mouthKey);if(!d)return;t.markRendered(c.displayAtMs,c.mouthKey,c.label,c.mouthPath,d),Qe()?.onBufferPrefetched()}finally{r.delete(c.mouthKey)}},ji),a=c=>{for(const d of c)t.has(d.displayAtMs,d.mouthKey)||r.has(d.mouthKey)||o.isQueuedOrInflight(0,d.mouthKey)||(r.add(d.mouthKey),o.enqueue({...d,displayAtMs:0,drawKey:d.mouthKey,diffs:{mouthPath:d.mouthPath,expressionPath:null}}))},l=(c,d,p,T=gn)=>{if(!e.supportsBufferedPlayback)return;const m=Math.max(0,d-Pt*4),A=Ii(c,m,d+T,p,Pt,n);a(A)},f=(c,d)=>{i=c,s=d},u=(c,d)=>!(i!==c||s!==d);return{reset(){t.reset(),o.reset(),r.clear(),Ce(n),i="",s=null,Qe()?.onBufferReset()},markExternallyDisplayed(c,d){f(c.split("|")[0]??c,d)},warmupTick(c){e.supportsBufferedPlayback&&l(c.queue,0,c.availablePaths,Math.max(ar,gn))},isWarmupReady(c,d=ar){if(!e.supportsBufferedPlayback)return!0;const{ready:p,total:T}=Na(t,c.queue,0,d,c.availablePaths,n);return T===0?!1:p/T>=Ki},getBufferedFrameCount:()=>t.size(),tick(c){const d=Qe();d?.onBufferTick(),l(c.queue,c.elapsedMs,c.availablePaths),t.pruneBefore(c.elapsedMs-gn);const p=Qn(c.queue,c.elapsedMs,c.availablePaths,n),T=en(p.diffPath),m=Rt({mouthPath:p.diffPath,expressionPath:c.expressionPath},c.expressionDrawKey),A=()=>(f(T,c.expressionPath),d?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!0});if(u(T,c.expressionPath)||c.playbackState.lastDrawnKey===m)return A();const C=t.findForMouthKey(T,c.elapsedMs,Pt);return C&&c.expressionPath!=null?(d?.onBufferHit(),{usedBuffer:!1,underrun:!1,held:!1}):C?(e.blitBitmap(c.canvas,C.bitmap),f(C.mouthKey,c.expressionPath),c.playbackState.lastDrawnKey=m,c.onStatus({diffPath:C.mouthPath,label:C.label}),c.onDisplayed(m,C.mouthPath,C.label),d?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!1}):(d?.onBufferUnderrun(),{usedBuffer:!1,underrun:!0,held:!1})}}}const Ua=`
|
|
6
6
|
in vec2 aPosition;
|
|
7
7
|
out vec2 vTextureCoord;
|
|
8
8
|
|
|
@@ -30,7 +30,7 @@ void main(void)
|
|
|
30
30
|
gl_Position = filterVertexPosition();
|
|
31
31
|
vTextureCoord = filterTextureCoord();
|
|
32
32
|
}
|
|
33
|
-
`,
|
|
33
|
+
`,Wa=`
|
|
34
34
|
in vec2 vTextureCoord;
|
|
35
35
|
out vec4 finalColor;
|
|
36
36
|
|
|
@@ -44,5 +44,5 @@ void main(void)
|
|
|
44
44
|
float keep = step(uThreshold + 1e-6, peak);
|
|
45
45
|
finalColor = vec4(color.rgb, keep);
|
|
46
46
|
}
|
|
47
|
-
`;function kr(e=5){const t=new pe.Filter({glProgram:pe.GlProgram.from({vertex:Va,fragment:Ua,name:"threshold-key-filter"}),resources:{thresholdUniforms:{uThreshold:{value:e/255,type:"f32"}}}});return t.setThreshold=n=>{t.resources.thresholdUniforms.uniforms.uThreshold=n/255},t.getThreshold=()=>Math.round(t.resources.thresholdUniforms.uniforms.uThreshold*255),t}function Wa(e,t,n){return e>n||t>n}function Ha(e){return e?e.getParameter(e.MAX_TEXTURE_SIZE):4096}function $a(e,t){return t!=null&&t>0?Math.floor(t):Ha(e)}function za(e,t){const n=document.createElement("canvas");n.width=t.w,n.height=t.h;const r=n.getContext("2d");if(!r)throw new Error("Failed to acquire 2d context for atlas cell crop");return r.drawImage(e,t.x,t.y,t.w,t.h,0,0,t.w,t.h),n}function Ii(e){return fetch(e).then(t=>{if(!t.ok)throw new Error(`Failed to load image: ${e}`);return t.blob()}).then(t=>createImageBitmap(t))}async function xr(e,t,n,r,i){const s=n?await pi(e,i):await fetch(e).then(c=>{if(!c.ok)throw new Error(`Failed to load ${e}`);return c.json()}),o=s.sheets?.[0];if(!o?.path)throw new Error(`${e} has no sheets[0].path`);const a=new Map,l=async(c,d)=>{const p=yi(t,d,n),T=n?await Rs(await bt(p,i??"")):await Ii(p);if(Wa(T.width,T.height,r))return console.info(`[PixiVisemeCompositor] Sheet ${d} (${T.width}x${T.height}) exceeds MAX_TEXTURE_SIZE=${r}; using per-cell crops.`),{mode:"cells",bitmap:T};const m=pe.Texture.from(T);return m.source.scaleMode="nearest",{mode:"full",texture:m}};a.set(o.index,await l(o.index,o.path));for(const c of s.sheets??[])c.index!==o.index&&c.path&&a.set(c.index,await l(c.index,c.path));const f=new Map;for(const c of s.cells??[])c.path&&f.set(c.path,c);const u=new Map;for(const c of s.sheets??[])u.set(c.index,c);return{atlasMeta:s,cellByPath:f,sheetByIndex:u,diffBase:t,sheets:a}}async function Ka(e,t={}){const n=new pe.Application;try{await n.init({canvas:e,width:842,height:1264,preference:"webgl",autoStart:!1,antialias:!1,resolution:1,autoDensity:!1,backgroundAlpha:1,backgroundColor:0,powerPreference:"high-performance"})}catch(_){throw n.destroy({removeView:!1}),_}if(n.renderer.type!==pe.RendererType.WEBGL)throw n.destroy({removeView:!1}),new Error("Pixi did not initialize a WebGL renderer");const r=$a(n.renderer.gl,t.maxTextureSize);let i=!1,s=!1,o=!1;const a=n.canvas,l=()=>{i=!0,!s&&!o&&(s=!0,t.onWebGlContextLost?.())};a.addEventListener("webglcontextlost",l);const f=new pe.Sprite(pe.Texture.EMPTY),u=new pe.Sprite(pe.Texture.EMPTY);u.visible=!1,u.alpha=0;const c=new pe.Sprite(pe.Texture.EMPTY),d=new pe.Sprite(pe.Texture.EMPTY),p=new pe.Sprite(pe.Texture.EMPTY);p.visible=!1;const T=kr(5),m=kr(5);c.filters=[T],d.filters=[m],n.stage.addChild(f),n.stage.addChild(u),n.stage.addChild(c),n.stage.addChild(d),n.stage.addChild(p);let P=null,C=null,E=null,g=null,I=null,N=null,A=null,ee=842,fe=1264,M=null,W=5;const K=new Map;let Q=null,Y=null,de=null;const F=Ur(()=>{K.clear(),N=null,A=null,P=null,M=null}),Z=(_,v)=>{ee=_,fe=v,n.renderer.resize(_,v),(e.width!==_||e.height!==v)&&(e.width=_,e.height=v)},k=()=>{c.visible=!1,d.visible=!1,c.texture=pe.Texture.EMPTY,d.texture=pe.Texture.EMPTY,Q=null,Y=null},q=()=>{I=null,u.visible=!1,u.alpha=0},re=()=>{f.visible=!0,f.width=ee,f.height=fe,f.x=0,f.y=0},oe=()=>{u.width=ee,u.height=fe,u.x=0,u.y=0},ne=()=>{p.visible=!1,q(),P&&(f.texture=P,re())},te=()=>{!I&&!u.visible||ne()},ie=_=>{if(o||i||!P){ne();return}const v=Math.max(0,_);if(!C||v<=0){ne();return}k(),p.visible=!1,f.texture=C,re(),u.texture=P,oe(),u.alpha=0,u.visible=!0,I={startMs:performance.now(),durationMs:v},V()},we=(_=performance.now())=>{if(!I)return!1;if(o||i)return te(),!1;const v=(_-I.startMs)/Math.max(1,I.durationMs);if(v>=1)return ne(),V(),!1;const x=Math.min(1,Math.max(0,v)),H=x*x*(3-2*x);return u.alpha=H,u.visible=!0,V(),!0},b=()=>{if(E){try{E.resource=null}catch{}E.destroy(),E=null}C&&(C.destroy(!1),C=null),g=null},$=(_,v)=>{const x=_.cellByPath.get(v);if(!x||!hi(x))return null;const H=`${_.diffBase}::${v}`;let X=K.get(H);if(!X){const se=x.sheet??0,Ee=_.sheets.get(se);if(!Ee)return null;let _e,Ve=!1;if(Ee.mode==="full")_e=new pe.Texture({source:Ee.texture.source,frame:new pe.Rectangle(x.x,x.y,x.w,x.h)});else{const Ue=za(Ee.bitmap,x);_e=pe.Texture.from(Ue),_e.source.scaleMode="nearest",Ve=!0}X={texture:_e,ownsSource:Ve},K.set(H,X)}return{texture:X.texture,cell:x}},S=(_,v,x,H)=>{if(!H||!x)return _.visible=!1,_.texture=pe.Texture.EMPTY,!1;const X=$(x,H);if(!X)return _.visible=!1,_.texture=pe.Texture.EMPTY,!1;const se=mi(x.atlasMeta,X.cell);return v.setThreshold(W),_.texture=X.texture,_.x=se.x,_.y=se.y,_.width=X.cell.w,_.height=X.cell.h,_.visible=!0,!0},O=_=>{if(!_||!N)return null;const v=M??new Set(N.cellByPath.keys());return zn(_,v)??(v.has(_)?_:null)},D=_=>{p.visible=!1,ne();const v=O(_.mouthPath),x=_.expressionPath&&A?jn(_.expressionPath,H=>A.cellByPath.has(H)):null;v!==Q?(S(c,T,N,v),Q=v):v?c.visible=!0:c.visible=!1,x!==Y?(S(d,m,A,x),Y=x):x?d.visible=!0:d.visible=!1},V=()=>{if(!(o||i||document.hidden))try{n.render()}catch{}};return{async loadAssets(_){if(o)return{width:ee,height:fe,visemePaths:[]};const v=Rt();if(v&&!_)throw new Error("Encrypted assets enabled but no key provided");const x=v?await Bs(await bt(Xt(),_??"")):await Ii(Xt());P&&P.destroy(!0),P=pe.Texture.from(x),P.source.scaleMode="linear";const H=Wr();N=await xr(Hr(),H,v,r,_);try{A=await xr($r(),H,v,r,_)}catch(se){console.warn("[PixiVisemeCompositor] expression atlas unavailable:",se),A=null}const X=di(N.atlasMeta,x.width,x.height);return Z(X.width,X.height),W=ln(N.atlasMeta),T.setThreshold(W),m.setThreshold(W),M=new Set(N.cellByPath.keys()),K.clear(),ne(),k(),V(),{width:X.width,height:X.height,visemePaths:[...N.cellByPath.keys()]}},getVisemeAtlasPaths(){return M},drawLiveFrame(_){o||i||!P||(te(),D(_),V())},drawIdleVideo(_,v){o||i||document.hidden||v&&!v()||_.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||(q(),k(),p.visible=!1,!C||g!==_?(b(),E=new pe.VideoSource({resource:_,autoPlay:!1,updateFPS:0}),E.autoUpdate=!1,C=new pe.Texture({source:E}),g=_):C.source.update(),f.texture=C,re(),V())},beginIdleToSilCrossfade:ie,tickIdleToSilCrossfade:we,finishIdleToSilCrossfade:te,isIdleToSilCrossfading(){return I!=null},renderSilOnly(){o||i||!P||(k(),ne(),V())},blitBitmap(_){o||i||(te(),k(),de&&(de.destroy(!0),de=null),de=pe.Texture.from(_),p.texture=de,p.visible=!0,p.x=0,p.y=0,p.width=ee,p.height=fe,f.visible=!1,V())},async compositePrefetchFrame(_){return null},renderFrame:V,isContextLost(){return i},dispose(){if(o)return;o=!0,a.removeEventListener("webglcontextlost",l),F(),b(),de&&(de.destroy(!0),de=null);for(const{texture:v,ownsSource:x}of K.values())v.destroy(x);K.clear(),P&&(P.destroy(!0),P=null);const _=v=>{v.mode==="full"?v.texture.destroy(!0):v.bitmap.close()};if(N)for(const v of N.sheets.values())_(v);if(A)for(const v of A.sheets.values())_(v);T.destroy(!0),m.destroy(!0),n.destroy({removeView:!1},{children:!0,texture:!0})}}}const Er=-1,Gt=1e5,Ir=new Map;async function ja(e){let t=Ir.get(e);if(!t){const n=await fetch(e);if(!n.ok)throw new Error(`Failed to fetch worker script (${n.status}): ${e}`);const r=await n.blob();t=URL.createObjectURL(r),Ir.set(e,t)}return new Worker(t,{name:"visemeDiffPreview"})}function qa(){return typeof Worker<"u"&&typeof OffscreenCanvas<"u"}function Cn(e,t){(e.width!==t.width||e.height!==t.height)&&(e.width=t.width,e.height=t.height);const n=e.getContext("2d");n&&n.drawImage(t,0,0)}function Ar(e,t){let n=0,r=null;const i=Jn(async(s,o)=>(await Pn(),await Mn(e,s),i.isLatestSeq(o)));return{usesWorker:!1,usesPixi:!1,async loadAssets(s){const o=await Pn(s);return r=o.visemePaths?new Set(o.visemePaths):null,o},getVisemeAtlasPaths(){return r},async renderSilOnly(){n+=1,i.reset(),await ga(e)},drawLiveFrame(s,o,a,l){i.enqueue(o,a,l)},async compositePrefetchFrame(s,o){try{return await wa(s)}catch{return null}},blitBitmap(s,o){Cn(s,o)},drawIdleVideo(){},beginIdleToSilCrossfade(){},tickIdleToSilCrossfade(){return!1},finishIdleToSilCrossfade(){},isIdleToSilCrossfading(){return!1},supportsBufferedPlayback:!0,async renderViseme(s,o){n+=1;const a=n;t.onStatus?.(o),await Mn(s,{mouthPath:_t(o),expressionPath:null})},dispose(){n+=1,i.reset()}}}function Ga(e,t,n){let r=null,i=1,s=0,o=!1,a=!1,l=null;const f=new Map,u=new Map;let c=Gt;const d=Jn(async(E,g,I)=>(f.set(g,{drawKey:I.drawKey,onDisplayed:I.onDisplayed}),await P({type:"drawFrame",diffPath:E.mouthPath,expressionDiffPath:E.expressionPath,liveSeq:g},void 0,!0),!1)),p=E=>{if(E===Er){let N=-1,A;for(const[ee,fe]of f)ee>=N&&(N=ee,A=fe);N>=0&&f.delete(N),A?.onDisplayed?.(A.drawKey);return}const g=-E,I=f.get(g);f.delete(g),I?.onDisplayed?.(I.drawKey)},T=new Map,m=(E,g)=>{a||!r||r.postMessage(E,[])},P=(E,g,I=!1)=>{if(a)return Promise.resolve();const N=i++;return new Promise((A,ee)=>{T.set(N,{resolve:fe=>A(fe),reject:ee,generation:typeof E.generation=="number"?E.generation:void 0,expectRenderDone:I}),m({...E,requestId:N})})},C=(async()=>{r=await ja(n),r.onmessage=E=>{if(a)return;const g=E.data;if(g.type==="status"){t.onStatus?.(g.label);return}if(g.type==="frame"){if(g.generation<=-Gt){const A=-g.generation,ee=u.get(A);u.delete(A),ee?.resolve(g.bitmap);return}const N=g.generation<0;if(!N&&g.generation!==s){g.bitmap.close();return}if(N&&!(g.generation===Er)){const ee=-g.generation;if(!d.isLatestSeq(ee)){Je()?.onWorkerStale(),g.bitmap.close();return}}if(N&&t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()){Je()?.onWorkerStale(),g.bitmap.close();return}Cn(e,g.bitmap),g.bitmap.close(),N&&p(g.generation);return}const I=T.get(g.requestId);if(I)switch(g.type){case"ready":T.delete(g.requestId),I.resolve();break;case"loadAssetsDone":T.delete(g.requestId),l=g.visemePaths?.length?new Set(g.visemePaths):null,I.resolve({width:g.width,height:g.height,visemePaths:g.visemePaths});break;case"renderDone":if(I.expectRenderDone&&I.generation!=null&&g.generation!==I.generation)return;T.delete(g.requestId),I.resolve();break;case"renderAborted":T.delete(g.requestId),I.resolve();break;case"error":T.delete(g.requestId),t.onError?.(g.message),I.reject(new Error(g.message));break}},r.onerror=E=>{if(a)return;const g=E.message||"Worker error";t.onError?.(g);for(const[,I]of T)I.reject(new Error(g));T.clear()},await P({type:"init"}),o=!0})();return{usesWorker:!0,usesPixi:!1,async loadAssets(E){if(a)return{width:842,height:1264};if(await C,a)return{width:842,height:1264};if(!o)throw new Error("Worker init failed");return await P({type:"loadAssets",keyHex:E,urls:rs(ut())})??{width:842,height:1264}},getVisemeAtlasPaths(){return l},async renderSilOnly(){if(a||(await C,a))return;s+=1,d.reset(),f.clear(),u.forEach(({resolve:g})=>g(null)),u.clear(),c=Gt;const E=s;await P({type:"cancelLiveDraws"}),await P({type:"renderSil",generation:E},void 0,!0)},drawLiveFrame(E,g,I,N){a||C.then(()=>{a||d.enqueue(g,I,N)})},compositePrefetchFrame(E,g){return a?Promise.resolve(null):C.then(()=>{if(a)return null;const I=++c;return new Promise(N=>{u.set(I,{resolve:N}),P({type:"drawFrame",diffPath:E.mouthPath,expressionDiffPath:E.expressionPath,liveSeq:I},void 0,!0).catch(()=>{u.delete(I),N(null)})})})},blitBitmap(E,g){Cn(E,g)},drawIdleVideo(){},beginIdleToSilCrossfade(){},tickIdleToSilCrossfade(){return!1},finishIdleToSilCrossfade(){},isIdleToSilCrossfading(){return!1},supportsBufferedPlayback:!0,async renderViseme(E,g,I={}){if(a||(await C,a))return;s+=1,d.reset(),f.clear();const N=s;try{await P({type:"cancelLiveDraws"}),await P({type:"renderViseme",generation:N,to:g,from:I.from,transitionDurationMs:I.transitionDurationMs,gapMs:I.gapMs,threshold:I.threshold},void 0,!0)}catch(A){if(A?.name==="AbortError")return;throw A}},dispose(){if(!a){a=!0,s+=1,d.reset(),f.clear(),u.forEach(({resolve:E})=>E(null)),u.clear(),c=Gt;for(const[,E]of T)E.resolve();T.clear(),r?.terminate(),r=null}}}}async function Ya(e,t){const n=await Ka(e,{onWebGlContextLost:t.onWebGlContextLost,maxTextureSize:t.pixiMaxTextureSize});let r=0,i=null,s=!1;const o=Jn(async(a,l)=>s?!1:t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()?(Je()?.onWorkerStale(),!1):(n.drawLiveFrame(a),o.isLatestSeq(l)));return{usesWorker:!1,usesPixi:!0,async loadAssets(a){if(s)return{width:842,height:1264};const l=await n.loadAssets(a);return i=l.visemePaths?.length?new Set(l.visemePaths):null,l},getVisemeAtlasPaths(){return i},async renderSilOnly(){s||(r+=1,o.reset(),n.renderSilOnly())},drawLiveFrame(a,l,f,u){s||o.enqueue(l,f,u)},async compositePrefetchFrame(a,l){if(s)return null;try{return await n.compositePrefetchFrame(a)}catch{return null}},blitBitmap(a,l){s||t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()||n.blitBitmap(l)},drawIdleVideo(a,l){s||n.drawIdleVideo(a,l)},beginIdleToSilCrossfade(a){s||n.beginIdleToSilCrossfade(a)},tickIdleToSilCrossfade(a){return s?!1:n.tickIdleToSilCrossfade(a)},finishIdleToSilCrossfade(){s||n.finishIdleToSilCrossfade()},isIdleToSilCrossfading(){return s?!1:n.isIdleToSilCrossfading()},supportsBufferedPlayback:!1,async renderViseme(a,l){if(s)return;r+=1;const f=r;o.reset(),t.onStatus?.(l),n.drawLiveFrame({mouthPath:_t(l),expressionPath:null})},dispose(){s||(s=!0,r+=1,o.reset(),n.dispose())}}}function Pr(e,t){if(!qa())return Ar(e,t);const n=Wi(t.workerScriptUrl);try{return Ga(e,t,n)}catch{return Ar(e,t)}}function Qa(e,t={}){if(t.preferLegacyRenderer)return Pr(e,t);let n=null,r=!1,i=null,s=!1;const o=()=>n?Promise.resolve(n):(i||(i=(async()=>{try{const a=await Ya(e,t);if(s)throw a.dispose(),new Error("Renderer disposed during Pixi init");return r=!0,n=a,a}catch(a){if(s)throw a instanceof Error?a:new Error(String(a));return console.warn("[AiTwin] Pixi WebGL renderer unavailable, using Canvas2D fallback:",a),n=Pr(e,t),r=!1,n}})()),i);return{get usesWorker(){return n?.usesWorker??!1},get usesPixi(){return r},async loadAssets(a){return(await o()).loadAssets(a)},getVisemeAtlasPaths(){return n?.getVisemeAtlasPaths()??null},async renderSilOnly(){return(await o()).renderSilOnly()},drawLiveFrame(a,l,f,u){o().then(c=>{s||c.drawLiveFrame(a,l,f,u)})},async compositePrefetchFrame(a,l){return(await o()).compositePrefetchFrame(a,l)},blitBitmap(a,l){n&&n.blitBitmap(a,l)},drawIdleVideo(a,l){n?.usesPixi&&n.drawIdleVideo(a,l)},beginIdleToSilCrossfade(a){n?.beginIdleToSilCrossfade(a)},tickIdleToSilCrossfade(a){return n?.tickIdleToSilCrossfade(a)??!1},finishIdleToSilCrossfade(){n?.finishIdleToSilCrossfade()},isIdleToSilCrossfading(){return n?.isIdleToSilCrossfading()??!1},get supportsBufferedPlayback(){return n?.supportsBufferedPlayback??!1},async renderViseme(a,l,f){return(await o()).renderViseme(a,l,f)},dispose(){s=!0,i=null,n?.dispose(),n=null}}}class Xa extends Error{constructor(t,n){super(`${t} timed out after ${Math.round(n/1e3)}s`),this.name="LoadTimeoutError"}}function bn(e,t,n){return new Promise((r,i)=>{const s=globalThis.setTimeout(()=>{i(new Xa(n,t))},t);e.then(o=>{globalThis.clearTimeout(s),r(o)},o=>{globalThis.clearTimeout(s),i(o)})})}const Ja={position:"relative",display:"inline-block",lineHeight:0},Za={display:"block",maxWidth:"100%",height:"auto"},eo={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"rgba(0,0,0,0.55)",color:"#fff",fontSize:"0.875rem",textAlign:"center"};function It(e){return ji(e)?Wn:Un}function qe(e,t){return t?.isSpeaking()?t:e.isSpeaking()?e:t?.isConnected()?t:e}const Ai=w.forwardRef(function({id:t,avatarId:n,faceId:r,assets:i,authToken:s,apiBase:o,ttsEngineId:a=it,voiceId:l,speakingRate:f=Bt,className:u,style:c,canvasStyle:d,onStatusChange:p,onDisplayStatus:T,onError:m,onReady:P,showErrorOverlay:C=!0,onUserTranscript:E,onBotOutput:g,onRealtimeLipsyncDebug:I,onFrameRenderStats:N,lipsyncBufferedPlayback:A=!0,lipsyncPlaybackWarmupMs:ee=1500,pixiMaxTextureSize:fe,captions:M},W){const K=w.useRef(null),Q=w.useRef(null),Y=w.useRef(null),de=w.useRef(A);de.current=A;const F=w.useRef(ee);F.current=ee;const Z=w.useRef(0),k=w.useRef(Qn()),q=w.useRef(aa()),re=w.useRef(!1),oe=w.useRef(null),ne=w.useRef(null),te=w.useRef(0),ie=w.useRef(0),we=w.useRef(0),b=w.useRef(null),$=w.useRef(null),S=w.useRef(!1),O=w.useRef(!1),D=w.useRef(!1),V=w.useRef(!1),_=w.useRef("sil"),v=w.useRef(0),x=w.useRef(!1),H=w.useRef(null),X=w.useRef(!1),[se,Ee]=w.useState("idle"),[_e,Ve]=w.useState(null),[Ue,fn]=w.useState(!1),[Zn,Ft]=w.useState(!1),[h,L]=w.useState({width:842,height:1264}),[J,ce]=w.useState(null),[Se,ve]=w.useState(0),ye=w.useRef(!1),Ie=w.useRef(s??null),Te=o?.trim()||at,lt=w.useRef(null),ke=w.useRef(null),Pe=w.useRef(!1),Ze=w.useRef({width:842,height:1264}),Ye=w.useRef(null),Lt=w.useRef("sil"),We=w.useRef(""),Fe=w.useMemo(()=>_a(M),[M]),Le=w.useCallback(()=>{We.current="",ce(null)},[]);w.useEffect(()=>{Fe.enabled||Le()},[Fe.enabled,Le]);const et=w.useCallback(y=>{if(!Fe.enabled)return;const R=y.isSpeaking(),U=y.isWarmingUp();if(!R||U){We.current&&Le();return}const B=ya(y.getWordQueue());if(!B){We.current&&Le();return}B!==We.current&&(We.current=B,ce(B))},[Fe.enabled,Le]),ge=w.useRef(void 0),Me=w.useRef(new Map),He=w.useRef(P),me=w.useRef(T),Tt=w.useRef(m),Ot=w.useRef(E),kt=w.useRef(g),ft=w.useRef(I),er=w.useRef(N),dt=w.useRef(xa());He.current=P,me.current=T,Tt.current=m,Ot.current=E,kt.current=g,ft.current=I,er.current=N,w.useEffect(()=>{const y=dt.current;return _r(y),()=>_r(null)},[]);const tr=w.useCallback(y=>{const R=y?.ttsEngineId??a??ke.current?.ttsEngineId??it,U=y?.voiceId??l??ke.current?.voiceId??It(R);return{ttsEngineId:R,voiceId:U}},[a,l]),Qe=w.useCallback(y=>{Ve(y),Tt.current?.(y)},[]),xt=w.useCallback(y=>{Ee(y),p?.(y)},[p]),ue=w.useRef(In(xt,Te,{onLipsyncDebug:y=>ft.current?.(y)})),le=w.useRef(null);w.useEffect(()=>(ue.current=In(xt,Te,{onLipsyncDebug:y=>ft.current?.(y)}),s&&ue.current.setDeveloperToken(s),ue.current.setTtsEngineId(a),()=>{ue.current.stop();const y=le.current;y&&(y.disconnect(),le.current=null)}),[xt,s,a,Te]);const nr=w.useCallback(()=>(le.current||(le.current=fi(xt,{speakingRate:f,onUserTranscript:(y,R)=>Ot.current?.(y,R),onBotOutput:y=>kt.current?.(y),onLipsyncDebug:y=>ft.current?.(y)}),le.current.setTtsEngineId(a)),le.current),[xt,f,a]),Ce=w.useCallback(()=>{b.current!=null&&(clearTimeout(b.current),b.current=null)},[]),Re=w.useCallback(()=>{$.current!=null&&(clearTimeout($.current),$.current=null),D.current=!1},[]),Nt=w.useCallback(()=>{if(V.current)return;const y=Q.current;if(V.current=!0,Re(),S.current=!1,O.current=!1,!X.current||!H.current){y?.renderSilOnly();return}H.current.setActive(!1);const R=H.current.getVideo();if(y?.usesPixi){y.drawIdleVideo(R),y.beginIdleToSilCrossfade(Sr);return}(async()=>{const U=K.current;U&&await vn(U,R,null,void 0,Ze.current).catch(()=>{}),await new Promise(B=>setTimeout(B,Sr)),V.current&&await y?.renderSilOnly()})()},[Re]),rr=w.useCallback(()=>{!X.current||!H.current||(V.current=!1,Q.current?.finishIdleToSilCrossfade(),Re(),D.current=!0,$.current=setTimeout(()=>{if($.current=null,qe(ue.current,le.current).isSpeaking()){D.current=!1;return}if(S.current){D.current=!1;return}const y=H.current;if(!y){D.current=!1;return}y.restart(),y.setActive(!0);const R=y.getVideo();let U=!1;const B=()=>{U||(U=!0,R.removeEventListener("playing",j),D.current=!1)},j=()=>{B()};if(R.addEventListener("playing",j,{once:!0}),R.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&!R.paused){B();return}setTimeout(B,300)},Ea))},[Re]),mt=w.useCallback(()=>{if(Ce(),me.current?.("sil"),S.current=!1,V.current=!1,!X.current||!H.current){D.current=!1;return}rr()},[Ce,rr]),dn=w.useCallback(async y=>{const R=ie.current,U=Q.current,B=K.current,j=()=>{y?.fallbackOnly||(S.current=!1)};if(!U||!B||!Ue){j();return}if(qe(ue.current,le.current).isSpeaking()){j();return}if(y?.fallbackOnly){if(!S.current||(Be(k.current),await U.renderSilOnly(),R!==ie.current)||qe(ue.current,le.current).isSpeaking())return;mt();return}if(br(k.current)){Be(k.current),mt();return}if(de.current&&U.supportsBufferedPlayback&&!y?.fallbackOnly){if(Be(k.current),Y.current?.reset(),await U.renderSilOnly(),R!==ie.current||qe(ue.current,le.current).isSpeaking())return;mt();return}const Ae=Ca(qe(ue.current,le.current).getVisemeQueue(),v.current,_.current),Oe=Ra(Ae,Ye.current);if(Be(k.current),!Oe){if(await U.renderSilOnly(),R!==ie.current||qe(ue.current,le.current).isSpeaking())return;mt();return}try{await U.renderViseme(B,"sil",{from:Ae,transitionDurationMs:ki})}catch(De){if(De?.name!=="AbortError")throw De}if(R!==ie.current){j();return}if(qe(ue.current,le.current).isSpeaking()){j();return}mt()},[Ue,mt]),ht=w.useCallback(()=>{if(O.current||S.current)return;O.current=!0,S.current=!0,Ce();const y=ie.current;dn().finally(()=>{O.current=!1}),b.current=setTimeout(()=>{b.current=null,y===ie.current&&dn({fallbackOnly:!0})},Da())},[Ce,dn]),ir=w.useCallback(async()=>{const y=Math.floor(Date.now()/1e3);if(lt.current&&y<lt.current.expiresAt-60)return lt.current.key;const R=Ie.current??await Pt();Ie.current=R,ue.current.setDeveloperToken(R);const U=await Zi(R,Te);return lt.current={key:U.value,expiresAt:U.expiresAt},U.value},[Te]);w.useEffect(()=>{s&&(Ie.current=s,ue.current.setDeveloperToken(s))},[s]),w.useEffect(()=>{ue.current.setTtsEngineId(a),le.current?.setTtsEngineId(a),ke.current&&(ke.current.ttsEngineId=a)},[a]),w.useEffect(()=>{const y=l??It(a);ke.current&&(ke.current.voiceId=y)},[l,a]);const tt=w.useMemo(()=>Nr(n,r),[n,r]),Di=w.useMemo(()=>i?JSON.stringify(i):tt?`face:${tt}`:`id:${t??""}`,[i,tt,t]);return w.useEffect(()=>{if(!t&&!i&&!tt){Qe("AiTwin requires `assets`, `avatarId`/`faceId`, or `id`");return}let y=!1;Pe.current=!1,fn(!1),Ft(!1),Ve(null),ke.current=null,H.current=null,X.current=!1;const R=K.current;if(!R)return;let U=null;return(async()=>{try{let B,j,xe,Ae;if(i)B=i,j=a,xe=l??It(j);else if(tt)me.current?.("loadFace"),B=xn(tt),j=a,xe=l??It(j);else{me.current?.("getAiTwin");const G=await bn(Or(t),3e4,"getAiTwin");if(y)return;if(!G.faceId?.trim())throw new Error("getAiTwin returned no faceId");j=G.ttsEngineId,xe=l??G.voiceId??It(j),Ae=G.knowledgeContextId?.trim()||void 0,B=xn(G.faceId)}ke.current={ttsEngineId:j,voiceId:xe,personaId:Ae},Vr(B),H.current=oa();const Oe=!!(i&&!ct(i));U=Qa(R,{preferLegacyRenderer:Oe,pixiMaxTextureSize:fe,onStatus:G=>{y||me.current?.(G)},onError:G=>{y||Qe(G)},shouldAcceptLiveFrame:()=>{if(re.current)return!0;if(S.current)return!1;const G=qe(ue.current,le.current);return G.isSpeaking()||G.isWarmingUp()},onWebGlContextLost:()=>{y||ye.current||(ye.current=!0,queueMicrotask(()=>{y||ve(G=>G+1)}))}}),Q.current=U,Y.current=Na(U),ye.current=!1,(G=>{const ae=()=>{if(!G||F.current<=0)return!1;const be=Q.current;return be?de.current&&be.supportsBufferedPlayback?!0:be.usesPixi:!1};ue.current.setLipsyncWarmupHold(G,ae),le.current?.setLipsyncWarmupHold(G,ae)})(!0),me.current?.("auth");const ze=Ie.current??s??await bn(Pt(),3e4,"getAuthToken");if(y)return;Ie.current=ze,ue.current.setDeveloperToken(ze),ue.current.setTtsEngineId(j);const Vt=Rt()?await ir():void 0;if(y)return;me.current?.("loadAssets");const he=await bn(U.loadAssets(Vt),18e4,"load face assets");if(!y&&he.width>0&&he.height>0&&(Ze.current=he,L(he)),y)return;Ye.current=U.getVisemeAtlasPaths(),Pe.current=!0,fn(!0),He.current?.(),U.renderSilOnly().then(()=>{y||me.current?.("sil")}),(async()=>{try{const G=await Os(Vt);if(await H.current.load(G),y)return;X.current=!0,Ft(!0),Be(k.current),H.current.setActive(!0);const ae=H.current.getVideo();U.usesPixi?U.drawIdleVideo(ae):await vn(R,ae,null,void 0,Ze.current),y||me.current?.("idle")}catch(G){if(y)return;X.current=!1,Ft(!1),console.warn("[AiTwin] Idle video unavailable:",G)}})()}catch(B){if(y)return;if(B instanceof Yt){Qe(B.message);return}Qe(B instanceof Error?B.message:"Failed to load AI twin")}})(),()=>{y=!0,H.current?.dispose(),U?.dispose(),Q.current=null}},[Di,i,tt,t,a,l,s,fe,ir,Qe,Se]),w.useEffect(()=>{const y={current:!1},R=()=>{const U=K.current,B=Q.current,j=qe(ue.current,le.current);if(!U||!B||!Ue){te.current=requestAnimationFrame(R);return}if(document.hidden){H.current?.setActive(!1),te.current=requestAnimationFrame(R);return}const xe=j.isSpeaking(),Ae=j.isWarmingUp(),Oe=xe&&!x.current,De=x.current&&!xe;Oe&&(Ce(),Re(),S.current=!1,O.current=!1,Be(k.current),Y.current?.reset(),dt.current.reset(),ge.current=void 0,we.current=0,_.current="sil",v.current=0,Nt()),De&&(q.current.reset(),H.current?.setActive(!1),Y.current?.reset(),B.finishIdleToSilCrossfade(),Le(),ht());const ze=De||S.current||D.current||V.current,Vt=A&&B.supportsBufferedPlayback;if(Ae){if(Nt(),X.current&&H.current?.setActive(!1),B.usesPixi&&B.isIdleToSilCrossfading()){B.tickIdleToSilCrossfade(performance.now()),j.getVisemeQueue().length>0&&Z.current===0&&(Z.current=performance.now()),x.current=j.isSpeaking(),te.current=requestAnimationFrame(R);return}const he=j.getVisemeQueue();he.length>0&&Z.current===0&&(Z.current=performance.now()),q.current.advance(performance.now());const G=q.current.getExpressionPath(),ae=q.current.getDrawKey(),be={queue:he,elapsedMs:0,expressionPath:G,expressionDrawKey:ae,availablePaths:Ye.current};let Ne=!1;Vt&&Y.current?(Y.current.warmupTick(be),Ne=Y.current.isWarmupReady(be,F.current)):B.usesPixi&&Tr(U,he,0,G,ae,k.current,(pt,Ut,mn,Wt)=>{B.drawLiveFrame(pt,Ut,mn,Ke=>{Wt?.(Ke),j.isWarmingUp()&&Ke!==""&&!br({lastDrawnKey:Ke})&&(Z.current=0,j.releaseWarmupHold())})},pt=>{me.current?.(pt.label)},Ye.current);const Xe=Z.current>0&&performance.now()-Z.current>$i;me.current?.(Ne?"buffer ready":"buffering lipsync…"),(Ne||Xe)&&(Z.current=0,j.releaseWarmupHold()),et(j),x.current=j.isSpeaking(),te.current=requestAnimationFrame(R);return}if(xe){Nt(),X.current&&H.current?.setActive(!1),B.usesPixi&&B.isIdleToSilCrossfading()&&B.finishIdleToSilCrossfade();const he=j.getVisemeQueue(),G=j.getPlaybackElapsedMs();Ts(he,G),v.current=G;const ae=he.length>0?Dt(he,G):"sil";ae!=="sil"&&(_.current=ae);const be=fa(G,j.getSentenceEmotions(),j.getWordQueue(),j.getStreamMood());q.current.setTargetEmotion(be),q.current.setTargetEyebrow(sa(G,j.getWordQueue(),st(be))),q.current.advance(performance.now());const Ne=q.current.getExpressionPath(),Xe=q.current.getDrawKey(),pt=(Ke,hn,Et,pn)=>{const sr={label:Lt.current,elapsedMs:G,mouthPath:hn.mouthPath,transitionMeta:ge.current};Me.current.set(Et,sr),Y.current?.markExternallyDisplayed(Et,Ne),B.drawLiveFrame(Ke,hn,Et,Ht=>{const Bi=Me.current.get(Ht)??sr;Me.current.delete(Ht),dt.current.onDrawDisplayed(Bi,he),Y.current?.markExternallyDisplayed(Ht,Ne),pn?.(Ht)})},Ut=Ke=>{Lt.current=Ke.label,ge.current=Ke.transitionMeta,me.current?.(Ke.label)},mn=A&&B.supportsBufferedPlayback;let Wt=!1;mn&&Y.current&&(Wt=Y.current.tick({canvas:U,queue:he,elapsedMs:G,expressionPath:Ne,expressionDrawKey:Xe,playbackState:k.current,availablePaths:Ye.current,onStatus:Ut,onDisplayed:(hn,Et,pn)=>{dt.current.onDrawDisplayed({label:pn,elapsedMs:G,mouthPath:Et,transitionMeta:ge.current},he)}}).usedBuffer),Wt||Tr(U,he,G,Ne,Xe,k.current,pt,Ut,Ye.current),dt.current.onRafTickSpeaking(),er.current?.(dt.current.snapshot(he,G))}else if(!ze&&re.current){H.current?.setActive(!1),q.current.advance(performance.now());const he=q.current.getExpressionPath(),G=q.current.getDrawKey();Sn(U,he,G,k.current,(ae,be,Ne,Xe)=>B.drawLiveFrame(ae,be,Ne,Xe),ae=>{if(ne.current){me.current?.(ne.current);return}const be=q.current.getTargetEmotion();me.current?.(ae==="sil"||ae==="blink"?`${be}${ae==="blink"?" · blink":""}`:ae)},null,oe.current)}else if(!ze&&X.current&&H.current){const he=H.current,G=he.getVideo();if(G.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){he.setActive(!0);const ae=()=>!j.isSpeaking()&&!S.current&&!D.current&&!re.current;B.usesPixi?(B.drawIdleVideo(G,ae),ae()&&me.current?.("idle")):y.current||(y.current=!0,vn(U,G,null,void 0,Ze.current,ae).then(()=>me.current?.("idle")).finally(()=>{y.current=!1}))}else Sn(U,null,"__sil__",k.current,(ae,be,Ne,Xe)=>B.drawLiveFrame(ae,be,Ne,Xe),ae=>me.current?.(ae))}else ze||Sn(U,null,"__sil__",k.current,(he,G,ae,be)=>B.drawLiveFrame(he,G,ae,be),he=>me.current?.(he));Fe.enabled&&et(j),x.current=xe,te.current=requestAnimationFrame(R)};return te.current=requestAnimationFrame(R),()=>{cancelAnimationFrame(te.current),Ce(),Re(),ue.current.stop(),le.current?.stop()}},[Ue,Zn,ht,Ce,Re,Nt,et,Le,Fe.enabled]),w.useImperativeHandle(W,()=>({speakText:async(y,R)=>{const U=y.trim();if(!U)return;const B=Q.current;if(!B||!Pe.current&&!Ue)throw new Error("AI twin is not ready");const{ttsEngineId:j,voiceId:xe}=tr(R);Ve(null),Le(),ie.current+=1,Ce(),Re(),S.current=!1,O.current=!1,_.current="sil",v.current=0,Be(k.current),re.current=!1,oe.current=null,ne.current=null,q.current.reset(),x.current=!1,V.current=!1,B.finishIdleToSilCrossfade();try{await ue.current.speak(U,{voiceId:xe,speakingRate:R?.speakingRate??f,ttsEngineId:j})}catch(Ae){throw V.current=!1,B.finishIdleToSilCrossfade(),ht(),Qe(Ae instanceof Error?Ae.message:"TTS failed"),Ae}},stop:()=>{ie.current+=1,Ce(),Re(),S.current=!1,O.current=!1,V.current=!1,Q.current?.finishIdleToSilCrossfade(),ue.current.stop(),le.current?.stop(),Be(k.current),Y.current?.reset(),Z.current=0,x.current=!1,Le(),ht()},setTtsEngineId:y=>{ue.current.setTtsEngineId(y),le.current?.setTtsEngineId(y),ke.current&&(ke.current.ttsEngineId=y)},renderViseme:async(y,R)=>{const U=Q.current,B=K.current;if(!U||!B||!Pe.current)throw new Error("AI twin is not ready");await U.renderViseme(B,y,{from:R?.from,transitionDurationMs:R?.transitionDurationMs,gapMs:R?.gapMs,onStatus:j=>me.current?.(j)})},setEmotion:y=>{if(!Pe.current)throw new Error("AI twin is not ready");const R=Q.current,U=K.current;if(!R||!U)throw new Error("AI twin is not ready");ie.current+=1,Ce(),Re(),S.current=!1,O.current=!1,D.current=!1,V.current=!1,ue.current.stop(),le.current?.stop(),Be(k.current),Y.current?.reset(),Z.current=0,x.current=!1,R.finishIdleToSilCrossfade(),H.current?.setActive(!1);const B=Ge(y);re.current=!0,oe.current=null,ne.current=null,q.current.snapToEmotion(B);const j=q.current.getExpressionPath(),xe=q.current.getDrawKey(),Ae={mouthPath:null,expressionPath:j},Oe=Ct(Ae,xe);k.current.lastDrawnKey="",R.drawLiveFrame(U,Ae,Oe,ze=>{ze===Oe&&(k.current.lastDrawnKey=Oe)});const De=st(B);me.current?.(j?`${B} · brow ${De>0?"+":""}${De}`:`${B} · brow 0 (sil base)`)},getEmotion:()=>re.current?q.current.getTargetEmotion():null,clearEmotionPreview:()=>{re.current=!1,oe.current=null,ne.current=null,q.current.reset(),Be(k.current),me.current?.("idle")},setViseme:y=>{if(!Pe.current)throw new Error("AI twin is not ready");const R=Q.current,U=K.current;if(!R||!U)throw new Error("AI twin is not ready");ie.current+=1,Ce(),Re(),S.current=!1,O.current=!1,D.current=!1,V.current=!1,ue.current.stop(),le.current?.stop(),Be(k.current),Y.current?.reset(),Z.current=0,x.current=!1,R.finishIdleToSilCrossfade(),H.current?.setActive(!1);const B=rn(y);re.current=!0,ne.current=B,oe.current=B==="sil"?null:_t(B),q.current.snapToEmotion("neutral");const j=q.current.getExpressionPath(),xe=q.current.getDrawKey(),Oe={mouthPath:oe.current,expressionPath:j},De=Ct(Oe,xe);k.current.lastDrawnKey="",R.drawLiveFrame(U,Oe,De,ze=>{ze===De&&(k.current.lastDrawnKey=De)}),me.current?.(B)},getViseme:()=>re.current?ne.current:null,isReady:()=>Pe.current,getStatus:()=>se,connect:async(y={})=>{Ve(null);try{let R=y.authToken?.trim();R||(R=Ie.current??s??await Pt(),Ie.current=R);const U=y.voiceId?.trim()??l??ke.current?.voiceId,B=y.personaId?.trim()??ke.current?.personaId,j=nr();await j.unlockAudio(),await j.connect({...y,apiBase:y.apiBase?.trim()||Te,authToken:R,voiceId:U,personaId:B,speakingRate:y.speakingRate??f})}catch(R){throw Qe(R instanceof Error?R.message:"Voice connect failed"),R}},disconnect:async()=>{const y=le.current;y&&(ie.current+=1,Ce(),Re(),S.current=!1,O.current=!1,V.current=!1,Q.current?.finishIdleToSilCrossfade(),Be(k.current),Y.current?.reset(),Z.current=0,x.current=!1,await y.disconnect(),ht())},isConnected:()=>le.current?.isConnected()??!1,getVoiceStream:()=>le.current?.getVoiceStream()??ue.current?.getVoiceStream()??null,setMuted:y=>{const R=ue.current,U=le.current;R?.setMuted?.(y),U?.setMuted?.(y)},isMuted:()=>{const y=le.current,R=ue.current;return y?.isMuted?.()??R?.isMuted?.()??!1},getPersonaId:()=>ke.current?.personaId?.trim()||null}),[Ue,f,s,l,Ce,Re,ht,Qe,tr,nr,se,Te]),z.jsxs("div",{className:u,style:{...Ja,...c},children:[z.jsx("canvas",{ref:K,width:h.width,height:h.height,style:{...Za,...d},"aria-label":t?`AI twin ${t}`:"AI twin face"}),C&&_e?z.jsx("div",{style:eo,children:_e}):null,Fe.enabled&&J?z.jsx(Ta,{text:J,style:Fe.style},J):null]})});async function to(e){try{const t=await e.json();if(typeof t.detail=="string"&&t.detail.trim())return t.detail;if(typeof t.error=="string"&&t.error.trim())return t.error}catch{}return`avatarReply failed (${e.status})`}async function Pi(e){const t=e.message.trim();if(!t)throw new Error("Message is required");const n=e.authToken.trim();if(!n)throw new Error("Auth token is required");const r=(e.apiBase?.trim()||at).replace(/\/$/,""),i=await fetch(`${r}/avatarReply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,Accept:"text/event-stream"},body:JSON.stringify({message:t,history:e.history??[],persona_id:e.personaId?.trim()||""})});if(!i.ok)throw new Error(await to(i));if(!i.body)throw new Error("avatarReply response body is empty");const s=i.body.getReader(),o=new TextDecoder;let a="",l="",f="",u="";for(;;){const{done:c,value:d}=await s.read();if(c)break;a+=o.decode(d,{stream:!0});const p=a.split(`
|
|
48
|
-
`);a=p.pop()||"";for(const T of p){if(T.startsWith("event: ")){u=T.slice(7).trim();continue}if(!T.startsWith("data: "))continue;const m=T.slice(6).trim();if(!m)continue;let P;try{P=JSON.parse(m)}catch{continue}if(u==="spokenText")l=P.text||"",e.onSpokenText?.(l);else if(u==="displayText")f=P.text||"";else if(u==="error")throw new Error(P.error||"avatarReply stream error")}}if(!l.trim()||!f.trim())throw new Error("avatarReply stream missing displayText or spokenText");return{displayText:f.trim(),spokenText:l.trim()}}function no({muted:e}){return e?z.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[z.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),z.jsx("path",{d:"m16 9.5 5 5m0-5-5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):z.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[z.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),z.jsx("path",{d:"M15.5 8.5a4.5 4.5 0 0 1 0 7M18.5 6a8 8 0 0 1 0 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}function ro(){return z.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:z.jsx("path",{d:"M8 5.5v13l11-6.5L8 5.5Z"})})}function io(){return z.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:z.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}function so(){return z.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:z.jsx("path",{d:"M5 6.5A2.5 2.5 0 0 1 7.5 4h9A2.5 2.5 0 0 1 19 6.5v7A2.5 2.5 0 0 1 16.5 16H10l-4 3.5V16H7.5A2.5 2.5 0 0 1 5 13.5v-7Z",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round"})})}function Mi({className:e}){return z.jsx("span",{className:e??"aitwin-widget__spinner","aria-hidden":!0,children:z.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:z.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeDasharray:"40 20"})})})}function ao({muted:e,onToggle:t}){return z.jsx("button",{type:"button",className:"aitwin-widget__mute",onClick:t,"aria-label":e?"Unmute":"Mute","aria-pressed":e,children:z.jsx(no,{muted:e})})}function oo(){return z.jsxs("div",{className:"aitwin-widget__connecting",role:"status","aria-live":"polite",children:[z.jsx(Mi,{className:"aitwin-widget__spinner aitwin-widget__spinner--accent"}),z.jsx("span",{children:"Connecting..."})]})}function co(e){const t=e.connecting||e.textSending||e.status==="loading"||e.status==="speaking",n=e.connecting?"Connecting...":e.connected?"End Talk":"Talk",r=["aitwin-widget__action",e.textMode&&!e.connecting?"":"aitwin-widget__action--primary",e.connecting?"aitwin-widget__action--connecting":""].filter(Boolean).join(" ");return z.jsxs("div",{className:"aitwin-widget__controls",children:[z.jsxs("div",{className:"aitwin-widget__actions",children:[z.jsxs("button",{type:"button",className:r,onClick:e.onTalk,disabled:!e.ready||e.connecting||e.textSending,"aria-busy":e.connecting,children:[e.connecting?z.jsx(Mi,{className:"aitwin-widget__spinner aitwin-widget__spinner--on-accent"}):e.connected?z.jsx(io,{}):z.jsx(ro,{}),z.jsx("span",{children:n})]}),z.jsxs("button",{type:"button",className:e.textMode?"aitwin-widget__action aitwin-widget__action--primary":"aitwin-widget__action",onClick:e.onTextMode,disabled:!e.ready||e.connecting||e.textSending,"aria-pressed":e.textMode,children:[z.jsx(so,{}),z.jsx("span",{children:"Text"})]})]}),e.textMode?z.jsxs("form",{className:"aitwin-widget__composer",onSubmit:i=>{i.preventDefault(),e.onSendText()},children:[z.jsx("input",{type:"text",className:"aitwin-widget__composer-input",value:e.textDraft,onChange:i=>e.onTextDraftChange(i.target.value),placeholder:e.textSending?"Getting reply...":"Type a message…",autoComplete:"off",disabled:!e.ready||t}),z.jsx("button",{type:"submit",className:"aitwin-widget__composer-send",disabled:!e.ready||t||!e.textDraft.trim()&&!e.textSending,"aria-busy":e.textSending,children:e.textSending?"…":"Send"})]}):null,e.error?z.jsx("p",{className:"aitwin-widget__controls-error",role:"alert",children:e.error}):null]})}function Mr(e){const t=e.id?.trim()||void 0,n=e.faceId?.trim()||e.avatarId?.trim()||void 0;return{id:n?void 0:t,faceId:n,authToken:e.authToken?.trim()||void 0,apiBase:e.apiBase?.trim()||void 0,voiceId:e.voiceId?.trim()||void 0,speakingRate:e.speakingRate}}function uo(e){return[e.id??"",e.faceId??"",e.authToken?.slice(0,16)??"",e.voiceId??"",e.apiBase??"",String(e.speakingRate??"")].join("|")}const Cr={display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",lineHeight:0},lo={display:"block",height:"100%",width:"100%",objectFit:"cover",objectPosition:"top"},fo=w.forwardRef(function({options:t},n){const r=w.useRef(null),i=w.useRef(t);i.current={...i.current,onReady:t.onReady,onStatusChange:t.onStatusChange,onError:t.onError,onUserTranscript:t.onUserTranscript,onBotOutput:t.onBotOutput};const[s,o]=w.useState(!!t.showControls),[a,l]=w.useState(()=>Mr(t)),[f,u]=w.useState(!1),[c,d]=w.useState(!1),[p,T]=w.useState(!1),[m,P]=w.useState("idle"),[C,E]=w.useState(null),[g,I]=w.useState(!1),[N,A]=w.useState(!1),[ee,fe]=w.useState(""),[M,W]=w.useState(!1),[K,Q]=w.useState([]),[Y,de]=w.useState(t.personaId?.trim()||void 0),F=w.useCallback(S=>{i.current={...i.current,...S},S.showControls!==void 0&&o(!!S.showControls),S.personaId!==void 0&&de(S.personaId.trim()||void 0),l(O=>Mr({id:S.id??O.id,faceId:S.faceId??S.avatarId??O.faceId,authToken:S.authToken??O.authToken,apiBase:S.apiBase??O.apiBase,voiceId:S.voiceId??O.voiceId,speakingRate:S.speakingRate??O.speakingRate}))},[]);w.useImperativeHandle(n,()=>({getTwin:()=>r.current,applyOptions:F}),[F]),w.useEffect(()=>{F(t)},[F,t.id,t.faceId,t.avatarId,t.authToken,t.apiBase,t.voiceId,t.speakingRate,t.showControls,t.personaId]);const Z=w.useCallback(()=>{u(!0),E(null),i.current.onReady?.()},[]),k=w.useCallback(S=>{P(S),i.current.onStatusChange?.(S)},[]),q=w.useCallback(S=>{E(S),T(!1),i.current.onError?.(S)},[]),re=w.useCallback((S,O)=>{i.current.onUserTranscript?.(S,O)},[]),oe=w.useCallback(S=>{i.current.onBotOutput?.(S)},[]);w.useEffect(()=>{if(!s)return;const S=window.setInterval(()=>{d(!!r.current?.isConnected())},400);return()=>window.clearInterval(S)},[s,a]),w.useEffect(()=>{f&&r.current?.setMuted(g)},[f,g,a]),w.useEffect(()=>{Q([])},[a.id,a.faceId]);const ne=()=>{const S=r.current;if(!S?.isReady())return;if(E(null),A(!1),S.isConnected()){T(!1),S.disconnect().finally(()=>{d(!1)});return}T(!0);const O={authToken:a.authToken,voiceId:a.voiceId,speakingRate:a.speakingRate,apiBase:a.apiBase};S.connect(O).then(()=>{d(!!S.isConnected())}).catch(D=>{const V=D instanceof Error?D.message:"Failed to connect voice.";E(V),i.current.onError?.(V)}).finally(()=>{T(!1)})},te=()=>{A(S=>!S),E(null)},ie=()=>{const S=ee.trim(),O=r.current;!S||!O?.isReady()||M||(E(null),fe(""),W(!0),i.current.onUserTranscript?.(S,!0),(async()=>{try{const D=a.authToken?.trim()||await Pt(),V=Y||O.getPersonaId()?.trim()||void 0,_=await Pi({message:S,authToken:D,apiBase:a.apiBase||at,personaId:V,history:K});Q(v=>[...v,{role:"user",content:S},{role:"assistant",content:_.displayText}]),i.current.onBotOutput?.(_.displayText),await O.speakText(_.spokenText,{voiceId:a.voiceId,speakingRate:a.speakingRate})}catch(D){const V=D instanceof Error?D.message:"Failed to get reply.";E(V),i.current.onError?.(V)}finally{W(!1)}})())},we=()=>{const S=!g;I(S),r.current?.setMuted(S)},b=uo(a),$=!!(a.id||a.faceId);return z.jsxs("div",{className:"aitwin-widget__layout",children:[z.jsxs("div",{className:"aitwin-widget__stage",children:[$?z.jsx("div",{style:Cr,children:z.jsx(Ai,{ref:r,id:a.id,faceId:a.faceId,authToken:a.authToken,apiBase:a.apiBase,voiceId:a.voiceId,speakingRate:a.speakingRate,style:Cr,canvasStyle:lo,onReady:Z,onStatusChange:k,onError:q,onUserTranscript:re,onBotOutput:oe},b)}):z.jsx("p",{className:"aitwin-widget__hint",style:{padding:16},children:"Pass id or faceId to load a twin."}),s?z.jsx(ao,{muted:g,onToggle:we}):null,s&&p?z.jsx(oo,{}):null]}),s?z.jsx(co,{ready:f,connected:c,connecting:p,status:m,textMode:N,textDraft:ee,textSending:M,error:C,onTalk:ne,onTextMode:te,onTextDraftChange:fe,onSendText:ie}):null]})}),mo=".aitwin-widget{--aitwin-border: rgba(255, 255, 255, .12);--aitwin-text: #f4f4f5;--aitwin-muted: #a1a1aa;--aitwin-accent: #f97316;--aitwin-accent-hover: #fb923c;--aitwin-font: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;--aitwin-size: 1;--aitwin-stage-width: calc(200px * var(--aitwin-size));--aitwin-stage-height: calc(267px * var(--aitwin-size));--aitwin-action-height: calc(40px * var(--aitwin-size));--aitwin-action-font: calc(13px * var(--aitwin-size));--aitwin-action-radius: calc(10px * var(--aitwin-size));--aitwin-action-gap: calc(6px * var(--aitwin-size));--aitwin-mute-size: calc(28px * var(--aitwin-size));--aitwin-layout-gap: calc(8px * var(--aitwin-size));box-sizing:border-box;color:var(--aitwin-text);font-family:var(--aitwin-font);font-size:calc(12px * var(--aitwin-size));line-height:1.45;width:fit-content;max-width:100%}.aitwin-widget *,.aitwin-widget *:before,.aitwin-widget *:after{box-sizing:border-box}.aitwin-widget__layout{display:flex;flex-direction:column;gap:var(--aitwin-layout-gap);width:fit-content;max-width:100%}.aitwin-widget__stage{align-items:center;background:#0a0a0b;border:1px solid var(--aitwin-border);border-radius:calc(10px * var(--aitwin-size));display:flex;flex-shrink:0;height:var(--aitwin-stage-height);justify-content:center;line-height:0;overflow:hidden;position:relative;width:var(--aitwin-stage-width)}.aitwin-widget__stage .aitwin-root,.aitwin-widget__stage canvas{display:block;height:100%;object-fit:cover;object-position:top;width:100%}.aitwin-widget__hint{color:var(--aitwin-muted);font-size:calc(11px * var(--aitwin-size));margin:0}.aitwin-widget__mute{align-items:center;background:#28282cb8;border:none;border-radius:999px;color:#fff;cursor:pointer;display:inline-flex;height:var(--aitwin-mute-size);justify-content:center;padding:0;position:absolute;right:calc(8px * var(--aitwin-size));top:calc(8px * var(--aitwin-size));width:var(--aitwin-mute-size);z-index:2}.aitwin-widget__mute:hover{background:#37373cd9}.aitwin-widget__mute svg{height:calc(15px * var(--aitwin-size));width:calc(15px * var(--aitwin-size))}.aitwin-widget__controls{display:flex;flex-direction:column;gap:var(--aitwin-action-gap);width:var(--aitwin-stage-width)}.aitwin-widget__actions{display:grid;gap:var(--aitwin-action-gap);grid-template-columns:1fr 1fr;width:100%}.aitwin-widget__action{align-items:center;background:transparent;border:1.5px solid var(--aitwin-accent);border-radius:999px;color:var(--aitwin-accent);cursor:pointer;display:inline-flex;font-family:inherit;font-size:var(--aitwin-action-font);font-weight:600;gap:calc(6px * var(--aitwin-size));height:var(--aitwin-action-height);justify-content:center;padding:0 calc(10px * var(--aitwin-size))}.aitwin-widget__action svg{flex-shrink:0;height:calc(12px * var(--aitwin-size));width:calc(12px * var(--aitwin-size))}.aitwin-widget__action:hover:not(:disabled){background:#f973161a}.aitwin-widget__action:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__action--primary{background:var(--aitwin-accent);border-color:transparent;color:#fff}.aitwin-widget__action--primary:hover:not(:disabled){background:var(--aitwin-accent-hover)}.aitwin-widget__action--connecting:disabled{cursor:progress;opacity:1}.aitwin-widget__spinner{display:inline-flex;flex-shrink:0;height:calc(14px * var(--aitwin-size));width:calc(14px * var(--aitwin-size))}.aitwin-widget__spinner svg{animation:aitwin-widget-spin .8s linear infinite;display:block;height:100%;width:100%}.aitwin-widget__spinner--accent{color:var(--aitwin-accent);height:calc(16px * var(--aitwin-size));width:calc(16px * var(--aitwin-size))}.aitwin-widget__spinner--on-accent{color:#fff}@keyframes aitwin-widget-spin{to{transform:rotate(360deg)}}.aitwin-widget__connecting{align-items:center;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);background:#ffffffe0;border-radius:999px;bottom:calc(14px * var(--aitwin-size));box-shadow:0 4px 16px #0000001f;color:#3f3f46;display:inline-flex;font-size:calc(12px * var(--aitwin-size));font-weight:600;gap:calc(8px * var(--aitwin-size));left:50%;line-height:1;padding:calc(8px * var(--aitwin-size)) calc(14px * var(--aitwin-size));pointer-events:none;position:absolute;transform:translate(-50%);z-index:3}.aitwin-widget__composer{display:grid;gap:var(--aitwin-action-gap);grid-template-columns:1fr auto;width:100%}.aitwin-widget__composer-input{background:#ffffff0a;border:1px solid var(--aitwin-border);border-radius:var(--aitwin-action-radius);color:var(--aitwin-text);font-family:inherit;font-size:calc(12px * var(--aitwin-size));min-width:0;outline:none;padding:calc(8px * var(--aitwin-size)) calc(10px * var(--aitwin-size))}.aitwin-widget__composer-input:focus{border-color:#f973168c}.aitwin-widget__composer-send{background:var(--aitwin-accent);border:none;border-radius:var(--aitwin-action-radius);color:#fff;cursor:pointer;font-family:inherit;font-size:calc(12px * var(--aitwin-size));font-weight:600;padding:0 calc(12px * var(--aitwin-size))}.aitwin-widget__composer-send:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__controls-error{color:#fecaca;font-size:calc(11px * var(--aitwin-size));margin:0}.aitwin-widget--float{bottom:20px;filter:drop-shadow(0 12px 32px rgba(0,0,0,.45));height:fit-content;margin:0;max-width:calc(100vw - 40px);position:fixed;right:20px;width:fit-content;z-index:2147483000}",Rr="data-aitwin-widget-style";function ho(){if(typeof document>"u"||document.querySelector(`style[${Rr}]`))return;const e=document.createElement("style");e.setAttribute(Rr,"1"),e.textContent=mo,document.head.appendChild(e)}const po=w.forwardRef(function(t,n){const r=w.useRef(null);w.useEffect(()=>{ho()},[]),w.useImperativeHandle(n,()=>({speakText:async(s,o)=>{const a=r.current?.getTwin();if(!a)throw new Error("AiTwinWidget: twin is not mounted");return a.speakText(s,o)},connect:async s=>{const o=r.current?.getTwin();if(!o)throw new Error("AiTwinWidget: twin is not mounted");return o.connect(s)},disconnect:async()=>{const s=r.current?.getTwin();if(s)return s.disconnect()},stop:()=>{r.current?.getTwin()?.stop()},isReady:()=>!!r.current?.getTwin()?.isReady(),isConnected:()=>!!r.current?.getTwin()?.isConnected(),getTwin:()=>r.current?.getTwin()??null}),[]);const i=!!t.float;return z.jsx("div",{className:i?"aitwin-widget aitwin-widget--float":"aitwin-widget",children:z.jsx(fo,{ref:r,options:t})})}),Ci="thumbnail.webp";function wo(e,t=Dn){const n=e.trim();if(!n)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${n}/${Ci}`}const go=new Set([".png",".jpg",".jpeg",".webp"]);function Ri(e=".png"){const t=e.toLowerCase();return go.has(t)?`source${t}`:"source.png"}function yo(e,t=Dn,n=".png"){const r=e.trim();if(!r)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${r}/${Ri(n)}`}exports.AI_TWIN_THUMBNAIL_FILENAME=Ci;exports.AiTwin=Ai;exports.AiTwinNotFoundError=Yt;exports.AiTwinWidget=po;exports.CONSONANT_SKIP_GROUP=Yr;exports.DEFAULT_TTS_ENGINE_ID=it;exports.EMOTION_TO_EYEBROW=_i;exports.EXPRESSION_ATLAS_EMOTIONS=Qs;exports.MIC_SAMPLE_RATE=Hn;exports.OCULUS_VISEME_IDS=Kr;exports.PLAYBACK_SAMPLE_RATE=$n;exports.SPEAKING_RATE_MAX=un;exports.SPEAKING_RATE_MIN=cn;exports.TTS_ENGINE_CARTESIA=ot;exports.TTS_ENGINE_GOOGLE=Fn;exports.TTS_ENGINE_INWORLD=nn;exports.VISEME_IDS=Ns;exports.VISEME_SKIP_GAP_MS=En;exports.VISEME_TEST_CARTESIA_VOICE_ID=Wn;exports.VISEME_TEST_SPEAKING_RATE=Bt;exports.VISEME_TEST_VOICE_ID=Un;exports.VISEME_VTIME_GRID_MS=Ln;exports.VOWEL_SKIP_GROUP=Gr;exports.aiTwinSourceFilename=Ri;exports.buildPlaybackTransitions=ni;exports.buildPlaybackVisemeSeries=an;exports.buildRawVisemeTransitions=ti;exports.buildVoiceWebSocketUrl=li;exports.compactSkippableVisemes=Nn;exports.createAvatarTtsLipsyncController=In;exports.createRealtimeVoiceLipsyncController=fi;exports.emotionToEyebrow=st;exports.faceAssetUrls=xn;exports.fetchAiTwin=Or;exports.fetchAvatarReply=Pi;exports.fetchDevAuthToken=Pt;exports.getAiTwinSourceUrl=yo;exports.getAiTwinThumbnailUrl=wo;exports.listSkippedVisemeEntries=on;exports.listSkippedVisemes=ps;exports.normalizeOculusViseme=rn;exports.normalizeStreamEmotion=Ge;exports.resolveDirectFaceId=Nr;exports.resolveVisemeAtTime=Dt;exports.resolveVisemeFromPlaybackSeries=Jr;exports.resolveWordAtTime=ks;exports.setActiveTwinAssets=Vr;exports.snapVisemeQueueToGrid=On;exports.snapVisemeVtimeToGrid=Qr;
|
|
47
|
+
`;function xr(e=5){const t=new he.Filter({glProgram:he.GlProgram.from({vertex:Ua,fragment:Wa,name:"threshold-key-filter"}),resources:{thresholdUniforms:{uThreshold:{value:e/255,type:"f32"}}}});return t.setThreshold=n=>{t.resources.thresholdUniforms.uniforms.uThreshold=n/255},t.getThreshold=()=>Math.round(t.resources.thresholdUniforms.uniforms.uThreshold*255),t}function Ha(e,t,n){return e>n||t>n}function $a(e){return e?e.getParameter(e.MAX_TEXTURE_SIZE):4096}function za(e,t){return t!=null&&t>0?Math.floor(t):$a(e)}function Ka(e,t){const n=document.createElement("canvas");n.width=t.w,n.height=t.h;const r=n.getContext("2d");if(!r)throw new Error("Failed to acquire 2d context for atlas cell crop");return r.drawImage(e,t.x,t.y,t.w,t.h,0,0,t.w,t.h),n}function Ai(e){return fetch(e).then(t=>{if(!t.ok)throw new Error(`Failed to load image: ${e}`);return t.blob()}).then(t=>createImageBitmap(t))}async function Er(e,t,n,r,i){const s=n?await wi(e,i):await fetch(e).then(c=>{if(!c.ok)throw new Error(`Failed to load ${e}`);return c.json()}),o=s.sheets?.[0];if(!o?.path)throw new Error(`${e} has no sheets[0].path`);const a=new Map,l=async(c,d)=>{const p=_i(t,d,n),T=n?await Ds(await bt(p,i??"")):await Ai(p);if(Ha(T.width,T.height,r))return console.info(`[PixiVisemeCompositor] Sheet ${d} (${T.width}x${T.height}) exceeds MAX_TEXTURE_SIZE=${r}; using per-cell crops.`),{mode:"cells",bitmap:T};const m=he.Texture.from(T);return m.source.scaleMode="nearest",{mode:"full",texture:m}};a.set(o.index,await l(o.index,o.path));for(const c of s.sheets??[])c.index!==o.index&&c.path&&a.set(c.index,await l(c.index,c.path));const f=new Map;for(const c of s.cells??[])c.path&&f.set(c.path,c);const u=new Map;for(const c of s.sheets??[])u.set(c.index,c);return{atlasMeta:s,cellByPath:f,sheetByIndex:u,diffBase:t,sheets:a}}async function ja(e,t={}){const n=new he.Application;try{await n.init({canvas:e,width:842,height:1264,preference:"webgl",autoStart:!1,antialias:!1,resolution:1,autoDensity:!1,backgroundAlpha:1,backgroundColor:0,powerPreference:"high-performance"})}catch(_){throw n.destroy({removeView:!1}),_}if(n.renderer.type!==he.RendererType.WEBGL)throw n.destroy({removeView:!1}),new Error("Pixi did not initialize a WebGL renderer");const r=za(n.renderer.gl,t.maxTextureSize);let i=!1,s=!1,o=!1;const a=n.canvas,l=()=>{i=!0,!s&&!o&&(s=!0,t.onWebGlContextLost?.())};a.addEventListener("webglcontextlost",l);const f=new he.Sprite(he.Texture.EMPTY),u=new he.Sprite(he.Texture.EMPTY);u.visible=!1,u.alpha=0;const c=new he.Sprite(he.Texture.EMPTY),d=new he.Sprite(he.Texture.EMPTY),p=new he.Sprite(he.Texture.EMPTY);p.visible=!1;const T=xr(5),m=xr(5);c.filters=[T],d.filters=[m],n.stage.addChild(f),n.stage.addChild(u),n.stage.addChild(c),n.stage.addChild(d),n.stage.addChild(p);let A=null,C=null,x=null,g=null,E=null,N=null,I=null,te=842,de=1264,P=null,W=5;const K=new Map;let X=null,Y=null,pe=null;const j=Wr(()=>{K.clear(),N=null,I=null,A=null,P=null}),Z=(_,v)=>{te=_,de=v,n.renderer.resize(_,v),(e.width!==_||e.height!==v)&&(e.width=_,e.height=v)},M=()=>{c.visible=!1,d.visible=!1,c.texture=he.Texture.EMPTY,d.texture=he.Texture.EMPTY,X=null,Y=null},G=()=>{E=null,u.visible=!1,u.alpha=0},V=()=>{f.visible=!0,f.width=te,f.height=de,f.x=0,f.y=0},ue=()=>{u.width=te,u.height=de,u.x=0,u.y=0},ne=()=>{p.visible=!1,G(),A&&(f.texture=A,V())},ae=()=>{!E&&!u.visible||ne()},we=_=>{if(o||i||!A){ne();return}const v=Math.max(0,_);if(!C||v<=0){ne();return}M(),p.visible=!1,f.texture=C,V(),u.texture=A,ue(),u.alpha=0,u.visible=!0,E={startMs:performance.now(),durationMs:v},O()},oe=(_=performance.now())=>{if(!E)return!1;if(o||i)return ae(),!1;const v=(_-E.startMs)/Math.max(1,E.durationMs);if(v>=1)return ne(),O(),!1;const k=Math.min(1,Math.max(0,v)),H=k*k*(3-2*k);return u.alpha=H,u.visible=!0,O(),!0},S=()=>{if(x){try{x.resource=null}catch{}x.destroy(),x=null}C&&(C.destroy(!1),C=null),g=null},$=(_,v)=>{const k=_.cellByPath.get(v);if(!k||!pi(k))return null;const H=`${_.diffBase}::${v}`;let J=K.get(H);if(!J){const ie=k.sheet??0,xe=_.sheets.get(ie);if(!xe)return null;let be,Re=!1;if(xe.mode==="full")be=new he.Texture({source:xe.texture.source,frame:new he.Rectangle(k.x,k.y,k.w,k.h)});else{const De=Ka(xe.bitmap,k);be=he.Texture.from(De),be.source.scaleMode="nearest",Re=!0}J={texture:be,ownsSource:Re},K.set(H,J)}return{texture:J.texture,cell:k}},b=(_,v,k,H)=>{if(!H||!k)return _.visible=!1,_.texture=he.Texture.EMPTY,!1;const J=$(k,H);if(!J)return _.visible=!1,_.texture=he.Texture.EMPTY,!1;const ie=hi(k.atlasMeta,J.cell);return v.setThreshold(W),_.texture=J.texture,_.x=ie.x,_.y=ie.y,_.width=J.cell.w,_.height=J.cell.h,_.visible=!0,!0},L=_=>{if(!_||!N)return null;const v=P??new Set(N.cellByPath.keys());return $n(_,v)??(v.has(_)?_:null)},B=_=>{p.visible=!1,ne();const v=L(_.mouthPath),k=_.expressionPath&&I?Kn(_.expressionPath,H=>I.cellByPath.has(H)):null;v!==X?(b(c,T,N,v),X=v):v?c.visible=!0:c.visible=!1,k!==Y?(b(d,m,I,k),Y=k):k?d.visible=!0:d.visible=!1},O=()=>{if(!(o||i||document.hidden))try{n.render()}catch{}};return{async loadAssets(_){if(o)return{width:te,height:de,visemePaths:[]};const v=Dt();if(v&&!_)throw new Error("Encrypted assets enabled but no key provided");const k=v?await Fs(await bt(Qt(),_??"")):await Ai(Qt());A&&A.destroy(!0),A=he.Texture.from(k),A.source.scaleMode="linear";const H=Hr();N=await Er($r(),H,v,r,_);try{I=await Er(zr(),H,v,r,_)}catch(ie){console.warn("[PixiVisemeCompositor] expression atlas unavailable:",ie),I=null}const J=mi(N.atlasMeta,k.width,k.height);return Z(J.width,J.height),W=un(N.atlasMeta),T.setThreshold(W),m.setThreshold(W),P=new Set(N.cellByPath.keys()),K.clear(),ne(),M(),O(),{width:J.width,height:J.height,visemePaths:[...N.cellByPath.keys()]}},getVisemeAtlasPaths(){return P},drawLiveFrame(_){o||i||!A||(ae(),B(_),O())},drawIdleVideo(_,v){o||i||document.hidden||v&&!v()||_.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||(G(),M(),p.visible=!1,!C||g!==_?(S(),x=new he.VideoSource({resource:_,autoPlay:!1,updateFPS:0}),x.autoUpdate=!1,C=new he.Texture({source:x}),g=_):C.source.update(),f.texture=C,V(),O())},beginIdleToSilCrossfade:we,tickIdleToSilCrossfade:oe,finishIdleToSilCrossfade:ae,isIdleToSilCrossfading(){return E!=null},renderSilOnly(){o||i||!A||(M(),ne(),O())},blitBitmap(_){o||i||(ae(),M(),pe&&(pe.destroy(!0),pe=null),pe=he.Texture.from(_),p.texture=pe,p.visible=!0,p.x=0,p.y=0,p.width=te,p.height=de,f.visible=!1,O())},async compositePrefetchFrame(_){return null},renderFrame:O,isContextLost(){return i},dispose(){if(o)return;o=!0,a.removeEventListener("webglcontextlost",l),j(),S(),pe&&(pe.destroy(!0),pe=null);for(const{texture:v,ownsSource:k}of K.values())v.destroy(k);K.clear(),A&&(A.destroy(!0),A=null);const _=v=>{v.mode==="full"?v.texture.destroy(!0):v.bitmap.close()};if(N)for(const v of N.sheets.values())_(v);if(I)for(const v of I.sheets.values())_(v);T.destroy(!0),m.destroy(!0),n.destroy({removeView:!1},{children:!0,texture:!0})}}}const Ir=-1,qt=1e5,Ar=new Map;async function qa(e){let t=Ar.get(e);if(!t){const n=await fetch(e);if(!n.ok)throw new Error(`Failed to fetch worker script (${n.status}): ${e}`);const r=await n.blob();t=URL.createObjectURL(r),Ar.set(e,t)}return new Worker(t,{name:"visemeDiffPreview"})}function Ga(){return typeof Worker<"u"&&typeof OffscreenCanvas<"u"}function Mn(e,t){(e.width!==t.width||e.height!==t.height)&&(e.width=t.width,e.height=t.height);const n=e.getContext("2d");n&&n.drawImage(t,0,0)}function Pr(e,t){let n=0,r=null;const i=Xn(async(s,o)=>(await An(),await Pn(e,s),i.isLatestSeq(o)));return{usesWorker:!1,usesPixi:!1,async loadAssets(s){const o=await An(s);return r=o.visemePaths?new Set(o.visemePaths):null,o},getVisemeAtlasPaths(){return r},async renderSilOnly(){n+=1,i.reset(),await ya(e)},drawLiveFrame(s,o,a,l){i.enqueue(o,a,l)},async compositePrefetchFrame(s,o){try{return await ga(s)}catch{return null}},blitBitmap(s,o){Mn(s,o)},drawIdleVideo(){},beginIdleToSilCrossfade(){},tickIdleToSilCrossfade(){return!1},finishIdleToSilCrossfade(){},isIdleToSilCrossfading(){return!1},supportsBufferedPlayback:!0,async renderViseme(s,o){n+=1;const a=n;t.onStatus?.(o),await Pn(s,{mouthPath:_t(o),expressionPath:null})},dispose(){n+=1,i.reset()}}}function Ya(e,t,n){let r=null,i=1,s=0,o=!1,a=!1,l=null;const f=new Map,u=new Map;let c=qt;const d=Xn(async(x,g,E)=>(f.set(g,{drawKey:E.drawKey,onDisplayed:E.onDisplayed}),await A({type:"drawFrame",diffPath:x.mouthPath,expressionDiffPath:x.expressionPath,liveSeq:g},void 0,!0),!1)),p=x=>{if(x===Ir){let N=-1,I;for(const[te,de]of f)te>=N&&(N=te,I=de);N>=0&&f.delete(N),I?.onDisplayed?.(I.drawKey);return}const g=-x,E=f.get(g);f.delete(g),E?.onDisplayed?.(E.drawKey)},T=new Map,m=(x,g)=>{a||!r||r.postMessage(x,[])},A=(x,g,E=!1)=>{if(a)return Promise.resolve();const N=i++;return new Promise((I,te)=>{T.set(N,{resolve:de=>I(de),reject:te,generation:typeof x.generation=="number"?x.generation:void 0,expectRenderDone:E}),m({...x,requestId:N})})},C=(async()=>{r=await qa(n),r.onmessage=x=>{if(a)return;const g=x.data;if(g.type==="status"){t.onStatus?.(g.label);return}if(g.type==="frame"){if(g.generation<=-qt){const I=-g.generation,te=u.get(I);u.delete(I),te?.resolve(g.bitmap);return}const N=g.generation<0;if(!N&&g.generation!==s){g.bitmap.close();return}if(N&&!(g.generation===Ir)){const te=-g.generation;if(!d.isLatestSeq(te)){Qe()?.onWorkerStale(),g.bitmap.close();return}}if(N&&t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()){Qe()?.onWorkerStale(),g.bitmap.close();return}Mn(e,g.bitmap),g.bitmap.close(),N&&p(g.generation);return}const E=T.get(g.requestId);if(E)switch(g.type){case"ready":T.delete(g.requestId),E.resolve();break;case"loadAssetsDone":T.delete(g.requestId),l=g.visemePaths?.length?new Set(g.visemePaths):null,E.resolve({width:g.width,height:g.height,visemePaths:g.visemePaths});break;case"renderDone":if(E.expectRenderDone&&E.generation!=null&&g.generation!==E.generation)return;T.delete(g.requestId),E.resolve();break;case"renderAborted":T.delete(g.requestId),E.resolve();break;case"error":T.delete(g.requestId),t.onError?.(g.message),E.reject(new Error(g.message));break}},r.onerror=x=>{if(a)return;const g=x.message||"Worker error";t.onError?.(g);for(const[,E]of T)E.reject(new Error(g));T.clear()},await A({type:"init"}),o=!0})();return{usesWorker:!0,usesPixi:!1,async loadAssets(x){if(a)return{width:842,height:1264};if(await C,a)return{width:842,height:1264};if(!o)throw new Error("Worker init failed");return await A({type:"loadAssets",keyHex:x,urls:is(lt())})??{width:842,height:1264}},getVisemeAtlasPaths(){return l},async renderSilOnly(){if(a||(await C,a))return;s+=1,d.reset(),f.clear(),u.forEach(({resolve:g})=>g(null)),u.clear(),c=qt;const x=s;await A({type:"cancelLiveDraws"}),await A({type:"renderSil",generation:x},void 0,!0)},drawLiveFrame(x,g,E,N){a||C.then(()=>{a||d.enqueue(g,E,N)})},compositePrefetchFrame(x,g){return a?Promise.resolve(null):C.then(()=>{if(a)return null;const E=++c;return new Promise(N=>{u.set(E,{resolve:N}),A({type:"drawFrame",diffPath:x.mouthPath,expressionDiffPath:x.expressionPath,liveSeq:E},void 0,!0).catch(()=>{u.delete(E),N(null)})})})},blitBitmap(x,g){Mn(x,g)},drawIdleVideo(){},beginIdleToSilCrossfade(){},tickIdleToSilCrossfade(){return!1},finishIdleToSilCrossfade(){},isIdleToSilCrossfading(){return!1},supportsBufferedPlayback:!0,async renderViseme(x,g,E={}){if(a||(await C,a))return;s+=1,d.reset(),f.clear();const N=s;try{await A({type:"cancelLiveDraws"}),await A({type:"renderViseme",generation:N,to:g,from:E.from,transitionDurationMs:E.transitionDurationMs,gapMs:E.gapMs,threshold:E.threshold},void 0,!0)}catch(I){if(I?.name==="AbortError")return;throw I}},dispose(){if(!a){a=!0,s+=1,d.reset(),f.clear(),u.forEach(({resolve:x})=>x(null)),u.clear(),c=qt;for(const[,x]of T)x.resolve();T.clear(),r?.terminate(),r=null}}}}async function Qa(e,t){const n=await ja(e,{onWebGlContextLost:t.onWebGlContextLost,maxTextureSize:t.pixiMaxTextureSize});let r=0,i=null,s=!1;const o=Xn(async(a,l)=>s?!1:t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()?(Qe()?.onWorkerStale(),!1):(n.drawLiveFrame(a),o.isLatestSeq(l)));return{usesWorker:!1,usesPixi:!0,async loadAssets(a){if(s)return{width:842,height:1264};const l=await n.loadAssets(a);return i=l.visemePaths?.length?new Set(l.visemePaths):null,l},getVisemeAtlasPaths(){return i},async renderSilOnly(){s||(r+=1,o.reset(),n.renderSilOnly())},drawLiveFrame(a,l,f,u){s||o.enqueue(l,f,u)},async compositePrefetchFrame(a,l){if(s)return null;try{return await n.compositePrefetchFrame(a)}catch{return null}},blitBitmap(a,l){s||t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()||n.blitBitmap(l)},drawIdleVideo(a,l){s||n.drawIdleVideo(a,l)},beginIdleToSilCrossfade(a){s||n.beginIdleToSilCrossfade(a)},tickIdleToSilCrossfade(a){return s?!1:n.tickIdleToSilCrossfade(a)},finishIdleToSilCrossfade(){s||n.finishIdleToSilCrossfade()},isIdleToSilCrossfading(){return s?!1:n.isIdleToSilCrossfading()},supportsBufferedPlayback:!1,async renderViseme(a,l){if(s)return;r+=1;const f=r;o.reset(),t.onStatus?.(l),n.drawLiveFrame({mouthPath:_t(l),expressionPath:null})},dispose(){s||(s=!0,r+=1,o.reset(),n.dispose())}}}function Mr(e,t){if(!Ga())return Pr(e,t);const n=Hi(t.workerScriptUrl);try{return Ya(e,t,n)}catch{return Pr(e,t)}}function Xa(e,t={}){if(t.preferLegacyRenderer)return Mr(e,t);let n=null,r=!1,i=null,s=!1;const o=()=>n?Promise.resolve(n):(i||(i=(async()=>{try{const a=await Qa(e,t);if(s)throw a.dispose(),new Error("Renderer disposed during Pixi init");return r=!0,n=a,a}catch(a){if(s)throw a instanceof Error?a:new Error(String(a));return console.warn("[AiTwin] Pixi WebGL renderer unavailable, using Canvas2D fallback:",a),n=Mr(e,t),r=!1,n}})()),i);return{get usesWorker(){return n?.usesWorker??!1},get usesPixi(){return r},async loadAssets(a){return(await o()).loadAssets(a)},getVisemeAtlasPaths(){return n?.getVisemeAtlasPaths()??null},async renderSilOnly(){return(await o()).renderSilOnly()},drawLiveFrame(a,l,f,u){o().then(c=>{s||c.drawLiveFrame(a,l,f,u)})},async compositePrefetchFrame(a,l){return(await o()).compositePrefetchFrame(a,l)},blitBitmap(a,l){n&&n.blitBitmap(a,l)},drawIdleVideo(a,l){n?.usesPixi&&n.drawIdleVideo(a,l)},beginIdleToSilCrossfade(a){n?.beginIdleToSilCrossfade(a)},tickIdleToSilCrossfade(a){return n?.tickIdleToSilCrossfade(a)??!1},finishIdleToSilCrossfade(){n?.finishIdleToSilCrossfade()},isIdleToSilCrossfading(){return n?.isIdleToSilCrossfading()??!1},get supportsBufferedPlayback(){return n?.supportsBufferedPlayback??!1},async renderViseme(a,l,f){return(await o()).renderViseme(a,l,f)},dispose(){s=!0,i=null,n?.dispose(),n=null}}}class Ja extends Error{constructor(t,n){super(`${t} timed out after ${Math.round(n/1e3)}s`),this.name="LoadTimeoutError"}}function Sn(e,t,n){return new Promise((r,i)=>{const s=globalThis.setTimeout(()=>{i(new Ja(n,t))},t);e.then(o=>{globalThis.clearTimeout(s),r(o)},o=>{globalThis.clearTimeout(s),i(o)})})}const Za={position:"relative",display:"inline-block",lineHeight:0},eo={display:"block",maxWidth:"100%",height:"auto"},to={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",padding:"1rem",background:"rgba(0,0,0,0.55)",color:"#fff",fontSize:"0.875rem",textAlign:"center"};function At(e){return qi(e)?Un:Vn}function Ke(e,t){return t?.isSpeaking()||t?.isWarmingUp()?t:e.isSpeaking()||e.isWarmingUp()?e:t?.isConnected()?t:e}const Pi=w.forwardRef(function({id:t,avatarId:n,faceId:r,assets:i,authToken:s,apiBase:o,ttsEngineId:a=st,voiceId:l,speakingRate:f=Ft,className:u,style:c,canvasStyle:d,onStatusChange:p,onDisplayStatus:T,onError:m,onReady:A,showErrorOverlay:C=!0,onUserTranscript:x,onBotOutput:g,onRealtimeLipsyncDebug:E,onFrameRenderStats:N,lipsyncBufferedPlayback:I=!0,lipsyncPlaybackWarmupMs:te=1500,pixiMaxTextureSize:de,captions:P},W){const K=w.useRef(null),X=w.useRef(null),Y=w.useRef(null),pe=w.useRef(I);pe.current=I;const j=w.useRef(te);j.current=te;const Z=w.useRef(0),M=w.useRef(Yn()),G=w.useRef(oa()),V=w.useRef(!1),ue=w.useRef(null),ne=w.useRef(null),ae=w.useRef(0),we=w.useRef(0),oe=w.useRef(0),S=w.useRef(null),$=w.useRef(null),b=w.useRef(!1),L=w.useRef(!1),B=w.useRef(!1),O=w.useRef(!1),_=w.useRef("sil"),v=w.useRef(0),k=w.useRef(!1),H=w.useRef(null),J=w.useRef(!1),[ie,xe]=w.useState("idle"),[be,Re]=w.useState(null),[De,ln]=w.useState(!1),[Jn,Lt]=w.useState(!1),[fn,Zn]=w.useState({width:842,height:1264}),[h,R]=w.useState(null),[ee,le]=w.useState(0),ve=w.useRef(!1),ge=w.useRef(s??null),ye=o?.trim()||ot,Be=w.useRef(null),_e=w.useRef(null),ze=w.useRef(!1),Xe=w.useRef({width:842,height:1264}),Fe=w.useRef(null),Tt=w.useRef("sil"),Je=w.useRef(""),Ue=w.useMemo(()=>va(P),[P]),Ee=w.useCallback(()=>{Je.current="",R(null)},[]);w.useEffect(()=>{Ue.enabled||Ee()},[Ue.enabled,Ee]);const Ze=w.useCallback(y=>{if(!Ue.enabled)return;const D=y.isSpeaking(),U=y.isWarmingUp();if(!D||U){Je.current&&Ee();return}const F=_a(y.getWordQueue());if(!F){Je.current&&Ee();return}F!==Je.current&&(Je.current=F,R(F))},[Ue.enabled,Ee]),et=w.useRef(void 0),tt=w.useRef(new Map),Se=w.useRef(A),re=w.useRef(T),Ne=w.useRef(m),ft=w.useRef(x),kt=w.useRef(g),dt=w.useRef(E),xt=w.useRef(N),qe=w.useRef(Ea());Se.current=A,re.current=T,Ne.current=m,ft.current=x,kt.current=g,dt.current=E,xt.current=N,w.useEffect(()=>{const y=qe.current;return vr(y),()=>vr(null)},[]);const er=w.useCallback(y=>{const D=y?.ttsEngineId??a??_e.current?.ttsEngineId??st,U=y?.voiceId??l??_e.current?.voiceId??At(D);return{ttsEngineId:D,voiceId:U}},[a,l]),Ge=w.useCallback(y=>{Re(y),Ne.current?.(y)},[]),Et=w.useCallback(y=>{xe(y),p?.(y)},[p]),ce=w.useRef(En(Et,ye,{onLipsyncDebug:y=>dt.current?.(y)})),fe=w.useRef(null),tr=w.useRef(()=>{});w.useEffect(()=>(ce.current=En(Et,ye,{onLipsyncDebug:y=>dt.current?.(y)}),s&&ce.current.setDeveloperToken(s),ce.current.setTtsEngineId(a),()=>{ce.current.stop();const y=fe.current;y&&(y.disconnect(),fe.current=null)}),[Et,s,a,ye]);const nr=w.useCallback(()=>(fe.current||(fe.current=di(Et,{speakingRate:f,onUserTranscript:(y,D)=>ft.current?.(y,D),onBotOutput:y=>kt.current?.(y),onLipsyncDebug:y=>dt.current?.(y)}),fe.current.setTtsEngineId(a),tr.current(!0)),fe.current),[Et,f,a]),Pe=w.useCallback(()=>{S.current!=null&&(clearTimeout(S.current),S.current=null)},[]),Me=w.useCallback(()=>{$.current!=null&&(clearTimeout($.current),$.current=null),B.current=!1},[]),Ot=w.useCallback(()=>{if(O.current)return;const y=X.current;if(O.current=!0,Me(),b.current=!1,L.current=!1,!J.current||!H.current){y?.renderSilOnly();return}H.current.setActive(!1);const D=H.current.getVideo();if(y?.usesPixi){y.drawIdleVideo(D),y.beginIdleToSilCrossfade(br);return}(async()=>{const U=K.current;U&&await _n(U,D,null,void 0,Xe.current).catch(()=>{}),await new Promise(F=>setTimeout(F,br)),O.current&&await y?.renderSilOnly()})()},[Me]),rr=w.useCallback(()=>{!J.current||!H.current||(O.current=!1,X.current?.finishIdleToSilCrossfade(),Me(),B.current=!0,$.current=setTimeout(()=>{if($.current=null,Ke(ce.current,fe.current).isSpeaking()){B.current=!1;return}if(b.current){B.current=!1;return}const y=H.current;if(!y){B.current=!1;return}y.restart(),y.setActive(!0);const D=y.getVideo();let U=!1;const F=()=>{U||(U=!0,D.removeEventListener("playing",q),B.current=!1)},q=()=>{F()};if(D.addEventListener("playing",q,{once:!0}),D.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&!D.paused){F();return}setTimeout(F,300)},Ia))},[Me]),mt=w.useCallback(()=>{if(Pe(),re.current?.("sil"),b.current=!1,O.current=!1,!J.current||!H.current){B.current=!1;return}rr()},[Pe,rr]),dn=w.useCallback(async y=>{const D=we.current,U=X.current,F=K.current,q=()=>{y?.fallbackOnly||(b.current=!1)};if(!U||!F||!De){q();return}if(Ke(ce.current,fe.current).isSpeaking()){q();return}if(y?.fallbackOnly){if(!b.current||(Ce(M.current),await U.renderSilOnly(),D!==we.current)||Ke(ce.current,fe.current).isSpeaking())return;mt();return}if(Tr(M.current)){Ce(M.current),mt();return}if(pe.current&&U.supportsBufferedPlayback&&!y?.fallbackOnly){if(Ce(M.current),Y.current?.reset(),await U.renderSilOnly(),D!==we.current||Ke(ce.current,fe.current).isSpeaking())return;mt();return}const Ie=Ra(Ke(ce.current,fe.current).getVisemeQueue(),v.current,_.current),Le=Da(Ie,Fe.current);if(Ce(M.current),!Le){if(await U.renderSilOnly(),D!==we.current||Ke(ce.current,fe.current).isSpeaking())return;mt();return}try{await U.renderViseme(F,"sil",{from:Ie,transitionDurationMs:xi})}catch(Ae){if(Ae?.name!=="AbortError")throw Ae}if(D!==we.current){q();return}if(Ke(ce.current,fe.current).isSpeaking()){q();return}mt()},[De,mt]),ht=w.useCallback(()=>{if(L.current||b.current)return;L.current=!0,b.current=!0,Pe();const y=we.current;dn().finally(()=>{L.current=!1}),S.current=setTimeout(()=>{S.current=null,y===we.current&&dn({fallbackOnly:!0})},Ba())},[Pe,dn]),ir=w.useCallback(async()=>{const y=Math.floor(Date.now()/1e3);if(Be.current&&y<Be.current.expiresAt-60)return Be.current.key;const D=ge.current??await Mt();ge.current=D,ce.current.setDeveloperToken(D);const U=await es(D,ye);return Be.current={key:U.value,expiresAt:U.expiresAt},U.value},[ye]);w.useEffect(()=>{s&&(ge.current=s,ce.current.setDeveloperToken(s))},[s]),w.useEffect(()=>{ce.current.setTtsEngineId(a),fe.current?.setTtsEngineId(a),_e.current&&(_e.current.ttsEngineId=a)},[a]),w.useEffect(()=>{const y=l??At(a);_e.current&&(_e.current.voiceId=y)},[l,a]);const nt=w.useMemo(()=>Vr(n,r),[n,r]),Bi=w.useMemo(()=>i?JSON.stringify(i):nt?`face:${nt}`:`id:${t??""}`,[i,nt,t]);return w.useEffect(()=>{if(!t&&!i&&!nt){Ge("AiTwin requires `assets`, `avatarId`/`faceId`, or `id`");return}let y=!1;ze.current=!1,ln(!1),Lt(!1),Re(null),_e.current=null,H.current=null,J.current=!1;const D=K.current;if(!D)return;let U=null;return(async()=>{try{let F,q,ke,Ie;if(i)F=i,q=a,ke=l??At(q);else if(nt)re.current?.("loadFace"),F=kn(nt),q=a,ke=l??At(q);else{re.current?.("getAiTwin");const Q=await Sn(Nr(t),3e4,"getAiTwin");if(y)return;if(!Q.faceId?.trim())throw new Error("getAiTwin returned no faceId");q=Q.ttsEngineId,ke=l??Q.voiceId??At(q),Ie=Q.knowledgeContextId?.trim()||void 0,F=kn(Q.faceId)}_e.current={ttsEngineId:q,voiceId:ke,personaId:Ie},Ur(F),H.current=ca();const Le=!!(i&&!ut(i));U=Xa(D,{preferLegacyRenderer:Le,pixiMaxTextureSize:de,onStatus:Q=>{y||re.current?.(Q)},onError:Q=>{y||Ge(Q)},shouldAcceptLiveFrame:()=>{if(V.current)return!0;if(b.current)return!1;const Q=Ke(ce.current,fe.current);return Q.isSpeaking()||Q.isWarmingUp()},onWebGlContextLost:()=>{y||ve.current||(ve.current=!0,queueMicrotask(()=>{y||le(Q=>Q+1)}))}}),X.current=U,Y.current=Va(U),ve.current=!1;const Ae=Q=>{const se=()=>{if(!Q||j.current<=0)return!1;const Te=X.current;return Te?pe.current&&Te.supportsBufferedPlayback?!0:Te.usesPixi:!1};ce.current.setLipsyncWarmupHold(Q,se),fe.current?.setLipsyncWarmupHold(Q,se)};tr.current=Ae,Ae(!0),re.current?.("auth");const We=ge.current??s??await Sn(Mt(),3e4,"getAuthToken");if(y)return;ge.current=We,ce.current.setDeveloperToken(We),ce.current.setTtsEngineId(q);const Nt=Dt()?await ir():void 0;if(y)return;re.current?.("loadAssets");const me=await Sn(U.loadAssets(Nt),18e4,"load face assets");if(!y&&me.width>0&&me.height>0&&(Xe.current=me,Zn(me)),y)return;Fe.current=U.getVisemeAtlasPaths(),ze.current=!0,ln(!0),Se.current?.(),U.renderSilOnly().then(()=>{y||re.current?.("sil")}),(async()=>{try{const Q=await Ns(Nt);if(await H.current.load(Q),y)return;J.current=!0,Lt(!0),Ce(M.current),H.current.setActive(!0);const se=H.current.getVideo();U.usesPixi?U.drawIdleVideo(se):await _n(D,se,null,void 0,Xe.current),y||re.current?.("idle")}catch(Q){if(y)return;J.current=!1,Lt(!1),console.warn("[AiTwin] Idle video unavailable:",Q)}})()}catch(F){if(y)return;if(F instanceof Gt){Ge(F.message);return}Ge(F instanceof Error?F.message:"Failed to load AI twin")}})(),()=>{y=!0,H.current?.dispose(),U?.dispose(),X.current=null}},[Bi,i,nt,t,a,l,s,de,ir,Ge,ee]),w.useEffect(()=>{const y={current:!1},D=()=>{const U=K.current,F=X.current,q=Ke(ce.current,fe.current);if(!U||!F||!De){ae.current=requestAnimationFrame(D);return}if(document.hidden){H.current?.setActive(!1),ae.current=requestAnimationFrame(D);return}const ke=q.isSpeaking(),Ie=q.isWarmingUp(),Le=ke&&!k.current,Ae=k.current&&!ke;Le&&(Pe(),Me(),b.current=!1,L.current=!1,Ce(M.current),Y.current?.reset(),qe.current.reset(),et.current=void 0,oe.current=0,_.current="sil",v.current=0,Ot()),Ae&&(G.current.reset(),H.current?.setActive(!1),Y.current?.reset(),F.finishIdleToSilCrossfade(),Ee(),ht());const We=Ae||b.current||B.current||O.current,Nt=I&&F.supportsBufferedPlayback;if(Ie){if(Ot(),J.current&&H.current?.setActive(!1),F.usesPixi&&F.isIdleToSilCrossfading()){F.tickIdleToSilCrossfade(performance.now()),q.getVisemeQueue().length>0&&Z.current===0&&(Z.current=performance.now()),k.current=q.isSpeaking(),ae.current=requestAnimationFrame(D);return}const me=q.getVisemeQueue();me.length>0&&Z.current===0&&(Z.current=performance.now()),G.current.advance(performance.now());const Q=G.current.getExpressionPath(),se=G.current.getDrawKey(),Te={queue:me,elapsedMs:0,expressionPath:Q,expressionDrawKey:se,availablePaths:Fe.current};let Oe=!1;Nt&&Y.current?(Y.current.warmupTick(Te),Oe=Y.current.isWarmupReady(Te,j.current)):F.usesPixi&&kr(U,me,0,Q,se,M.current,(pt,Vt,mn,Ut)=>{F.drawLiveFrame(pt,Vt,mn,He=>{Ut?.(He),q.isWarmingUp()&&He!==""&&!Tr({lastDrawnKey:He})&&(Z.current=0,q.releaseWarmupHold())})},pt=>{re.current?.(pt.label)},Fe.current);const Ye=Z.current>0&&performance.now()-Z.current>zi;re.current?.(Oe?"buffer ready":"buffering lipsync…"),(Oe||Ye)&&(Z.current=0,q.releaseWarmupHold()),Ze(q),k.current=q.isSpeaking(),ae.current=requestAnimationFrame(D);return}if(ke){Ot(),J.current&&H.current?.setActive(!1),F.usesPixi&&F.isIdleToSilCrossfading()&&F.finishIdleToSilCrossfade();const me=q.getVisemeQueue(),Q=q.getPlaybackElapsedMs();ks(me,Q),v.current=Q;const se=me.length>0?Bt(me,Q):"sil";se!=="sil"&&(_.current=se);const Te=da(Q,q.getSentenceEmotions(),q.getWordQueue(),q.getStreamMood());G.current.setTargetEmotion(Te),G.current.setTargetEyebrow(aa(Q,q.getWordQueue(),at(Te))),G.current.advance(performance.now());const Oe=G.current.getExpressionPath(),Ye=G.current.getDrawKey(),pt=(He,hn,It,pn)=>{const sr={label:Tt.current,elapsedMs:Q,mouthPath:hn.mouthPath,transitionMeta:et.current};tt.current.set(It,sr),Y.current?.markExternallyDisplayed(It,Oe),F.drawLiveFrame(He,hn,It,Wt=>{const Fi=tt.current.get(Wt)??sr;tt.current.delete(Wt),qe.current.onDrawDisplayed(Fi,me),Y.current?.markExternallyDisplayed(Wt,Oe),pn?.(Wt)})},Vt=He=>{Tt.current=He.label,et.current=He.transitionMeta,re.current?.(He.label)},mn=I&&F.supportsBufferedPlayback;let Ut=!1;mn&&Y.current&&(Ut=Y.current.tick({canvas:U,queue:me,elapsedMs:Q,expressionPath:Oe,expressionDrawKey:Ye,playbackState:M.current,availablePaths:Fe.current,onStatus:Vt,onDisplayed:(hn,It,pn)=>{qe.current.onDrawDisplayed({label:pn,elapsedMs:Q,mouthPath:It,transitionMeta:et.current},me)}}).usedBuffer),Ut||kr(U,me,Q,Oe,Ye,M.current,pt,Vt,Fe.current),qe.current.onRafTickSpeaking(),xt.current?.(qe.current.snapshot(me,Q))}else if(!We&&V.current){H.current?.setActive(!1),G.current.advance(performance.now());const me=G.current.getExpressionPath(),Q=G.current.getDrawKey();vn(U,me,Q,M.current,(se,Te,Oe,Ye)=>F.drawLiveFrame(se,Te,Oe,Ye),se=>{if(ne.current){re.current?.(ne.current);return}const Te=G.current.getTargetEmotion();re.current?.(se==="sil"||se==="blink"?`${Te}${se==="blink"?" · blink":""}`:se)},null,ue.current)}else if(!We&&J.current&&H.current){const me=H.current,Q=me.getVideo();if(Q.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){me.setActive(!0);const se=()=>!q.isSpeaking()&&!b.current&&!B.current&&!V.current;F.usesPixi?(F.drawIdleVideo(Q,se),se()&&re.current?.("idle")):y.current||(y.current=!0,_n(U,Q,null,void 0,Xe.current,se).then(()=>re.current?.("idle")).finally(()=>{y.current=!1}))}else vn(U,null,"__sil__",M.current,(se,Te,Oe,Ye)=>F.drawLiveFrame(se,Te,Oe,Ye),se=>re.current?.(se))}else We||vn(U,null,"__sil__",M.current,(me,Q,se,Te)=>F.drawLiveFrame(me,Q,se,Te),me=>re.current?.(me));Ue.enabled&&Ze(q),k.current=ke,ae.current=requestAnimationFrame(D)};return ae.current=requestAnimationFrame(D),()=>{cancelAnimationFrame(ae.current),Pe(),Me(),ce.current.stop(),fe.current?.stop()}},[De,Jn,ht,Pe,Me,Ot,Ze,Ee,Ue.enabled]),w.useImperativeHandle(W,()=>({speakText:async(y,D)=>{const U=y.trim();if(!U)return;const F=X.current;if(!F||!ze.current&&!De)throw new Error("AI twin is not ready");const{ttsEngineId:q,voiceId:ke}=er(D);Re(null),Ee(),we.current+=1,Pe(),Me(),b.current=!1,L.current=!1,_.current="sil",v.current=0,Ce(M.current),V.current=!1,ue.current=null,ne.current=null,G.current.reset(),k.current=!1,O.current=!1,F.finishIdleToSilCrossfade();try{await ce.current.speak(U,{voiceId:ke,speakingRate:D?.speakingRate??f,ttsEngineId:q})}catch(Ie){throw O.current=!1,F.finishIdleToSilCrossfade(),ht(),Ge(Ie instanceof Error?Ie.message:"TTS failed"),Ie}},stop:()=>{we.current+=1,Pe(),Me(),b.current=!1,L.current=!1,O.current=!1,X.current?.finishIdleToSilCrossfade(),ce.current.stop(),fe.current?.stop(),Ce(M.current),Y.current?.reset(),Z.current=0,k.current=!1,Ee(),ht()},setTtsEngineId:y=>{ce.current.setTtsEngineId(y),fe.current?.setTtsEngineId(y),_e.current&&(_e.current.ttsEngineId=y)},renderViseme:async(y,D)=>{const U=X.current,F=K.current;if(!U||!F||!ze.current)throw new Error("AI twin is not ready");await U.renderViseme(F,y,{from:D?.from,transitionDurationMs:D?.transitionDurationMs,gapMs:D?.gapMs,onStatus:q=>re.current?.(q)})},setEmotion:y=>{if(!ze.current)throw new Error("AI twin is not ready");const D=X.current,U=K.current;if(!D||!U)throw new Error("AI twin is not ready");we.current+=1,Pe(),Me(),b.current=!1,L.current=!1,B.current=!1,O.current=!1,ce.current.stop(),fe.current?.stop(),Ce(M.current),Y.current?.reset(),Z.current=0,k.current=!1,D.finishIdleToSilCrossfade(),H.current?.setActive(!1);const F=je(y);V.current=!0,ue.current=null,ne.current=null,G.current.snapToEmotion(F);const q=G.current.getExpressionPath(),ke=G.current.getDrawKey(),Ie={mouthPath:null,expressionPath:q},Le=Rt(Ie,ke);M.current.lastDrawnKey="",D.drawLiveFrame(U,Ie,Le,We=>{We===Le&&(M.current.lastDrawnKey=Le)});const Ae=at(F);re.current?.(q?`${F} · brow ${Ae>0?"+":""}${Ae}`:`${F} · brow 0 (sil base)`)},getEmotion:()=>V.current?G.current.getTargetEmotion():null,clearEmotionPreview:()=>{V.current=!1,ue.current=null,ne.current=null,G.current.reset(),Ce(M.current),re.current?.("idle")},setViseme:y=>{if(!ze.current)throw new Error("AI twin is not ready");const D=X.current,U=K.current;if(!D||!U)throw new Error("AI twin is not ready");we.current+=1,Pe(),Me(),b.current=!1,L.current=!1,B.current=!1,O.current=!1,ce.current.stop(),fe.current?.stop(),Ce(M.current),Y.current?.reset(),Z.current=0,k.current=!1,D.finishIdleToSilCrossfade(),H.current?.setActive(!1);const F=nn(y);V.current=!0,ne.current=F,ue.current=F==="sil"?null:_t(F),G.current.snapToEmotion("neutral");const q=G.current.getExpressionPath(),ke=G.current.getDrawKey(),Le={mouthPath:ue.current,expressionPath:q},Ae=Rt(Le,ke);M.current.lastDrawnKey="",D.drawLiveFrame(U,Le,Ae,We=>{We===Ae&&(M.current.lastDrawnKey=Ae)}),re.current?.(F)},getViseme:()=>V.current?ne.current:null,isReady:()=>ze.current,getStatus:()=>ie,connect:async(y={})=>{Re(null);try{let D=y.authToken?.trim();D||(D=ge.current??s??await Mt(),ge.current=D);const U=y.voiceId?.trim()??l??_e.current?.voiceId,F=y.personaId?.trim()??_e.current?.personaId,q=nr();await q.unlockAudio(),await q.connect({...y,apiBase:y.apiBase?.trim()||ye,authToken:D,voiceId:U,personaId:F,speakingRate:y.speakingRate??f})}catch(D){throw Ge(D instanceof Error?D.message:"Voice connect failed"),D}},disconnect:async()=>{const y=fe.current;y&&(we.current+=1,Pe(),Me(),b.current=!1,L.current=!1,O.current=!1,X.current?.finishIdleToSilCrossfade(),Ce(M.current),Y.current?.reset(),Z.current=0,k.current=!1,await y.disconnect(),ht())},isConnected:()=>fe.current?.isConnected()??!1,getVoiceStream:()=>fe.current?.getVoiceStream()??ce.current?.getVoiceStream()??null,setMuted:y=>{const D=ce.current,U=fe.current;D?.setMuted?.(y),U?.setMuted?.(y)},isMuted:()=>{const y=fe.current,D=ce.current;return y?.isMuted?.()??D?.isMuted?.()??!1},getPersonaId:()=>_e.current?.personaId?.trim()||null}),[De,f,s,l,Pe,Me,ht,Ge,er,nr,ie,ye]),z.jsxs("div",{className:u,style:{...Za,...c},children:[z.jsx("canvas",{ref:K,width:fn.width,height:fn.height,style:{...eo,...d},"aria-label":t?`AI twin ${t}`:"AI twin face"}),C&&be?z.jsx("div",{style:to,children:be}):null,Ue.enabled&&h?z.jsx(ka,{text:h,style:Ue.style},h):null]})});async function no(e){try{const t=await e.json();if(typeof t.detail=="string"&&t.detail.trim())return t.detail;if(typeof t.error=="string"&&t.error.trim())return t.error}catch{}return`avatarReply failed (${e.status})`}async function Mi(e){const t=e.message.trim();if(!t)throw new Error("Message is required");const n=e.authToken.trim();if(!n)throw new Error("Auth token is required");const r=(e.apiBase?.trim()||ot).replace(/\/$/,""),i=await fetch(`${r}/avatarReply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,Accept:"text/event-stream"},body:JSON.stringify({message:t,history:e.history??[],persona_id:e.personaId?.trim()||""})});if(!i.ok)throw new Error(await no(i));if(!i.body)throw new Error("avatarReply response body is empty");const s=i.body.getReader(),o=new TextDecoder;let a="",l="",f="",u="";for(;;){const{done:c,value:d}=await s.read();if(c)break;a+=o.decode(d,{stream:!0});const p=a.split(`
|
|
48
|
+
`);a=p.pop()||"";for(const T of p){if(T.startsWith("event: ")){u=T.slice(7).trim();continue}if(!T.startsWith("data: "))continue;const m=T.slice(6).trim();if(!m)continue;let A;try{A=JSON.parse(m)}catch{continue}if(u==="spokenText")l=A.text||"",e.onSpokenText?.(l);else if(u==="displayText")f=A.text||"";else if(u==="error")throw new Error(A.error||"avatarReply stream error")}}if(!l.trim()||!f.trim())throw new Error("avatarReply stream missing displayText or spokenText");return{displayText:f.trim(),spokenText:l.trim()}}function ro({muted:e}){return e?z.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[z.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),z.jsx("path",{d:"m16 9.5 5 5m0-5-5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):z.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[z.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),z.jsx("path",{d:"M15.5 8.5a4.5 4.5 0 0 1 0 7M18.5 6a8 8 0 0 1 0 12",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}function io(){return z.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:z.jsx("path",{d:"M8 5.5v13l11-6.5L8 5.5Z"})})}function so(){return z.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:z.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}function ao(){return z.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:z.jsx("path",{d:"M5 6.5A2.5 2.5 0 0 1 7.5 4h9A2.5 2.5 0 0 1 19 6.5v7A2.5 2.5 0 0 1 16.5 16H10l-4 3.5V16H7.5A2.5 2.5 0 0 1 5 13.5v-7Z",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round"})})}function Ci({className:e}){return z.jsx("span",{className:e??"aitwin-widget__spinner","aria-hidden":!0,children:z.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:z.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeDasharray:"40 20"})})})}function oo({muted:e,onToggle:t}){return z.jsx("button",{type:"button",className:"aitwin-widget__mute",onClick:t,"aria-label":e?"Unmute":"Mute","aria-pressed":e,children:z.jsx(ro,{muted:e})})}function co(){return z.jsxs("div",{className:"aitwin-widget__connecting",role:"status","aria-live":"polite",children:[z.jsx(Ci,{className:"aitwin-widget__spinner aitwin-widget__spinner--accent"}),z.jsx("span",{children:"Connecting..."})]})}function uo(e){const t=e.connecting||e.textSending||e.status==="loading"||e.status==="speaking",n=e.connecting?"Connecting...":e.connected?"End Talk":"Talk",r=["aitwin-widget__action",e.textMode&&!e.connecting?"":"aitwin-widget__action--primary",e.connecting?"aitwin-widget__action--connecting":""].filter(Boolean).join(" ");return z.jsxs("div",{className:"aitwin-widget__controls",children:[z.jsxs("div",{className:"aitwin-widget__actions",children:[z.jsxs("button",{type:"button",className:r,onClick:e.onTalk,disabled:!e.ready||e.connecting||e.textSending,"aria-busy":e.connecting,children:[e.connecting?z.jsx(Ci,{className:"aitwin-widget__spinner aitwin-widget__spinner--on-accent"}):e.connected?z.jsx(so,{}):z.jsx(io,{}),z.jsx("span",{children:n})]}),z.jsxs("button",{type:"button",className:e.textMode?"aitwin-widget__action aitwin-widget__action--primary":"aitwin-widget__action",onClick:e.onTextMode,disabled:!e.ready||e.connecting||e.textSending,"aria-pressed":e.textMode,children:[z.jsx(ao,{}),z.jsx("span",{children:"Text"})]})]}),e.textMode?z.jsxs("form",{className:"aitwin-widget__composer",onSubmit:i=>{i.preventDefault(),e.onSendText()},children:[z.jsx("input",{type:"text",className:"aitwin-widget__composer-input",value:e.textDraft,onChange:i=>e.onTextDraftChange(i.target.value),placeholder:e.textSending?"Getting reply...":"Type a message…",autoComplete:"off",disabled:!e.ready||t}),z.jsx("button",{type:"submit",className:"aitwin-widget__composer-send",disabled:!e.ready||t||!e.textDraft.trim()&&!e.textSending,"aria-busy":e.textSending,children:e.textSending?"…":"Send"})]}):null,e.error?z.jsx("p",{className:"aitwin-widget__controls-error",role:"alert",children:e.error}):null]})}function Cr(e){const t=e.id?.trim()||void 0,n=e.faceId?.trim()||e.avatarId?.trim()||void 0;return{id:n?void 0:t,faceId:n,authToken:e.authToken?.trim()||void 0,apiBase:e.apiBase?.trim()||void 0,voiceId:e.voiceId?.trim()||void 0,speakingRate:e.speakingRate}}function lo(e){return[e.id??"",e.faceId??"",e.authToken?.slice(0,16)??"",e.voiceId??"",e.apiBase??"",String(e.speakingRate??"")].join("|")}const Rr={display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",lineHeight:0},fo={display:"block",height:"100%",width:"100%",objectFit:"cover",objectPosition:"top"},mo=w.forwardRef(function({options:t},n){const r=w.useRef(null),i=w.useRef(t);i.current={...i.current,onReady:t.onReady,onStatusChange:t.onStatusChange,onError:t.onError,onUserTranscript:t.onUserTranscript,onBotOutput:t.onBotOutput};const[s,o]=w.useState(!!t.showControls),[a,l]=w.useState(()=>Cr(t)),[f,u]=w.useState(!1),[c,d]=w.useState(!1),[p,T]=w.useState(!1),[m,A]=w.useState("idle"),[C,x]=w.useState(null),[g,E]=w.useState(!1),[N,I]=w.useState(!1),[te,de]=w.useState(""),[P,W]=w.useState(!1),[K,X]=w.useState([]),[Y,pe]=w.useState(t.personaId?.trim()||void 0),j=w.useCallback(b=>{i.current={...i.current,...b},b.showControls!==void 0&&o(!!b.showControls),b.personaId!==void 0&&pe(b.personaId.trim()||void 0),l(L=>Cr({id:b.id??L.id,faceId:b.faceId??b.avatarId??L.faceId,authToken:b.authToken??L.authToken,apiBase:b.apiBase??L.apiBase,voiceId:b.voiceId??L.voiceId,speakingRate:b.speakingRate??L.speakingRate}))},[]);w.useImperativeHandle(n,()=>({getTwin:()=>r.current,applyOptions:j}),[j]),w.useEffect(()=>{j(t)},[j,t.id,t.faceId,t.avatarId,t.authToken,t.apiBase,t.voiceId,t.speakingRate,t.showControls,t.personaId]);const Z=w.useCallback(()=>{u(!0),x(null),i.current.onReady?.()},[]),M=w.useCallback(b=>{A(b),i.current.onStatusChange?.(b)},[]),G=w.useCallback(b=>{x(b),T(!1),i.current.onError?.(b)},[]),V=w.useCallback((b,L)=>{i.current.onUserTranscript?.(b,L)},[]),ue=w.useCallback(b=>{i.current.onBotOutput?.(b)},[]);w.useEffect(()=>{if(!s)return;const b=window.setInterval(()=>{d(!!r.current?.isConnected())},400);return()=>window.clearInterval(b)},[s,a]),w.useEffect(()=>{f&&r.current?.setMuted(g)},[f,g,a]),w.useEffect(()=>{X([])},[a.id,a.faceId]);const ne=()=>{const b=r.current;if(!b?.isReady())return;if(x(null),I(!1),b.isConnected()){T(!1),b.disconnect().finally(()=>{d(!1)});return}T(!0);const L={authToken:a.authToken,voiceId:a.voiceId,speakingRate:a.speakingRate,apiBase:a.apiBase};b.connect(L).then(()=>{d(!!b.isConnected())}).catch(B=>{const O=B instanceof Error?B.message:"Failed to connect voice.";x(O),i.current.onError?.(O)}).finally(()=>{T(!1)})},ae=()=>{I(b=>!b),x(null)},we=()=>{const b=te.trim(),L=r.current;!b||!L?.isReady()||P||(x(null),de(""),W(!0),i.current.onUserTranscript?.(b,!0),(async()=>{try{const B=a.authToken?.trim()||await Mt(),O=Y||L.getPersonaId()?.trim()||void 0,_=await Mi({message:b,authToken:B,apiBase:a.apiBase||ot,personaId:O,history:K});X(v=>[...v,{role:"user",content:b},{role:"assistant",content:_.displayText}]),i.current.onBotOutput?.(_.displayText),await L.speakText(_.spokenText,{voiceId:a.voiceId,speakingRate:a.speakingRate})}catch(B){const O=B instanceof Error?B.message:"Failed to get reply.";x(O),i.current.onError?.(O)}finally{W(!1)}})())},oe=()=>{const b=!g;E(b),r.current?.setMuted(b)},S=lo(a),$=!!(a.id||a.faceId);return z.jsxs("div",{className:"aitwin-widget__layout",children:[z.jsxs("div",{className:"aitwin-widget__stage",children:[$?z.jsx("div",{style:Rr,children:z.jsx(Pi,{ref:r,id:a.id,faceId:a.faceId,authToken:a.authToken,apiBase:a.apiBase,voiceId:a.voiceId,speakingRate:a.speakingRate,style:Rr,canvasStyle:fo,onReady:Z,onStatusChange:M,onError:G,onUserTranscript:V,onBotOutput:ue},S)}):z.jsx("p",{className:"aitwin-widget__hint",style:{padding:16},children:"Pass id or faceId to load a twin."}),s?z.jsx(oo,{muted:g,onToggle:oe}):null,s&&p?z.jsx(co,{}):null]}),s?z.jsx(uo,{ready:f,connected:c,connecting:p,status:m,textMode:N,textDraft:te,textSending:P,error:C,onTalk:ne,onTextMode:ae,onTextDraftChange:de,onSendText:we}):null]})}),ho=".aitwin-widget{--aitwin-border: rgba(255, 255, 255, .12);--aitwin-text: #f4f4f5;--aitwin-muted: #a1a1aa;--aitwin-accent: #f97316;--aitwin-accent-hover: #fb923c;--aitwin-font: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;--aitwin-size: 1;--aitwin-stage-width: calc(200px * var(--aitwin-size));--aitwin-stage-height: calc(267px * var(--aitwin-size));--aitwin-action-height: calc(40px * var(--aitwin-size));--aitwin-action-font: calc(13px * var(--aitwin-size));--aitwin-action-radius: calc(10px * var(--aitwin-size));--aitwin-action-gap: calc(6px * var(--aitwin-size));--aitwin-mute-size: calc(28px * var(--aitwin-size));--aitwin-layout-gap: calc(8px * var(--aitwin-size));box-sizing:border-box;color:var(--aitwin-text);font-family:var(--aitwin-font);font-size:calc(12px * var(--aitwin-size));line-height:1.45;width:fit-content;max-width:100%}.aitwin-widget *,.aitwin-widget *:before,.aitwin-widget *:after{box-sizing:border-box}.aitwin-widget__layout{display:flex;flex-direction:column;gap:var(--aitwin-layout-gap);width:fit-content;max-width:100%}.aitwin-widget__stage{align-items:center;background:#0a0a0b;border:1px solid var(--aitwin-border);border-radius:calc(10px * var(--aitwin-size));display:flex;flex-shrink:0;height:var(--aitwin-stage-height);justify-content:center;line-height:0;overflow:hidden;position:relative;width:var(--aitwin-stage-width)}.aitwin-widget__stage .aitwin-root,.aitwin-widget__stage canvas{display:block;height:100%;object-fit:cover;object-position:top;width:100%}.aitwin-widget__hint{color:var(--aitwin-muted);font-size:calc(11px * var(--aitwin-size));margin:0}.aitwin-widget__mute{align-items:center;background:#28282cb8;border:none;border-radius:999px;color:#fff;cursor:pointer;display:inline-flex;height:var(--aitwin-mute-size);justify-content:center;padding:0;position:absolute;right:calc(8px * var(--aitwin-size));top:calc(8px * var(--aitwin-size));width:var(--aitwin-mute-size);z-index:2}.aitwin-widget__mute:hover{background:#37373cd9}.aitwin-widget__mute svg{height:calc(15px * var(--aitwin-size));width:calc(15px * var(--aitwin-size))}.aitwin-widget__controls{display:flex;flex-direction:column;gap:var(--aitwin-action-gap);width:var(--aitwin-stage-width)}.aitwin-widget__actions{display:grid;gap:var(--aitwin-action-gap);grid-template-columns:1fr 1fr;width:100%}.aitwin-widget__action{align-items:center;background:transparent;border:1.5px solid var(--aitwin-accent);border-radius:999px;color:var(--aitwin-accent);cursor:pointer;display:inline-flex;font-family:inherit;font-size:var(--aitwin-action-font);font-weight:600;gap:calc(6px * var(--aitwin-size));height:var(--aitwin-action-height);justify-content:center;padding:0 calc(10px * var(--aitwin-size))}.aitwin-widget__action svg{flex-shrink:0;height:calc(12px * var(--aitwin-size));width:calc(12px * var(--aitwin-size))}.aitwin-widget__action:hover:not(:disabled){background:#f973161a}.aitwin-widget__action:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__action--primary{background:var(--aitwin-accent);border-color:transparent;color:#fff}.aitwin-widget__action--primary:hover:not(:disabled){background:var(--aitwin-accent-hover)}.aitwin-widget__action--connecting:disabled{cursor:progress;opacity:1}.aitwin-widget__spinner{display:inline-flex;flex-shrink:0;height:calc(14px * var(--aitwin-size));width:calc(14px * var(--aitwin-size))}.aitwin-widget__spinner svg{animation:aitwin-widget-spin .8s linear infinite;display:block;height:100%;width:100%}.aitwin-widget__spinner--accent{color:var(--aitwin-accent);height:calc(16px * var(--aitwin-size));width:calc(16px * var(--aitwin-size))}.aitwin-widget__spinner--on-accent{color:#fff}@keyframes aitwin-widget-spin{to{transform:rotate(360deg)}}.aitwin-widget__connecting{align-items:center;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);background:#ffffffe0;border-radius:999px;bottom:calc(14px * var(--aitwin-size));box-shadow:0 4px 16px #0000001f;color:#3f3f46;display:inline-flex;font-size:calc(12px * var(--aitwin-size));font-weight:600;gap:calc(8px * var(--aitwin-size));left:50%;line-height:1;padding:calc(8px * var(--aitwin-size)) calc(14px * var(--aitwin-size));pointer-events:none;position:absolute;transform:translate(-50%);z-index:3}.aitwin-widget__composer{display:grid;gap:var(--aitwin-action-gap);grid-template-columns:1fr auto;width:100%}.aitwin-widget__composer-input{background:#ffffff0a;border:1px solid var(--aitwin-border);border-radius:var(--aitwin-action-radius);color:var(--aitwin-text);font-family:inherit;font-size:calc(12px * var(--aitwin-size));min-width:0;outline:none;padding:calc(8px * var(--aitwin-size)) calc(10px * var(--aitwin-size))}.aitwin-widget__composer-input:focus{border-color:#f973168c}.aitwin-widget__composer-send{background:var(--aitwin-accent);border:none;border-radius:var(--aitwin-action-radius);color:#fff;cursor:pointer;font-family:inherit;font-size:calc(12px * var(--aitwin-size));font-weight:600;padding:0 calc(12px * var(--aitwin-size))}.aitwin-widget__composer-send:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__controls-error{color:#fecaca;font-size:calc(11px * var(--aitwin-size));margin:0}.aitwin-widget--float{bottom:20px;filter:drop-shadow(0 12px 32px rgba(0,0,0,.45));height:fit-content;margin:0;max-width:calc(100vw - 40px);position:fixed;right:20px;width:fit-content;z-index:2147483000}",Dr="data-aitwin-widget-style";function po(){if(typeof document>"u"||document.querySelector(`style[${Dr}]`))return;const e=document.createElement("style");e.setAttribute(Dr,"1"),e.textContent=ho,document.head.appendChild(e)}const wo=w.forwardRef(function(t,n){const r=w.useRef(null);w.useEffect(()=>{po()},[]),w.useImperativeHandle(n,()=>({speakText:async(s,o)=>{const a=r.current?.getTwin();if(!a)throw new Error("AiTwinWidget: twin is not mounted");return a.speakText(s,o)},connect:async s=>{const o=r.current?.getTwin();if(!o)throw new Error("AiTwinWidget: twin is not mounted");return o.connect(s)},disconnect:async()=>{const s=r.current?.getTwin();if(s)return s.disconnect()},stop:()=>{r.current?.getTwin()?.stop()},isReady:()=>!!r.current?.getTwin()?.isReady(),isConnected:()=>!!r.current?.getTwin()?.isConnected(),getTwin:()=>r.current?.getTwin()??null}),[]);const i=!!t.float;return z.jsx("div",{className:i?"aitwin-widget aitwin-widget--float":"aitwin-widget",children:z.jsx(mo,{ref:r,options:t})})}),Ri="thumbnail.webp";function go(e,t=Rn){const n=e.trim();if(!n)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${n}/${Ri}`}const yo=new Set([".png",".jpg",".jpeg",".webp"]);function Di(e=".png"){const t=e.toLowerCase();return yo.has(t)?`source${t}`:"source.png"}function _o(e,t=Rn,n=".png"){const r=e.trim();if(!r)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${r}/${Di(n)}`}exports.AI_TWIN_THUMBNAIL_FILENAME=Ri;exports.AiTwin=Pi;exports.AiTwinNotFoundError=Gt;exports.AiTwinWidget=wo;exports.CONSONANT_SKIP_GROUP=Qr;exports.DEFAULT_TTS_ENGINE_ID=st;exports.EMOTION_TO_EYEBROW=vi;exports.EXPRESSION_ATLAS_EMOTIONS=Xs;exports.MIC_SAMPLE_RATE=Wn;exports.OCULUS_VISEME_IDS=jr;exports.PLAYBACK_SAMPLE_RATE=Hn;exports.SPEAKING_RATE_MAX=cn;exports.SPEAKING_RATE_MIN=on;exports.TTS_ENGINE_CARTESIA=ct;exports.TTS_ENGINE_GOOGLE=Bn;exports.TTS_ENGINE_INWORLD=tn;exports.VISEME_IDS=Vs;exports.VISEME_SKIP_GAP_MS=xn;exports.VISEME_TEST_CARTESIA_VOICE_ID=Un;exports.VISEME_TEST_SPEAKING_RATE=Ft;exports.VISEME_TEST_VOICE_ID=Vn;exports.VISEME_VTIME_GRID_MS=Fn;exports.VOWEL_SKIP_GROUP=Yr;exports.aiTwinSourceFilename=Di;exports.buildPlaybackTransitions=ri;exports.buildPlaybackVisemeSeries=sn;exports.buildRawVisemeTransitions=ni;exports.buildVoiceWebSocketUrl=fi;exports.compactSkippableVisemes=On;exports.createAvatarTtsLipsyncController=En;exports.createRealtimeVoiceLipsyncController=di;exports.emotionToEyebrow=at;exports.faceAssetUrls=kn;exports.fetchAiTwin=Nr;exports.fetchAvatarReply=Mi;exports.fetchDevAuthToken=Mt;exports.getAiTwinSourceUrl=_o;exports.getAiTwinThumbnailUrl=go;exports.listSkippedVisemeEntries=an;exports.listSkippedVisemes=ws;exports.normalizeOculusViseme=nn;exports.normalizeStreamEmotion=je;exports.resolveDirectFaceId=Vr;exports.resolveVisemeAtTime=Bt;exports.resolveVisemeFromPlaybackSeries=Zr;exports.resolveWordAtTime=xs;exports.setActiveTwinAssets=Ur;exports.snapVisemeQueueToGrid=Ln;exports.snapVisemeVtimeToGrid=Xr;
|