@streamoji/aitwin 0.7.5 → 0.7.6

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 CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M=require("react/jsx-runtime"),m=require("react"),bs=require("@pipecat-ai/client-js"),nr=require("@pipecat-ai/websocket-transport"),we=require("pixi.js");var Nn=typeof document<"u"?document.currentScript:null;const Ss="https://aitwin.bubu.social",wi={publicBase:Ss},Ts="0.7.5",ks={version:Ts},xs={},Pt="https://ai.aitwin.me",rr=`${wi.publicBase}/custom-faces`,Es=`${wi.publicBase}/aitwin-workers/v${ks.version}/visemeDiffPreview.worker.js`;function Is(e){if(e)return e;const t=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Nn&&Nn.tagName.toUpperCase()==="SCRIPT"&&Nn.src||new URL("aitwin.cjs",document.baseURI).href}<"u"?xs?.VITE_AITWIN_WORKER_URL:void 0;return t?.trim()?t.trim():Es}const As="https://us-central1-streamoji-265f4.cloudfunctions.net/getAiTwin",On=3e3,Vt=16,Nr=3e3,Ms=4e3,Rs=.85,Cs=8,ir=400,sr="eng_a7f2b9c1",gn="eng_d4e8f3a2",st="eng_c9b1e6d4",at="visemetts",yt=st,yn="eve",$n=new Set([gn,st,at]),ar={[sr]:"oculus_direct",[st]:"oculus_direct",[at]:"oculus_direct",[gn]:"inworld_word"},Kn={google:sr,inworld:gn,cartesia:st,visemetts:at};function Ps(e){const t=e.trim();if(t)return t in ar?t:Kn[t.toLowerCase()]}function gi(e){const t=e?.trim();if(!t)return{};const n=t.indexOf(":");if(n<=0)return{voiceId:t};const r=Ps(t.slice(0,n));if(!r)return{voiceId:t};const i=t.slice(n+1).trim();return{ttsEngineId:r,voiceId:i||void 0}}function it(e,t){const n=gi(t);return{ttsEngineId:n.ttsEngineId??e,voiceId:n.voiceId}}function yi(e){return ar[e]}function vi(e){return e===st}function _i(e){return e===at}function Ds(e){if(e.ttsEngineId&&e.ttsEngineId in ar)return e.ttsEngineId;const t=e.tts?.toLowerCase();return t&&t in Kn?Kn[t]:yt}class un extends Error{constructor(t="AI twin not found"){super(t),this.name="AiTwinNotFoundError"}}function or(e,...t){const n=typeof e=="string"?e:e?.brainId?.trim()||e?.knowledgeContextId?.trim();for(const r of[n,...t]){const i=r?.trim();if(i)return i}}function cr(e,...t){const n=typeof e=="string"?e:e?.brainUrl?.trim();for(const r of[n,...t]){const i=r?.trim();if(i)return i}}function Bs(e){const t=(e??"").trim();if(!t)return;let n;try{n=new URL(t)}catch{throw new Error("brainUrl must be an http or https URL")}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error("brainUrl must be an http or https URL");if(!n.host)throw new Error("brainUrl must be an http or https URL");if(n.hash)throw new Error("brainUrl must not include a fragment");return t}async function bi(e,t=As){const n=new URL(t);n.searchParams.set("id",e);const r=await fetch(n.toString());if(r.status===404)throw new un;if(!r.ok)throw new Error(`getAiTwin failed (${r.status})`);const i=await r.json();if(!i.success)throw new un(i.error??"AI twin not found");const{tts:s,token:o,...a}=i.data,u=String(a.authToken??o??"").trim()||void 0,d=or(a),l=cr(a);return{...a,ttsEngineId:Ds(i.data),authToken:u,brainId:d,knowledgeContextId:d,brainUrl:l}}const lr="thumbnail.webp";function Si(e,t=rr){const n=e.trim();if(!n)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${n}/${lr}`}function Or(e){const t=e?.trim();if(!t)return null;try{return Si(t)}catch{return null}}function Fs(e){if(!e)return null;const t=(e.binBase||e.twinBase).trim().replace(/\/$/,"");return t?`${t}/${lr}`:null}const Ls="https://us-central1-streamoji-265f4.cloudfunctions.net/getAuthToken",Ns="client_6TNvp3SCs4Og0a1ijm9TommXLql1",Os="kk8Fq8EmexzP10jMIEwY3R44M5RKUEm1",Us="6TNvp3SCs4Og0a1ijm9TommXLql1",Vs="Swaraj Mali";async function ln(){const e=await fetch(Ls,{method:"POST",headers:{"Content-Type":"application/json","Client-Id":Ns,"Client-Secret":Os},body:JSON.stringify({userId:Us,userName:Vs})});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 Ws(e,t=Pt){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 js(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 rn(e){return Uint8Array.from(e)}function zs(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}async function Hs(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=rn(n.subarray(0,12)),i=rn(n.subarray(12,28)),s=rn(n.subarray(28)),o=rn(zs(s,i)),a=await crypto.subtle.importKey("raw",js(t),{name:"AES-GCM"},!1,["decrypt"]);return crypto.subtle.decrypt({name:"AES-GCM",iv:r,tagLength:128},a,o)}let Gn=null;const qn=new Set;function sn(e){return e.includes("/custom-faces/")}function dn(e){const t=e.binBase.trim().replace(/\/$/,""),n=e.twinBase.trim().replace(/\/$/,"");if(!(e.encrypted||sn(t)||sn(n)))return{twinBase:n,binBase:t,encrypted:!1};const i=sn(t)?t:sn(n)?n:t;return{twinBase:i,binBase:i,encrypted:!0}}function bt(e){return dn(e).encrypted}function Yn(e,t=rr){const n=`${t.replace(/\/$/,"")}/${e}`;return{twinBase:n,binBase:n,encrypted:!0}}function Ti(e,t){return(e??t)?.trim()||void 0}function ki(e){Gn=dn(e);for(const t of qn)t()}function $s(e,t){const n=typeof globalThis.location<"u"?globalThis.location.href:void 0;if(!n)return dn(e);const r=i=>{try{return new URL(i,n).href.replace(/\/$/,"")}catch{return i}};return dn({twinBase:r(e.twinBase),binBase:r(e.binBase),encrypted:e.encrypted})}function St(){if(!Gn)throw new Error("Twin assets not configured; call setActiveTwinAssets first");return Gn}function xi(e){return qn.add(e),()=>qn.delete(e)}function fn(){const e=St();return bt(e)?`${e.binBase}/sil.bin`:`${e.twinBase}/sil.png`}function Ks(){const e=St();return bt(e)?`${e.binBase}/idle.bin`:`${e.twinBase}/idle.mp4`}function Ei(){const e=St();return bt(e)?e.binBase:e.twinBase}function Ht(){return bt(St())}function Ii(){const e=St();return bt(e)?`${e.binBase}/atlas.bin`:`${e.twinBase}/atlas.json`}function Ai(){const e=St();return bt(e)?`${e.binBase}/expression_atlas.bin`:`${e.twinBase}/expression_atlas.json`}const vt=[{code:"en",label:"English",visemetts:!0,cartesia:!0},{code:"es",label:"Spanish",visemetts:!0,cartesia:!0},{code:"es-MX",label:"Spanish (Mexico)",visemetts:!0,cartesia:!0},{code:"es-ES",label:"Spanish (Spain)",visemetts:!0,cartesia:!0},{code:"pt",label:"Portuguese",visemetts:!0,cartesia:!0},{code:"pt-BR",label:"Portuguese (Brazil)",visemetts:!0,cartesia:!0},{code:"pt-PT",label:"Portuguese (Portugal)",visemetts:!0,cartesia:!0},{code:"fr",label:"French",visemetts:!0,cartesia:!0},{code:"de",label:"German",visemetts:!0,cartesia:!0},{code:"it",label:"Italian",visemetts:!0,cartesia:!0},{code:"zh",label:"Chinese",visemetts:!0,cartesia:!0},{code:"ja",label:"Japanese",visemetts:!0,cartesia:!0},{code:"hi",label:"Hindi",visemetts:!0,cartesia:!0},{code:"ko",label:"Korean",visemetts:!0,cartesia:!0},{code:"ru",label:"Russian",visemetts:!0,cartesia:!0},{code:"tr",label:"Turkish",visemetts:!0,cartesia:!0},{code:"id",label:"Indonesian",visemetts:!0,cartesia:!0},{code:"ar",label:"Arabic",visemetts:!0,cartesia:!0},{code:"ar-EG",label:"Arabic (Egypt)",visemetts:!0,cartesia:!0},{code:"ar-AE",label:"Arabic (UAE)",visemetts:!0,cartesia:!0},{code:"vi",label:"Vietnamese",visemetts:!0,cartesia:!0},{code:"bn",label:"Bengali",visemetts:!0,cartesia:!0},{code:"auto",label:"Auto-detect",visemetts:!0,cartesia:!1},{code:"nl",label:"Dutch",visemetts:!1,cartesia:!0},{code:"pl",label:"Polish",visemetts:!1,cartesia:!0},{code:"sv",label:"Swedish",visemetts:!1,cartesia:!0},{code:"tl",label:"Tagalog",visemetts:!1,cartesia:!0},{code:"bg",label:"Bulgarian",visemetts:!1,cartesia:!0},{code:"ro",label:"Romanian",visemetts:!1,cartesia:!0},{code:"cs",label:"Czech",visemetts:!1,cartesia:!0},{code:"el",label:"Greek",visemetts:!1,cartesia:!0},{code:"fi",label:"Finnish",visemetts:!1,cartesia:!0},{code:"hr",label:"Croatian",visemetts:!1,cartesia:!0},{code:"ms",label:"Malay",visemetts:!1,cartesia:!0},{code:"sk",label:"Slovak",visemetts:!1,cartesia:!0},{code:"da",label:"Danish",visemetts:!1,cartesia:!0},{code:"ta",label:"Tamil",visemetts:!1,cartesia:!0},{code:"uk",label:"Ukrainian",visemetts:!1,cartesia:!0},{code:"hu",label:"Hungarian",visemetts:!1,cartesia:!0},{code:"no",label:"Norwegian",visemetts:!1,cartesia:!0},{code:"th",label:"Thai",visemetts:!1,cartesia:!0},{code:"he",label:"Hebrew",visemetts:!1,cartesia:!0},{code:"ka",label:"Georgian",visemetts:!1,cartesia:!0},{code:"te",label:"Telugu",visemetts:!1,cartesia:!0},{code:"gu",label:"Gujarati",visemetts:!1,cartesia:!0},{code:"kn",label:"Kannada",visemetts:!1,cartesia:!0},{code:"ml",label:"Malayalam",visemetts:!1,cartesia:!0},{code:"mr",label:"Marathi",visemetts:!1,cartesia:!0},{code:"pa",label:"Punjabi",visemetts:!1,cartesia:!0}],Mi=vt.map(e=>e.code),Gs=new Set(Mi),qs=new Set(vt.filter(e=>e.visemetts).map(e=>e.code)),Ys=new Set(vt.filter(e=>e.cartesia).map(e=>e.code)),Qs="en";function Ri(e){return Gs.has(e)}function vn(e){const t=e?.trim();if(t)return t}function Xs(e){return e===at?vt.filter(t=>t.visemetts).map(t=>t.code):e===st?vt.filter(t=>t.cartesia).map(t=>t.code):vt.filter(t=>t.visemetts&&t.cartesia).map(t=>t.code)}function Js(e,t){const n=t.trim();return n?e===at?qs.has(n):e===st?Ys.has(n):Ri(n):!1}function Ci(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 Pi=["aa","CH","DD","E","FF","I","O","PP","RR","SS","TH","U","kk","nn","sil"],Zs=new Map(Pi.map(e=>[e.toLowerCase(),e]));function _n(e){const t=(e??"").trim();return t?Zs.get(t.toLowerCase())??"sil":"sil"}const ea={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 ta(e){if(!e)return["sil"];const t=e.toLowerCase();return ea[t]??["sil"]}function Di(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 At(e,t){const n=Math.max(0,Math.min(e.length-1,t));return e[n]??""}function bn(e,t){const n=e.toLowerCase().replace(/[^a-z']/g,"");return!n||At(n,t)!=="w"||t>0&&At(n,t-1)==="q"?!1:t===0&&/^w[aeiouy]/.test(n)}function na(e,t){const n=e.toLowerCase(),r=At(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 ra(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(bn(n,t))return"FF";const i=At(n,t);return i==="u"||i==="w"?"U":"O"}function ia(e,t){const n=e.toLowerCase();if(bn(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)||At(n,t)==="o"?"O":"U"}const an={d:"DD",t:"DD",n:"DD",s:"SS",z:"SS",k:"kk",g:"kk",c:"CH",x:"CH",j:"CH"};function sa(e,t){const n=e.toLowerCase(),r=At(n,t);if(an[r])return an[r];for(let i=0;i<n.length;i++){const s=n[i];if(an[s])return an[s]}return"DD"}function Bi(e,t,n){const r=ta(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 na(i,o);case"o":return ra(i,o);case"qw":return ia(i,o);case"cdgknstxyz":return sa(i,o);default:return r[0]}}const ur=16,Qn=47,Fi=new Set(["aa","E","I"]),Li=new Set(["DD","SS","kk","CH"]),aa=[Fi,Li];function oa(e){for(const t of aa)if(t.has(e))return t;return null}function ca(e){return oa(e)!=null}function Ni(e,t=ur){return t<=0?e:Math.round(e/t)*t}function dr(e,t=ur){return e.map(n=>({...n,vtime:Ni(n.vtime,t)}))}function Oi(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 fr(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(!ca(r.viseme)){t.push(r);continue}const o=r.vtime-s.vtime,a=i.vtime-r.vtime;o<Qn||a<Qn||t.push(r)}return t.push(e[e.length-1]),t}function Sn(e){return fr(Oi(dr(e)))}function Ui(e,t){let n="sil";for(const r of e){if(r.vtime>t)break;r.viseme!=="sil"&&(n=r.viseme)}return n}function Tn(e){const t=Oi(dr(e)),n=fr(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 la(e){return Tn(e).map(t=>t.viseme)}const ua=32,Ur=48;function Vi(e){let t=0;for(const n of e)t=Math.max(t,n.vtime+n.vduration);return t}function Wi(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 da(e){return Sn(e).find(n=>n.viseme!=="sil")??null}function wt(e){const t=Vi(e);return Wi(e)?t+ir:t}function fa(e){const t=[],n=da(e);n&&n.vtime>0&&t.push({from:"sil",to:n.viseme,fromVtime:0,toVtime:n.vtime});const r=Wi(e),i=Vi(e);return r&&t.push({from:r.viseme,to:"sil",fromVtime:i,toVtime:i+ir}),t}function ji(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 zi(e){return e.length===0?[]:[...fa(e),...ji(e)]}function ma(e,t,n=!1){let r=null;for(const i of e){const{transStart:s,transEnd:o}=Hi(i.fromVtime,i.toVtime,i.from,i.to,n);t>=s&&t<o&&(r=i)}return r}function Hi(e,t,n,r,i=!1){const s=Math.max(0,t-e);if(i&&(n==="PP"||r==="PP")&&s>Ur){const l=Ur,c=t,f=c-l;return{gapMs:s,effectiveGapMs:l,holdEnd:f,transStart:f,transEnd:c}}const a=s>0?Math.max(s,ua):0,u=e,d=e+a;return{gapMs:s,effectiveGapMs:a,holdEnd:e,transStart:u,transEnd:d}}function $i(e,t,n,r,i,s){r.forEach(o=>{const u=String(o.word??"").trim();if(!u)return;const d=Math.round((o.start??0)*1e3),l=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:u,wtime:i+d,wduration:l,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 u=Math.round((o.start??0)*1e3),d=Math.max(1,Math.round((o.duration??0)*1e3)),l=i+u,c=qi(t,l),f=c?Di(c,l):0;let w;yi(s)==="oculus_direct"?(w=_n(a),w==="U"&&c&&bn(c.word,f)&&(w="FF")):w=Bi(a,c?.word??"",f),e.push({viseme:w,weight:1,vtime:l,vduration:d})})}function Ki(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 mr=16e3;function Gi(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:mr}function ha(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 pa(e){return e.length>=4&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70}function Vr(e,t,n=mr){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 wa(e){const t=ha(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 Wr(e,t,n=mr){const r=wa(t),i=Gi(n);if(pa(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 Vr(e,r,i);try{const s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);return await e.decodeAudioData(s)}catch{return Vr(e,r,i)}}function qi(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function Yi(e,t){const n=[],r=[];let i=null,s=!1,o=!1,a=!1,u=!1,d=0,l=0,c=0,f=null,w=1,T=t,h=!1,I=null,H=null,O=!1,v=0,E=!1,V=!1,L=0,se=null,re=null,P=null;const q=()=>({visemes:[],words:[],segmentOffsetMs:0}),Q=()=>{V=!1,L=0},ee=()=>{f!=null&&(clearTimeout(f),f=null)},oe=()=>{for(const _ of r){try{_.onended=null,_.stop(0)}catch{}try{_.disconnect()}catch{}}r.length=0},ue=()=>{for(const _ of r)_.playbackRate.value=w},Se=()=>{if(!(h||!u||s||V||r.length>0||n.length>0)){if(a&&i&&l>0){const _=(i.currentTime-l)*1e3;if(_<v){ee();const B=w>0?(v-_)/w:v-_;f=setTimeout(()=>{h||(o=!1,f=null,e.onSpeakingDone(),e.onNotify())},Math.max(0,B));return}}o=!1,ee(),e.onSpeakingDone(),e.onNotify()}},We=_=>{const B=wt(_);if(B<=0){e.onSpeakingDone(),e.onNotify();return}o=!0,d=performance.now(),e.onSpeakingStart(),e.onNotify(),ee();const W=w>0?B/w:B;f=setTimeout(()=>{h||(o=!1,f=null,e.onSpeakingDone(),e.onNotify())},W)},ne=(_,B,W,b)=>{B.length!==0&&(c=W,B.forEach(y=>{const A=String(y.word??"").trim();if(!A)return;const U=Math.round((y.start??0)*1e3),j=y.duration!=null?Math.round(y.duration*1e3):y.end!=null?Math.max(1,Math.round((y.end-(y.start??0))*1e3)):0;_.push({word:A,wtime:c+U,wduration:j,queueIndex:_.length,gesture:y.gesture??null,emphasis:y.emphasis===!0})}))},D=(_,B,W,b,y,x)=>{W.length!==0&&(c=b,W.forEach(A=>{const U=String(A.symbol??A.viseme??"").trim();if(!U)return;const j=Math.round((A.start??0)*1e3),Z=Math.max(1,Math.round((A.duration??0)*1e3)),Te=c+j,Ae=qi(B,Te),F=Ae?Di(Ae,Te):0;let te;yi(x)==="oculus_direct"?(te=_n(U),te==="U"&&Ae&&bn(Ae.word,F)&&(te="FF")):te=Bi(U,Ae?.word??"",F),_.push({viseme:te,weight:1,vtime:Te,vduration:Z})}),e.onNotify())},S=(_,B,W,b,y,x,A)=>{ne(B,b,y),D(_,B,W,y,x,A)},J=(_,B,W)=>{P===_&&_.visemes===B||(B.length=0,W.length=0,_.visemes=B,_.words=W,_.segmentOffsetMs=0,P=_,c=0,v=0)},X=_=>(H||(H=_.createGain(),H.gain.value=O?0:1,H.connect(_.destination)),H),ce=async()=>{const _=window.AudioContext||window.webkitAudioContext;return i||(i=new _,H=null,I=null),i.state==="suspended"&&await i.resume(),X(i),I||(I=i.createMediaStreamDestination()),i},Y=(_,B)=>{if(!i)return 0;const W=i,b=W.currentTime,y=b+.02;if(B.isFirstAudio){l<=0&&(l=y);const A=(y-b)*1e3;d=performance.now()+A}B.onBeforeStart?.(y);const x=W.createBufferSource();return x.buffer=_,x.playbackRate.value=w,x.connect(X(W)),I&&x.connect(I),r.push(x),h?(r.pop(),y):(B.isFirstAudio&&(o=!0,e.onSpeakingStart()),x.onended=()=>{const A=r.indexOf(x);A>=0&&r.splice(A,1),e.onNotify(),!h&&(se&&re?z(se,re):Se())},x.start(y),y)},z=async(_,B)=>{if(h||s||r.length>0)return;if(n.length===0){Se();return}s=!0;let W=!1;try{const b=await ce();if(h)return;const y=n[0];if(!y)return;const x=!o;if(E&&(e.shouldHoldForWarmup?.()??!1)&&(V||x&&y.newStream)||V){J(y.utterance,_,B);for(const j of n){if(h)return;j.audioBuffer||(j.audioBuffer=await Wr(b,j.audio,j.sampleRate)),a=!0,V||(V=!0,L=0,j.newStream&&j.onNewStream?.()),j.visemesQueued||(S(_,B,j.visemes,j.words,L,!0,T),j.visemesQueued=!0,L+=Math.round(j.audioBuffer.duration*1e3),v=Math.max(v,wt(_)))}e.onNotify();return}const U=n.shift();if(!U||(U.audioBuffer||(U.audioBuffer=await Wr(b,U.audio,U.sampleRate)),h))return;a=!0,ee(),J(U.utterance,_,B),U.visemesQueued=!1,U.newStream&&U.onNewStream?.(),Y(U.audioBuffer,{isFirstAudio:!o,isFirstOfStream:!1,onBeforeStart:j=>{l=j,c=0,d=performance.now()+(j-b.currentTime)*1e3,_.length=0,B.length=0,S(_,B,U.visemes,U.words,0,!0,T),U.visemesQueued=!0,U.utterance.segmentOffsetMs=0}}),W=r.length>0,v=wt(_),e.onNotify()}catch(b){console.error("[avatarChunkPlayback] audio chunk failed:",b)}finally{if(s=!1,h)return;if(V){n.some(y=>!y.audioBuffer||!y.visemesQueued)&&z(_,B);return}!W&&r.length===0&&n.length>0?z(_,B):r.length===0&&n.length===0&&Se()}};return{setStreamTtsEngineId:_=>{T=_},setPlaybackSpeed:_=>{w=Math.max(.1,Math.min(1,_)),ue()},getPlaybackSpeed:()=>w,setMuted:_=>{O=_,H&&(H.gain.value=_?0:1)},isMuted:()=>O,setLipsyncWarmupHoldEnabled:_=>{E=_,_||Q()},isWarmingUp:()=>V,releaseWarmupHold:()=>{if(V){V=!1,L=0;for(const _ of n)_.newStream=!1;se&&re&&z(se,re),e.onNotify()}},resetForNewStream:_=>{h=!1,u=!1,T=_,v=0},resumeBotStream:()=>{h=!1,u=!1},clearAborted:()=>{h=!1},primeAudioContext:async()=>{const _=window.AudioContext||window.webkitAudioContext;i||(i=new _,H=null,I=null),i.state==="suspended"&&await i.resume(),X(i),I||(I=i.createMediaStreamDestination())},stop:()=>{h=!0,ee(),oe(),n.length=0,s=!1,o=!1,a=!1,u=!1,c=0,l=0,d=0,v=0,se=null,re=null,P=null,Q()},markStreamComplete:_=>{if(v=Math.max(v,wt(_)),u=!0,!a&&_.length>0){We(_);return}Se()},playAudioChunk:async(_,B,W,b,y,x,A)=>{if(h)return;se=_,re=B;const U=Gi(A?.sampleRate),j=A?.newStream===!0,Z=q();if(!W?.trim()){if(b.length===0&&y.length===0)return;J(Z,_,B),j&&A?.onNewStream?.(),S(_,B,b,y,0,!0,T),v=wt(_),!o&&v>0&&We(_),e.onNotify();return}n.push({audio:W,audioBuffer:null,utterance:Z,visemes:b,words:y,isNewSegment:x,sampleRate:U,newStream:j,onNewStream:A?.onNewStream,visemesQueued:!1}),await z(_,B)},queueTimingsOnly:(_,B,W,b,y,x)=>{if(h)return;const A=q();J(A,_,B),S(_,B,W,b,0,!0,T),A.segmentOffsetMs=0,v=wt(_)},getPlaybackElapsedMs:()=>a&&i&&l>0?Math.max(0,(i.currentTime-l)*1e3*w):o?Math.max(0,(performance.now()-d)*w):0,isSpeaking:()=>o?!0:!a||!i||l<=0?!1:(i.currentTime-l)*1e3<v,getVoiceStream:()=>I?I.stream:null,getPlaybackStartPerf:()=>d,bargeIn:()=>{h=!0,u=!1,ee(),oe(),n.length=0,s=!1,o=!1,a=!1,c=0,l=0,d=0,v=0,se=null,re=null,P=null,Q()},interrupt:()=>{h=!0,u=!1,ee(),oe(),n.length=0,s=!1,o=!1,a=!1,c=0,l=0,d=0,v=0,se=null,re=null,P=null,Q()}}}function $t(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 Qi(e,t,n=120){const r=$t(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 ga(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 ya(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function jr(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 kn=.5,xn=1.5,hr="Olivia",pr="f786b574-daa5-4673-aa0c-cbe3e8534c02",Kt=.85;function Xn(e,t=Pt,n={}){const r=`${t.replace(/\/$/,"")}/avatar_ttsWithPoses`,i=[],s=[],o=[],a=[];let u=0;const d=[],l=[];let c="",f="neutral",w="",T=yt;const h=new Set;let I=0,H=null,O=0,v=null;const E=()=>h.forEach(D=>D());let V=()=>!1;const L=Yi({onSpeakingStart:()=>e("speaking"),onSpeakingDone:()=>e("done"),onNotify:E,shouldHoldForWarmup:()=>V()},yt),se=()=>L.getPlaybackElapsedMs(),re=(D,S=c)=>{if(!n.onLipsyncDebug)return;const J=se(),X=i,ce=Tn(o).map(Y=>({viseme:Y.viseme,vtimeMs:Y.vtime}));n.onLipsyncDebug({event:D,spokenText:S,mood:f,playbackAnchorPerf:L.getPlaybackStartPerf(),playbackElapsedMs:J,queueLength:X.length,activeViseme:$t(X,J),segments:l.map(Y=>({...Y,visemes:[...Y.visemes]})),fullQueueLength:o.length,compactionSkipped:ce})},P=(D,S)=>{n.onLipsyncDebug&&(H={event:D,spokenText:S},I===0&&(I=requestAnimationFrame(()=>{I=0;const J=H;H=null,J&&re(J.event,J.spokenText)})))},q=(D,S,J,X,ce)=>{if(!n.onLipsyncDebug)return;const Y=i.slice(S),z=J.filter($=>String($.symbol??$.viseme??"").trim());l.push({spokenText:D,audioOffsetMs:Y[0]?.vtime??0,isNewSegment:X,chunkDurationMs:ce,receivedAtMs:performance.now(),visemes:Y.map(($,ve)=>{const ae=z[ve];return{rawSymbol:String(ae?.symbol??ae?.viseme??$.viseme).trim(),viseme:$.viseme,startSec:Number(ae?.start??0),durationSec:Number(ae?.duration??0),vtimeMs:$.vtime,vdurationMs:$.vduration}})})},Q=()=>{o.length=0,a.length=0,u=0},ee=(D,S,J,X,ce)=>{if(D.length===0&&S.length===0)return;$i(o,a,D,S,u,ce);const Y=Ki(D,u),z=J?jr(J,X):null;u=Math.max(Y,z!=null?u+z:u)},oe=()=>{O+=1,v?.abort(),v=null,L.stop(),i.length=0,s.length=0,Q(),d.length=0,f="neutral",l.length=0,c="",e("idle"),P("reset"),E()},ue=D=>{const S=it(D?.ttsEngineId,D?.voiceId),J=S.ttsEngineId??T??yt,X=S.voiceId??(J===at?yn:hr),ce=D?.speakingRate??Kt,Y=Math.max(kn,Math.min(xn,ce));return{engineId:J,voiceId:X,speakingRate:Y,language:vn(D?.language)}},Se=async D=>{oe();const S=O;v=new AbortController,e("loading"),c=D.debugSpokenFallback,l.length=0,Q();const J=w.trim();if(!J)throw new Error("Developer token required for avatar_ttsWithPoses");L.resetForNewStream(D.engineId),L.setStreamTtsEngineId(D.engineId);let X="",ce="";try{const Y=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${J}`,Accept:"text/event-stream"},body:JSON.stringify(D.requestBody),signal:v.signal});if(!Y.ok)throw new Error(`avatar_ttsWithPoses failed (${Y.status})`);const z=Y.body;if(!z)throw new Error("No response body");const $=z.getReader(),ve=new TextDecoder;let ae="",_=!0;const B=()=>X||D.debugSpokenFallback,W=async b=>{if(S!==O)return;const y=Ci(b);if(y){if(y.event==="spokenText"){const x=typeof y.data.text=="string"?y.data.text.trim():"";x&&(X=x,c=x,D.onSpokenText?.(x),E());return}if(y.event==="displayText"){const x=typeof y.data.text=="string"?y.data.text.trim():"";x&&(ce=x,D.onDisplayText?.(x),E());return}if(y.event!=="done"){if(y.event==="audio"){const x=y.data.chunk,A=y.data.visemes??[],U=y.data.words??[],j=y.data.is_new_segment??!1,Z=y.data.sample_rate,Te=Number(y.data.audio_offset_ms??0),Ae=i.length,F=B();if(ee(A,U,x,Z,D.engineId),x){const te=_;_=!1,await L.playAudioChunk(i,s,x,A,U,j,{sampleRate:Z,newStream:te,audioOffsetMs:Te}),q(F,Ae,A,j,jr(x,Z)),P("audio_chunk",F)}else(A.length>0||U.length>0)&&(L.queueTimingsOnly(i,s,A,U,j,{audioOffsetMs:Te,newStream:_}),q(F,Ae,A,j,null),P("audio_chunk",F))}else if(y.event==="metadata"){const x=y.data.mood;typeof x=="string"&&x.trim()&&(f=x.trim());const A=y.data.spoken_text??y.data.text;typeof A=="string"&&A.trim()&&!X&&(X=A.trim(),c=X);const U=y.data.sentence_emotions;if(Array.isArray(U)){d.length=0;for(const j of U){if(!j||typeof j!="object")continue;const Z=j;d.push({sentence_index:Number(Z.sentence_index??0),text:String(Z.text??""),sentiment:typeof Z.sentiment=="string"?Z.sentiment:void 0,emotion:String(Z.emotion??f),start_word:Number(Z.start_word??0),end_word:Number(Z.end_word??0)})}}E(),P("metadata",B())}else if(y.event==="error")throw new Error(String(y.data.message??"avatar_ttsWithPoses stream error"))}}};for(;;){if(S!==O)return{displayText:ce,spokenText:X,aborted:!0};const{done:b,value:y}=await $.read();y&&(ae+=ve.decode(y,{stream:!0}));const x=ae.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("react/jsx-runtime"),u=require("react"),Ks=require("@pipecat-ai/client-js"),wn=require("@pipecat-ai/websocket-transport"),Te=require("pixi.js");var Xr=typeof document<"u"?document.currentScript:null;const qs="https://aitwin.bubu.social",Fi={publicBase:qs},Ys="0.7.6",Qs={version:Ys},Xs={},ut="https://ai.aitwin.me",Pr=`${Fi.publicBase}/custom-faces`,Js=`${Fi.publicBase}/aitwin-workers/v${Qs.version}/visemeDiffPreview.worker.js`;function Zs(e){if(e)return e;const t=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Xr&&Xr.tagName.toUpperCase()==="SCRIPT"&&Xr.src||new URL("aitwin.cjs",document.baseURI).href}<"u"?Xs?.VITE_AITWIN_WORKER_URL:void 0;return t?.trim()?t.trim():Js}const ea="https://us-central1-streamoji-265f4.cloudfunctions.net/getAiTwin",Jr=3e3,er=16,Jn=3e3,ta=4e3,ra=.85,na=8,yn=400,vn="eng_a7f2b9c1",Cr="eng_d4e8f3a2",dt="eng_c9b1e6d4",ft="visemetts",Et=dt,Fr="eve",an=new Set([Cr,dt,ft]),_n={[vn]:"oculus_direct",[dt]:"oculus_direct",[ft]:"oculus_direct",[Cr]:"inworld_word"},on={google:vn,inworld:Cr,cartesia:dt,visemetts:ft};function ia(e){const t=e.trim();if(t)return t in _n?t:on[t.toLowerCase()]}function Bi(e){const t=e?.trim();if(!t)return{};const r=t.indexOf(":");if(r<=0)return{voiceId:t};const n=ia(t.slice(0,r));if(!n)return{voiceId:t};const i=t.slice(r+1).trim();return{ttsEngineId:n,voiceId:i||void 0}}function lt(e,t){const r=Bi(t);return{ttsEngineId:r.ttsEngineId??e,voiceId:r.voiceId}}function Di(e){return _n[e]}function Li(e){return e===dt}function Oi(e){return e===ft}function sa(e){if(e.ttsEngineId&&e.ttsEngineId in _n)return e.ttsEngineId;const t=e.tts?.toLowerCase();return t&&t in on?on[t]:Et}class kr extends Error{constructor(t="AI twin not found"){super(t),this.name="AiTwinNotFoundError"}}function bn(e,...t){const r=typeof e=="string"?e:e?.brainId?.trim()||e?.knowledgeContextId?.trim();for(const n of[r,...t]){const i=n?.trim();if(i)return i}}function Sn(e,...t){const r=typeof e=="string"?e:e?.brainUrl?.trim();for(const n of[r,...t]){const i=n?.trim();if(i)return i}}function aa(e){const t=(e??"").trim();if(!t)return;let r;try{r=new URL(t)}catch{throw new Error("brainUrl must be an http or https URL")}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error("brainUrl must be an http or https URL");if(!r.host)throw new Error("brainUrl must be an http or https URL");if(r.hash)throw new Error("brainUrl must not include a fragment");return t}async function Ni(e,t=ea){const r=new URL(t);r.searchParams.set("id",e);const n=await fetch(r.toString());if(n.status===404)throw new kr;if(!n.ok)throw new Error(`getAiTwin failed (${n.status})`);const i=await n.json();if(!i.success)throw new kr(i.error??"AI twin not found");const{tts:s,token:o,...a}=i.data,f=String(a.authToken??o??"").trim()||void 0,h=bn(a),l=Sn(a);return{...a,ttsEngineId:sa(i.data),authToken:f,brainId:h,knowledgeContextId:h,brainUrl:l}}const Tn="thumbnail.webp";function Ui(e,t=Pr){const r=e.trim();if(!r)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${r}/${Tn}`}function Zn(e){const t=e?.trim();if(!t)return null;try{return Ui(t)}catch{return null}}function oa(e){if(!e)return null;const t=(e.binBase||e.twinBase).trim().replace(/\/$/,"");return t?`${t}/${Tn}`:null}const ca="https://us-central1-streamoji-265f4.cloudfunctions.net/getAuthToken",la="client_6TNvp3SCs4Og0a1ijm9TommXLql1",ua="kk8Fq8EmexzP10jMIEwY3R44M5RKUEm1",da="6TNvp3SCs4Og0a1ijm9TommXLql1",fa="Swaraj Mali";async function Tr(){const e=await fetch(ca,{method:"POST",headers:{"Content-Type":"application/json","Client-Id":la,"Client-Secret":ua},body:JSON.stringify({userId:da,userName:fa})});if(!e.ok)throw new Error(`getAuthToken failed (${e.status})`);const t=await e.json(),r=t.authToken??t.token??"";if(!r.trim())throw new Error("getAuthToken returned no token");return r}async function ma(e,t=ut){const r=await fetch(`${t.replace(/\/$/,"")}/api/session-value`,{headers:{Authorization:`Bearer ${e}`}});if(!r.ok)throw new Error(`/api/session-value failed (${r.status})`);const n=await r.json();if(!n.value)throw new Error("Session value response missing value");return n}function ha(e){const t=e.trim();if(t.length%2!==0)throw new Error("Invalid hex key");const r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function yr(e){return Uint8Array.from(e)}function pa(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e,0),r.set(t,e.length),r}async function ga(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 r=new Uint8Array(e),n=yr(r.subarray(0,12)),i=yr(r.subarray(12,28)),s=yr(r.subarray(28)),o=yr(pa(s,i)),a=await crypto.subtle.importKey("raw",ha(t),{name:"AES-GCM"},!1,["decrypt"]);return crypto.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},a,o)}let cn=null;const ln=new Set;function vr(e){return e.includes("/custom-faces/")}function Er(e){const t=e.binBase.trim().replace(/\/$/,""),r=e.twinBase.trim().replace(/\/$/,"");if(!(e.encrypted||vr(t)||vr(r)))return{twinBase:r,binBase:t,encrypted:!1};const i=vr(t)?t:vr(r)?r:t;return{twinBase:i,binBase:i,encrypted:!0}}function At(e){return Er(e).encrypted}function un(e,t=Pr){const r=`${t.replace(/\/$/,"")}/${e}`;return{twinBase:r,binBase:r,encrypted:!0}}function Vi(e,t){return(e??t)?.trim()||void 0}function Wi(e){cn=Er(e);for(const t of ln)t()}function wa(e,t){const r=typeof globalThis.location<"u"?globalThis.location.href:void 0;if(!r)return Er(e);const n=i=>{try{return new URL(i,r).href.replace(/\/$/,"")}catch{return i}};return Er({twinBase:n(e.twinBase),binBase:n(e.binBase),encrypted:e.encrypted})}function Rt(){if(!cn)throw new Error("Twin assets not configured; call setActiveTwinAssets first");return cn}function ji(e){return ln.add(e),()=>ln.delete(e)}function tr(){const e=Rt();return At(e)?`${e.binBase}/sil.bin`:`${e.twinBase}/sil.png`}function ya(){const e=Rt();return At(e)?`${e.binBase}/idle.bin`:`${e.twinBase}/idle.mp4`}function Hi(){const e=Rt();return At(e)?e.binBase:e.twinBase}function $t(){return At(Rt())}function $i(){const e=Rt();return At(e)?`${e.binBase}/atlas.bin`:`${e.twinBase}/atlas.json`}function zi(){const e=Rt();return At(e)?`${e.binBase}/expression_atlas.bin`:`${e.twinBase}/expression_atlas.json`}async function yt(e,t){const r=await fetch(e);if(!r.ok)throw new Error(`Failed to load encrypted asset: ${e}`);const n=await r.arrayBuffer();return ga(n,t)}async function Gi(e,t){if(!t)throw new Error("Missing asset key for encrypted JSON");const r=await yt(e,t),n=new TextDecoder().decode(r);return JSON.parse(n)}async function va(e){const t=new Blob([e],{type:"image/webp"});return createImageBitmap(t)}async function _a(e){const t=new Blob([e],{type:"image/webp"}),r=URL.createObjectURL(t);return new Promise((n,i)=>{const s=new Image;s.decoding="async",s.onload=()=>{URL.revokeObjectURL(r),n(s)},s.onerror=()=>{URL.revokeObjectURL(r),i(new Error("Failed to decode decrypted image"))},s.src=r})}async function ba(e){const t=new Blob([e],{type:"image/png"});return createImageBitmap(t)}async function Ki(e){const t=new Blob([e],{type:"image/png"}),r=URL.createObjectURL(t);return new Promise((n,i)=>{const s=new Image;s.decoding="async",s.onload=()=>{URL.revokeObjectURL(r),n(s)},s.onerror=()=>{URL.revokeObjectURL(r),i(new Error("Failed to decode decrypted PNG"))},s.src=r})}function qi(e){const t=new Blob([e],{type:"video/mp4"});return URL.createObjectURL(t)}async function Sa(e){const t=ya();if(!$t())return t;if(!e)throw new Error("Missing asset key for encrypted idle video");const r=await yt(t,e);return qi(r)}const sr=["open_palm","emphasis","thumbs_up","friendly_wave","point_camera"],Ta="ges",ka="m.json",xr={idle:"G_001",open_palm:"G_002",emphasis:"G_003",thumbs_up:"G_004",friendly_wave:"G_005",point_camera:"G_006"},Yi=new Set(sr),Qi={};for(const e of sr){const t=xr[e];t&&(Qi[t]=e)}function Ea(e){return!!e&&Yi.has(e)}function Nt(e){return e?Yi.has(e)?e:Qi[e]??null:null}function Xi(e,t=Pr){return`${t.replace(/\/$/,"")}/${e}/${Ta}`}function Ji(e){return`${e.replace(/\/$/,"")}/${ka}`}function Zi(e,t){const r=xr[t]??t;return`${e.replace(/\/$/,"")}/${r}.bin`}async function xa(e){const t=await fetch(Ji(e));if(!t.ok)throw new Error(`Failed to load full-body crop meta (${t.status})`);return await t.json()}async function ei(e,t,r){const n=await yt(Zi(e,t),r);return qi(n)}function Ia(e){const t=Math.min(1,Math.max(0,e));return t*t*t*(t*(t*6-15)+10)}const Aa=u.forwardRef(function({gesturesBase:t,keyHex:r,status:n,activePose:i=null,poseSynced:s=!1,style:o},a){const f=u.useRef(null),h=u.useRef(null),l=u.useRef(null),c=u.useRef(null),p=u.useRef(null),y=u.useRef(null),E=u.useRef(null),g=u.useRef({}),M=u.useRef(null),W=u.useRef(null),B=u.useRef([]),_=u.useRef(null),x=u.useRef(!1),N=u.useRef(!1),j=u.useRef(!1),G=u.useRef(!1),ie=u.useRef([]),P=u.useRef(n),V=u.useRef(0),Z=u.useRef(0);P.current=n;const Q=I=>{const b=g.current[I];b&&(f.current?.pause(),j.current=!1,x.current=!0,W.current=I,N.current=B.current.length>0,se(b),ne(!0),S(!1),$(d=>d+1))},ue=()=>{if(x.current)return;j.current=!1;const I=f.current;I&&(I.currentTime=0,I.play().catch(()=>{}),S(!0))};u.useImperativeHandle(a,()=>({waitForIdleCycleEnd:()=>{const I=f.current;if(!I||!Number.isFinite(I.duration)||I.duration<=0)return{promise:Promise.resolve(),cancel:()=>{}};if(I.ended||j.current)return j.current=!0,I.pause(),{promise:Promise.resolve(),cancel:()=>{}};let b;return{promise:new Promise(m=>{b={resolve:m,cancelled:!1},ie.current.push(b)}),cancel:()=>{b.cancelled=!0,ie.current=ie.current.filter(m=>m!==b)}}},resumeIdleLoop:()=>{ie.current=[],j.current&&ue()}}));const[ae,Re]=u.useState(!1),[ke,ne]=u.useState(!1),[ze,S]=u.useState(!0),[ee,$]=u.useState(0),[H,de]=u.useState(null),[X,se]=u.useState(null),[me,he]=u.useState({topFrac:.41,heightFrac:.59}),K=u.useCallback(()=>{const I=f.current,b=h.current;if(!I||!b)return;const d=I.videoWidth,m=I.videoHeight;if(d<1||m<1)return;(b.width!==d||b.height!==m)&&(b.width=d,b.height=m);const k=b.getContext("2d");k&&k.drawImage(I,0,0,d,m)},[]),re=u.useCallback(()=>{const I=l.current,b=c.current,d=M.current;if(!I||!b||!d)return;const m=I.videoWidth,k=I.videoHeight;if(m<1||k<1)return;(b.width!==m||b.height!==k)&&(b.width=m,b.height=k);const O=b.getContext("2d",{willReadFrequently:!0});if(!O)return;O.drawImage(I,0,0,m,k);const F=d.y_end,te=d.silHeight,C=d.seamLockPx??56,J=Math.max(1,te-F),T=y.current;if(!T||!T.complete||T.naturalWidth<1||T.naturalHeight<=F)return;const q=Math.max(8,Math.round(C*(k/Math.max(1,J)))),Ee=Math.min(C,T.naturalHeight-F);if(Ee<1||q<1)return;let ye=p.current;ye||(ye=document.createElement("canvas"),p.current=ye),(ye.width!==m||ye.height!==q)&&(ye.width=m,ye.height=q);const De=ye.getContext("2d",{willReadFrequently:!0});if(!De)return;De.clearRect(0,0,m,q),De.drawImage(T,0,F,T.naturalWidth,Ee,0,0,m,q);const Se=O.getImageData(0,0,m,q),ve=De.getImageData(0,0,m,q),w=Se.data,D=ve.data,oe=Math.max(1,q-1);for(let fe=0;fe<q;fe++){const we=Ia(fe/oe),ge=1-we,Me=we,Ge=fe*m*4;for(let Ne=0;Ne<m;Ne++){const Ke=Ge+Ne*4;w[Ke]=D[Ke]*ge+w[Ke]*Me,w[Ke+1]=D[Ke+1]*ge+w[Ke+1]*Me,w[Ke+2]=D[Ke+2]*ge+w[Ke+2]*Me}}O.putImageData(Se,0,0)},[]);return u.useEffect(()=>{let I=!1;const b=[];return(async()=>{try{const d=await xa(t);if(I)return;M.current=d;const m=Math.max(1,d.silHeight),k=Math.max(0,Math.min(d.y_end,m-1));if(he({topFrac:k/m,heightFrac:1-k/m}),$t()){const C=await yt(tr(),r),J=await Ki(C);if(I)return;y.current=J}const O=await ei(t,"idle",r);if(b.push(O),I){URL.revokeObjectURL(O);return}E.current=O,de(O);const F={};for(const C of sr){const J=await ei(t,C,r);if(b.push(J),I){URL.revokeObjectURL(J);return}F[C]=J}g.current=F;const te=F.open_palm??Object.values(F)[0];te&&se(te),Re(!0)}catch{I||Re(!1)}})(),()=>{I=!0;for(const d of b)URL.revokeObjectURL(d);E.current=null,g.current={}}},[t,r]),u.useEffect(()=>{const I=f.current,b=h.current;if(!ae||!I||!b||!H)return;const d=()=>{x.current||(I.currentTime=0,I.play().catch(()=>{}))},m=()=>{I.play().catch(()=>{})},k=()=>{const F=B.current[0];if(N.current&&P.current==="speaking"&&F&&!x.current){if(!g.current[F]){d();return}B.current.shift(),Q(F);return}const te=ie.current.filter(C=>!C.cancelled);if(te.length>0&&!x.current){ie.current=[],j.current=!0,I.pause();for(const C of te)C.resolve();return}if(P.current==="speaking"){j.current=!0,I.pause();return}d()};I.addEventListener("loadedmetadata",m),I.addEventListener("ended",k),I.readyState>=1&&m();const O=()=>{K(),V.current=requestAnimationFrame(O)};return V.current=requestAnimationFrame(O),()=>{I.removeEventListener("loadedmetadata",m),I.removeEventListener("ended",k),cancelAnimationFrame(V.current)}},[ae,H,K]),u.useEffect(()=>{if(!ae)return;if(!(n==="speaking")){const d=G.current;if(G.current=!1,B.current=[],_.current=null,N.current=!1,!x.current)if(ne(!1),d)ue();else{S(!0);const m=f.current;m?.paused&&!j.current&&m.play().catch(()=>{})}return}if(G.current=!0,!s)return;const b=Nt(i);if(b&&b!==_.current&&b!==W.current&&!B.current.includes(b)&&(B.current.push(b),_.current=b),B.current.length>0&&!x.current){const d=B.current.shift();d&&Q(d)}},[n,ae,i,s]),u.useEffect(()=>{if(!ke||!X||ee===0)return;const I=l.current;if(!I)return;I.src=X,I.currentTime=0,I.play().catch(()=>{if(x.current=!1,W.current=null,P.current==="speaking")return;ne(!1),S(!0);const m=f.current;m&&(m.currentTime=0,m.play().catch(()=>{}))});const b=()=>{re(),Z.current=requestAnimationFrame(b)};Z.current=requestAnimationFrame(b);const d=()=>{if(x.current=!1,W.current=null,P.current==="speaking"){const k=B.current.shift();if(k){Q(k);return}I.pause();return}ne(!1),S(!0),B.current=[],_.current=null,N.current=!1;const m=f.current;m&&(m.currentTime=0,m.play().catch(()=>{}))};return I.addEventListener("ended",d),()=>{cancelAnimationFrame(Z.current),I.removeEventListener("ended",d)}},[ke,X,ee,re]),H?R.jsxs("div",{"aria-hidden":!0,style:{position:"absolute",inset:0,pointerEvents:"none",...o},children:[R.jsx("video",{ref:f,src:H,muted:!0,playsInline:!0,preload:"auto",style:{position:"absolute",width:1,height:1,opacity:0,overflow:"hidden"}}),R.jsx("canvas",{ref:h,style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",zIndex:1,opacity:ze?1:0,transition:"opacity 650ms ease"}}),X?R.jsxs(R.Fragment,{children:[R.jsx("video",{ref:l,muted:!0,playsInline:!0,preload:"auto",style:{position:"absolute",width:1,height:1,opacity:0,overflow:"hidden"}}),R.jsx("canvas",{ref:c,style:{position:"absolute",left:0,width:"100%",top:`${me.topFrac*100}%`,height:`${me.heightFrac*100}%`,objectFit:"fill",zIndex:2,opacity:ke?1:0,transition:"opacity 280ms ease-in-out"}})]}):null]}):null}),xt=[{code:"en",label:"English",visemetts:!0,cartesia:!0},{code:"es",label:"Spanish",visemetts:!0,cartesia:!0},{code:"es-MX",label:"Spanish (Mexico)",visemetts:!0,cartesia:!0},{code:"es-ES",label:"Spanish (Spain)",visemetts:!0,cartesia:!0},{code:"pt",label:"Portuguese",visemetts:!0,cartesia:!0},{code:"pt-BR",label:"Portuguese (Brazil)",visemetts:!0,cartesia:!0},{code:"pt-PT",label:"Portuguese (Portugal)",visemetts:!0,cartesia:!0},{code:"fr",label:"French",visemetts:!0,cartesia:!0},{code:"de",label:"German",visemetts:!0,cartesia:!0},{code:"it",label:"Italian",visemetts:!0,cartesia:!0},{code:"zh",label:"Chinese",visemetts:!0,cartesia:!0},{code:"ja",label:"Japanese",visemetts:!0,cartesia:!0},{code:"hi",label:"Hindi",visemetts:!0,cartesia:!0},{code:"ko",label:"Korean",visemetts:!0,cartesia:!0},{code:"ru",label:"Russian",visemetts:!0,cartesia:!0},{code:"tr",label:"Turkish",visemetts:!0,cartesia:!0},{code:"id",label:"Indonesian",visemetts:!0,cartesia:!0},{code:"ar",label:"Arabic",visemetts:!0,cartesia:!0},{code:"ar-EG",label:"Arabic (Egypt)",visemetts:!0,cartesia:!0},{code:"ar-AE",label:"Arabic (UAE)",visemetts:!0,cartesia:!0},{code:"vi",label:"Vietnamese",visemetts:!0,cartesia:!0},{code:"bn",label:"Bengali",visemetts:!0,cartesia:!0},{code:"auto",label:"Auto-detect",visemetts:!0,cartesia:!1},{code:"nl",label:"Dutch",visemetts:!1,cartesia:!0},{code:"pl",label:"Polish",visemetts:!1,cartesia:!0},{code:"sv",label:"Swedish",visemetts:!1,cartesia:!0},{code:"tl",label:"Tagalog",visemetts:!1,cartesia:!0},{code:"bg",label:"Bulgarian",visemetts:!1,cartesia:!0},{code:"ro",label:"Romanian",visemetts:!1,cartesia:!0},{code:"cs",label:"Czech",visemetts:!1,cartesia:!0},{code:"el",label:"Greek",visemetts:!1,cartesia:!0},{code:"fi",label:"Finnish",visemetts:!1,cartesia:!0},{code:"hr",label:"Croatian",visemetts:!1,cartesia:!0},{code:"ms",label:"Malay",visemetts:!1,cartesia:!0},{code:"sk",label:"Slovak",visemetts:!1,cartesia:!0},{code:"da",label:"Danish",visemetts:!1,cartesia:!0},{code:"ta",label:"Tamil",visemetts:!1,cartesia:!0},{code:"uk",label:"Ukrainian",visemetts:!1,cartesia:!0},{code:"hu",label:"Hungarian",visemetts:!1,cartesia:!0},{code:"no",label:"Norwegian",visemetts:!1,cartesia:!0},{code:"th",label:"Thai",visemetts:!1,cartesia:!0},{code:"he",label:"Hebrew",visemetts:!1,cartesia:!0},{code:"ka",label:"Georgian",visemetts:!1,cartesia:!0},{code:"te",label:"Telugu",visemetts:!1,cartesia:!0},{code:"gu",label:"Gujarati",visemetts:!1,cartesia:!0},{code:"kn",label:"Kannada",visemetts:!1,cartesia:!0},{code:"ml",label:"Malayalam",visemetts:!1,cartesia:!0},{code:"mr",label:"Marathi",visemetts:!1,cartesia:!0},{code:"pa",label:"Punjabi",visemetts:!1,cartesia:!0}],es=xt.map(e=>e.code),Ra=new Set(es),Ma=new Set(xt.filter(e=>e.visemetts).map(e=>e.code)),Pa=new Set(xt.filter(e=>e.cartesia).map(e=>e.code)),Ca="en";function ts(e){return Ra.has(e)}function Br(e){const t=e?.trim();if(t)return t}function Fa(e){return e===ft?xt.filter(t=>t.visemetts).map(t=>t.code):e===dt?xt.filter(t=>t.cartesia).map(t=>t.code):xt.filter(t=>t.visemetts&&t.cartesia).map(t=>t.code)}function Ba(e,t){const r=t.trim();return r?e===ft?Ma.has(r):e===dt?Pa.has(r):ts(r):!1}function rs(e){const t=e.split(/\r?\n/);let r="",n="";for(const s of t)s.startsWith("event:")?r=s.slice(6).trim():s.startsWith("data:")&&(n=s.slice(5).trim());if(!r)return null;let i={};if(n)try{i=JSON.parse(n)}catch{i={raw:n}}return{event:r,data:i}}const ns=["aa","CH","DD","E","FF","I","O","PP","RR","SS","TH","U","kk","nn","sil"],Da=new Map(ns.map(e=>[e.toLowerCase(),e]));function Dr(e){const t=(e??"").trim();return t?Da.get(t.toLowerCase())??"sil":"sil"}const La={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 Oa(e){if(!e)return["sil"];const t=e.toLowerCase();return La[t]??["sil"]}function is(e,t){const r=e.word.length;if(r<=0)return 0;const n=e.wduration;if(n<=0)return 0;const i=Math.max(0,Math.min(1,(t-e.wtime)/n));return Math.min(r-1,Math.floor(i*r))}function Vt(e,t){const r=Math.max(0,Math.min(e.length-1,t));return e[r]??""}function Lr(e,t){const r=e.toLowerCase().replace(/[^a-z']/g,"");return!r||Vt(r,t)!=="w"||t>0&&Vt(r,t-1)==="q"?!1:t===0&&/^w[aeiouy]/.test(r)}function Na(e,t){const r=e.toLowerCase(),n=Vt(r,t),i=r.slice(Math.max(0,t-1),t+2);return n==="i"||n==="y"?"I":i.includes("ee")||n==="e"||r.includes("ea")?"E":"aa"}function Ua(e,t){const r=e.toLowerCase(),n=r.slice(Math.max(0,t-1),Math.min(r.length,t+3));if(/oo|ou|uw/.test(n))return"U";if(Lr(r,t))return"FF";const i=Vt(r,t);return i==="u"||i==="w"?"U":"O"}function Va(e,t){const r=e.toLowerCase();if(Lr(r,t))return"FF";const n=r.slice(Math.max(0,t-2),t+1);if(/qu/.test(n))return"U";const i=r.slice(Math.max(0,t-1),Math.min(r.length,t+3));return/wo|wh/.test(i)||Vt(r,t)==="o"?"O":"U"}const _r={d:"DD",t:"DD",n:"DD",s:"SS",z:"SS",k:"kk",g:"kk",c:"CH",x:"CH",j:"CH"};function Wa(e,t){const r=e.toLowerCase(),n=Vt(r,t);if(_r[n])return _r[n];for(let i=0;i<r.length;i++){const s=r[i];if(_r[s])return _r[s]}return"DD"}function ss(e,t,r){const n=Oa(e);if(n.length===1)return n[0];const i=t.trim();if(!i)return n[0];const s=(e??"").toLowerCase(),o=Math.max(0,r);switch(s){case"aei":return Na(i,o);case"o":return Ua(i,o);case"qw":return Va(i,o);case"cdgknstxyz":return Wa(i,o);default:return n[0]}}const kn=16,dn=47,as=new Set(["aa","E","I"]),os=new Set(["DD","SS","kk","CH"]),ja=[as,os];function Ha(e){for(const t of ja)if(t.has(e))return t;return null}function $a(e){return Ha(e)!=null}function cs(e,t=kn){return t<=0?e:Math.round(e/t)*t}function En(e,t=kn){return e.map(r=>({...r,vtime:cs(r.vtime,t)}))}function ls(e){const t=new Map;for(const r of e)t.has(r.vtime)||t.set(r.vtime,r);return[...t.values()].sort((r,n)=>r.vtime-n.vtime)}function xn(e){if(e.length<=2)return[...e];const t=[e[0]];for(let r=1;r<e.length-1;r++){const n=e[r],i=e[r+1],s=t[t.length-1];if(!$a(n.viseme)){t.push(n);continue}const o=n.vtime-s.vtime,a=i.vtime-n.vtime;o<dn||a<dn||t.push(n)}return t.push(e[e.length-1]),t}function Or(e){return xn(ls(En(e)))}function us(e,t){let r="sil";for(const n of e){if(n.vtime>t)break;n.viseme!=="sil"&&(r=n.viseme)}return r}function Nr(e){const t=ls(En(e)),r=xn(t),n=new Set(r.map(s=>s.vtime)),i=[];for(const s of t)n.has(s.vtime)||i.push({viseme:s.viseme,vtime:s.vtime});return i}function za(e){return Nr(e).map(t=>t.viseme)}const Ga=32,ti=48;function ds(e){let t=0;for(const r of e)t=Math.max(t,r.vtime+r.vduration);return t}function fs(e){let t=null,r=-1;for(const n of e){if(n.viseme==="sil")continue;const i=n.vtime+n.vduration;i>r&&(t=n,r=i)}return t}function Ka(e){return Or(e).find(r=>r.viseme!=="sil")??null}function Tt(e){const t=ds(e);return fs(e)?t+yn:t}function qa(e){const t=[],r=Ka(e);r&&r.vtime>0&&t.push({from:"sil",to:r.viseme,fromVtime:0,toVtime:r.vtime});const n=fs(e),i=ds(e);return n&&t.push({from:n.viseme,to:"sil",fromVtime:i,toVtime:i+yn}),t}function ms(e){const t=Or(e),r=[];for(let n=0;n<t.length-1;n++){const i=t[n].viseme,s=t[n+1].viseme,o=t[n].vtime,a=t[n+1].vtime;i===s||a<=o||r.push({from:i,to:s,fromVtime:o,toVtime:a})}return r}function hs(e){return e.length===0?[]:[...qa(e),...ms(e)]}function Ya(e,t,r=!1){let n=null;for(const i of e){const{transStart:s,transEnd:o}=ps(i.fromVtime,i.toVtime,i.from,i.to,r);t>=s&&t<o&&(n=i)}return n}function ps(e,t,r,n,i=!1){const s=Math.max(0,t-e);if(i&&(r==="PP"||n==="PP")&&s>ti){const l=ti,c=t,p=c-l;return{gapMs:s,effectiveGapMs:l,holdEnd:p,transStart:p,transEnd:c}}const a=s>0?Math.max(s,Ga):0,f=e,h=e+a;return{gapMs:s,effectiveGapMs:a,holdEnd:e,transStart:f,transEnd:h}}function gs(e,t,r,n,i,s){n.forEach(o=>{const f=String(o.word??"").trim();if(!f)return;const h=Math.round((o.start??0)*1e3),l=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:f,wtime:i+h,wduration:l,queueIndex:t.length,gesture:o.gesture??null,emphasis:o.emphasis===!0})}),r.forEach(o=>{const a=String(o.symbol??o.viseme??"").trim();if(!a)return;const f=Math.round((o.start??0)*1e3),h=Math.max(1,Math.round((o.duration??0)*1e3)),l=i+f,c=vs(t,l),p=c?is(c,l):0;let y;Di(s)==="oculus_direct"?(y=Dr(a),y==="U"&&c&&Lr(c.word,p)&&(y="FF")):y=ss(a,c?.word??"",p),e.push({viseme:y,weight:1,vtime:l,vduration:h})})}function ws(e,t){let r=t;for(const n of e){const i=Math.round((n.start??0)*1e3),s=Math.max(1,Math.round((n.duration??0)*1e3));r=Math.max(r,t+i+s)}return r}const In=16e3;function ys(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:In}function Qa(e){let t=e.trim();const r=t.indexOf(",");t.startsWith("data:")&&r>=0&&(t=t.slice(r+1)),t=t.replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/");const n=t.length%4;return n!==0&&(t+="=".repeat(4-n)),t}function Xa(e){return e.length>=4&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70}function ri(e,t,r=In){const n=t.byteOffset%2===0?t:t.slice(),i=new Int16Array(n.buffer,n.byteOffset,n.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,r);return o.copyToChannel(s,0),o}function Ja(e){const t=Qa(e),r=window.atob(t),n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r.charCodeAt(i);return n}async function ni(e,t,r=In){const n=Ja(t),i=ys(r);if(Xa(n)){const s=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);return e.decodeAudioData(s)}if(n.length>=2&&n.length%2===0)return ri(e,n,i);try{const s=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength);return await e.decodeAudioData(s)}catch{return ri(e,n,i)}}function vs(e,t){for(const r of e)if(t>=r.wtime&&t<r.wtime+r.wduration)return r;return null}function _s(e,t){const r=[],n=[];let i=null,s=!1,o=!1,a=!1,f=!1,h=0,l=0,c=0,p=null,y=1,E=t,g=!1,M=null,W=null,B=!1,_=0,x=!1,N=!1,j=0,G=null,ie=null,P=null,V=null,Z=null;const Q=()=>({visemes:[],words:[],segmentOffsetMs:0}),ue=()=>{N=!1,j=0},ae=()=>{const d=ie;G=null,ie=null,d?.(),!g&&!s&&n.length===0&&r.length>0&&P&&V&&K(P,V)},Re=()=>{G||(G=new Promise(d=>{ie=d}))},ke=()=>{p!=null&&(clearTimeout(p),p=null)},ne=()=>{for(const d of n){try{d.onended=null,d.stop(0)}catch{}try{d.disconnect()}catch{}}n.length=0},ze=()=>{for(const d of n)d.playbackRate.value=y},S=()=>{if(!(g||!f||s||N||n.length>0||r.length>0)){if(a&&i&&l>0){const d=(i.currentTime-l)*1e3;if(d<_){ke();const m=y>0?(_-d)/y:_-d;p=setTimeout(()=>{g||(o=!1,p=null,e.onSpeakingDone(),e.onNotify())},Math.max(0,m));return}}o=!1,ke(),e.onSpeakingDone(),e.onNotify()}},ee=d=>{const m=Tt(d);if(m<=0){e.onSpeakingDone(),e.onNotify();return}o=!0,h=performance.now(),e.onSpeakingStart(),e.onNotify(),ke();const k=y>0?m/y:m;p=setTimeout(()=>{g||(o=!1,p=null,e.onSpeakingDone(),e.onNotify())},k)},$=(d,m,k,O)=>{m.length!==0&&(c=k,m.forEach(F=>{const C=String(F.word??"").trim();if(!C)return;const J=Math.round((F.start??0)*1e3),T=F.duration!=null?Math.round(F.duration*1e3):F.end!=null?Math.max(1,Math.round((F.end-(F.start??0))*1e3)):0;d.push({word:C,wtime:c+J,wduration:T,queueIndex:d.length,gesture:F.gesture??null,emphasis:F.emphasis===!0})}))},H=(d,m,k,O,F,te)=>{k.length!==0&&(c=O,k.forEach(C=>{const J=String(C.symbol??C.viseme??"").trim();if(!J)return;const T=Math.round((C.start??0)*1e3),q=Math.max(1,Math.round((C.duration??0)*1e3)),Ee=c+T,ye=vs(m,Ee),De=ye?is(ye,Ee):0;let Se;Di(te)==="oculus_direct"?(Se=Dr(J),Se==="U"&&ye&&Lr(ye.word,De)&&(Se="FF")):Se=ss(J,ye?.word??"",De),d.push({viseme:Se,weight:1,vtime:Ee,vduration:q})}),e.onNotify())},de=(d,m,k,O,F,te,C)=>{$(m,O,F),H(d,m,k,F,te,C)},X=(d,m,k)=>{Z===d&&d.visemes===m||(m.length=0,k.length=0,d.visemes=m,d.words=k,d.segmentOffsetMs=0,Z=d,c=0,_=0)},se=d=>(W||(W=d.createGain(),W.gain.value=B?0:1,W.connect(d.destination)),W),me=async()=>{const d=window.AudioContext||window.webkitAudioContext;return i||(i=new d,W=null,M=null),i.state==="suspended"&&await i.resume(),se(i),M||(M=i.createMediaStreamDestination()),i},he=(d,m)=>{if(!i)return 0;const k=i,O=k.currentTime,F=O+.02;if(m.isFirstAudio){l<=0&&(l=F);const C=(F-O)*1e3;h=performance.now()+C}m.onBeforeStart?.(F);const te=k.createBufferSource();return te.buffer=d,te.playbackRate.value=y,te.connect(se(k)),M&&te.connect(M),n.push(te),g?(n.pop(),F):(m.isFirstAudio&&(o=!0,e.onSpeakingStart()),te.onended=()=>{const C=n.indexOf(te);C>=0&&n.splice(C,1),e.onNotify(),!g&&(P&&V?K(P,V):S())},te.start(F),F)},K=async(d,m)=>{if(g||s||n.length>0)return;if(r.length===0){S();return}s=!0;let k=!1;try{if(G&&await G,g)return;const O=await me();if(g)return;const F=r[0];if(!F)return;const te=!o;if(x&&(e.shouldHoldForWarmup?.()??!1)&&(N||te&&F.newStream)||N){X(F.utterance,d,m);for(const T of r){if(g)return;T.audioBuffer||(T.audioBuffer=await ni(O,T.audio,T.sampleRate)),a=!0,N||(N=!0,j=0,T.newStream&&T.onNewStream?.()),T.visemesQueued||(de(d,m,T.visemes,T.words,j,!0,E),T.visemesQueued=!0,j+=Math.round(T.audioBuffer.duration*1e3),_=Math.max(_,Tt(d)))}e.onNotify();return}const J=r.shift();if(!J||(J.audioBuffer||(J.audioBuffer=await ni(O,J.audio,J.sampleRate)),g))return;a=!0,ke(),X(J.utterance,d,m),J.visemesQueued=!1,J.newStream&&J.onNewStream?.(),he(J.audioBuffer,{isFirstAudio:!o,isFirstOfStream:!1,onBeforeStart:T=>{l=T,c=0,h=performance.now()+(T-O.currentTime)*1e3,d.length=0,m.length=0,de(d,m,J.visemes,J.words,0,!0,E),J.visemesQueued=!0,J.utterance.segmentOffsetMs=0}}),k=n.length>0,_=Tt(d),e.onNotify()}catch(O){console.error("[avatarChunkPlayback] audio chunk failed:",O)}finally{if(s=!1,g)return;if(N){r.some(F=>!F.audioBuffer||!F.visemesQueued)&&K(d,m);return}!k&&n.length===0&&r.length>0?K(d,m):n.length===0&&r.length===0&&S()}};return{setStreamTtsEngineId:d=>{E=d},setPlaybackSpeed:d=>{y=Math.max(.1,Math.min(1,d)),ze()},getPlaybackSpeed:()=>y,setMuted:d=>{B=d,W&&(W.gain.value=d?0:1)},isMuted:()=>B,setLipsyncWarmupHoldEnabled:d=>{x=d,d||ue()},isWarmingUp:()=>N,releaseWarmupHold:()=>{if(N){N=!1,j=0;for(const d of r)d.newStream=!1;P&&V&&K(P,V),e.onNotify()}},resetForNewStream:d=>{g=!1,f=!1,E=d,_=0},resumeBotStream:()=>{g=!1,f=!1},clearAborted:()=>{g=!1},primeAudioContext:async()=>{const d=window.AudioContext||window.webkitAudioContext;i||(i=new d,W=null,M=null),i.state==="suspended"&&await i.resume(),se(i),M||(M=i.createMediaStreamDestination())},armStartHold:Re,releaseStartHold:ae,stop:()=>{g=!0,ae(),ke(),ne(),r.length=0,s=!1,o=!1,a=!1,f=!1,c=0,l=0,h=0,_=0,P=null,V=null,Z=null,ue()},markStreamComplete:d=>{if(_=Math.max(_,Tt(d)),f=!0,!a&&d.length>0){ee(d);return}S()},playAudioChunk:async(d,m,k,O,F,te,C)=>{if(g)return;P=d,V=m;const J=ys(C?.sampleRate),T=C?.newStream===!0,q=Q();if(!k?.trim()){if(O.length===0&&F.length===0)return;X(q,d,m),T&&C?.onNewStream?.(),de(d,m,O,F,0,!0,E),_=Tt(d),!o&&_>0&&ee(d),e.onNotify();return}r.push({audio:k,audioBuffer:null,utterance:q,visemes:O,words:F,isNewSegment:te,sampleRate:J,newStream:T,onNewStream:C?.onNewStream,visemesQueued:!1}),await K(d,m)},queueTimingsOnly:(d,m,k,O,F,te)=>{if(g)return;const C=Q();X(C,d,m),de(d,m,k,O,0,!0,E),C.segmentOffsetMs=0,_=Tt(d)},getPlaybackElapsedMs:()=>a&&i&&l>0?Math.max(0,(i.currentTime-l)*1e3*y):o?Math.max(0,(performance.now()-h)*y):0,isSpeaking:()=>o?!0:!a||!i||l<=0?!1:(i.currentTime-l)*1e3<_,getVoiceStream:()=>M?M.stream:null,getPlaybackStartPerf:()=>h,bargeIn:()=>{g=!0,ae(),f=!1,ke(),ne(),r.length=0,s=!1,o=!1,a=!1,c=0,l=0,h=0,_=0,P=null,V=null,Z=null,ue()},interrupt:()=>{g=!0,ae(),f=!1,ke(),ne(),r.length=0,s=!1,o=!1,a=!1,c=0,l=0,h=0,_=0,P=null,V=null,Z=null,ue()}}}function ar(e,t){let r=null;for(const n of e)t<n.vtime||t>=n.vtime+n.vduration||(!r||n.vtime>=r.vtime)&&(r=n);return r?r.viseme:"sil"}function bs(e,t,r=120){const n=ar(e,t);if(n!=="sil")return n;let i=null;for(const s of e){if(s.vtime>t)break;const o=s.vtime+s.vduration;o<=t&&t-o<=r&&(i=s)}return i?.viseme??"sil"}function Za(e,t,r=400){const n=t-r;let i=0;for(const s of e)if(s.vtime+s.vduration<n)i+=1;else break;i>0&&e.splice(0,i)}function Ss(e,t){for(const r of e)if(t>=r.wtime&&t<r.wtime+r.wduration)return r;return null}function ii(e,t,r){const n=Ss(e,t);if(n?.gesture&&r(n.gesture))return n.gesture;for(const i of e)if(i.wtime>=t&&i.gesture&&r(i.gesture))return i.gesture;for(const i of e)if(i.gesture&&r(i.gesture))return i.gesture;return null}function si(e,t){const r=e.trim();if(!r)return null;try{const n=r.replace(/\s+/g,""),i=atob(n).length,s=Number.isFinite(t)&&(t??0)>0?Number(t):16e3;return i/2/s*1e3}catch{return null}}const Ur=.5,Vr=1.5,An="Olivia",Rn="f786b574-daa5-4673-aa0c-cbe3e8534c02",or=.85;function fn(e,t=ut,r={}){const n=`${t.replace(/\/$/,"")}/avatar_ttsWithPoses`,i=[],s=[],o=[],a=[];let f=0;const h=[],l=[];let c="",p="neutral",y="",E=Et,g=!!r.fullBody;const M=new Set;let W=0,B=null,_=0,x=null;const N=()=>M.forEach(S=>S());let j=()=>!1;const G=_s({onSpeakingStart:()=>e("speaking"),onSpeakingDone:()=>e("done"),onNotify:N,shouldHoldForWarmup:()=>j()},Et),ie=()=>G.getPlaybackElapsedMs(),P=(S,ee=c)=>{if(!r.onLipsyncDebug)return;const $=ie(),H=i,de=Nr(o).map(X=>({viseme:X.viseme,vtimeMs:X.vtime}));r.onLipsyncDebug({event:S,spokenText:ee,mood:p,playbackAnchorPerf:G.getPlaybackStartPerf(),playbackElapsedMs:$,queueLength:H.length,activeViseme:ar(H,$),segments:l.map(X=>({...X,visemes:[...X.visemes]})),fullQueueLength:o.length,compactionSkipped:de})},V=(S,ee)=>{r.onLipsyncDebug&&(B={event:S,spokenText:ee},W===0&&(W=requestAnimationFrame(()=>{W=0;const $=B;B=null,$&&P($.event,$.spokenText)})))},Z=(S,ee,$,H,de)=>{if(!r.onLipsyncDebug)return;const X=i.slice(ee),se=$.filter(me=>String(me.symbol??me.viseme??"").trim());l.push({spokenText:S,audioOffsetMs:X[0]?.vtime??0,isNewSegment:H,chunkDurationMs:de,receivedAtMs:performance.now(),visemes:X.map((me,he)=>{const K=se[he];return{rawSymbol:String(K?.symbol??K?.viseme??me.viseme).trim(),viseme:me.viseme,startSec:Number(K?.start??0),durationSec:Number(K?.duration??0),vtimeMs:me.vtime,vdurationMs:me.vduration}})})},Q=()=>{o.length=0,a.length=0,f=0},ue=(S,ee,$,H,de)=>{if(S.length===0&&ee.length===0)return;gs(o,a,S,ee,f,de);const X=ws(S,f),se=$?si($,H):null;f=Math.max(X,se!=null?f+se:f)},ae=()=>{_+=1,x?.abort(),x=null,G.stop(),i.length=0,s.length=0,Q(),h.length=0,p="neutral",l.length=0,c="",e("idle"),V("reset"),N()},Re=S=>{const ee=lt(S?.ttsEngineId,S?.voiceId),$=ee.ttsEngineId??E??Et,H=ee.voiceId??($===ft?Fr:An),de=S?.speakingRate??or,X=Math.max(Ur,Math.min(Vr,de));return{engineId:$,voiceId:H,speakingRate:X,language:Br(S?.language)}},ke=async S=>{ae();const ee=_;x=new AbortController,e("loading"),c=S.debugSpokenFallback,l.length=0,Q();const $=y.trim();if(!$)throw new Error("Developer token required for avatar_ttsWithPoses");G.resetForNewStream(S.engineId),G.setStreamTtsEngineId(S.engineId),S.delayPlayback&&G.armStartHold();let H="",de="";try{const X=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$}`,Accept:"text/event-stream"},body:JSON.stringify(S.requestBody),signal:x.signal});if(!X.ok)throw new Error(`avatar_ttsWithPoses failed (${X.status})`);const se=X.body;if(!se)throw new Error("No response body");const me=se.getReader(),he=new TextDecoder;let K="",re=!0;const I=()=>H||S.debugSpokenFallback,b=async d=>{if(ee!==_)return;const m=rs(d);if(m){if(m.event==="spokenText"){const k=typeof m.data.text=="string"?m.data.text.trim():"";k&&(H=k,c=k,S.onSpokenText?.(k),N());return}if(m.event==="displayText"){const k=typeof m.data.text=="string"?m.data.text.trim():"";k&&(de=k,S.onDisplayText?.(k),N());return}if(m.event!=="done"){if(m.event==="audio"){const k=m.data.chunk,O=m.data.visemes??[],F=m.data.words??[],te=m.data.is_new_segment??!1,C=m.data.sample_rate,J=Number(m.data.audio_offset_ms??0),T=i.length,q=I();if(ue(O,F,k,C,S.engineId),k){const Ee=re;re=!1,await G.playAudioChunk(i,s,k,O,F,te,{sampleRate:C,newStream:Ee,audioOffsetMs:J}),Z(q,T,O,te,si(k,C)),V("audio_chunk",q)}else(O.length>0||F.length>0)&&(G.queueTimingsOnly(i,s,O,F,te,{audioOffsetMs:J,newStream:re}),Z(q,T,O,te,null),V("audio_chunk",q))}else if(m.event==="metadata"){const k=m.data.mood;typeof k=="string"&&k.trim()&&(p=k.trim());const O=m.data.spoken_text??m.data.text;typeof O=="string"&&O.trim()&&!H&&(H=O.trim(),c=H);const F=m.data.sentence_emotions;if(Array.isArray(F)){h.length=0;for(const te of F){if(!te||typeof te!="object")continue;const C=te;h.push({sentence_index:Number(C.sentence_index??0),text:String(C.text??""),sentiment:typeof C.sentiment=="string"?C.sentiment:void 0,emotion:String(C.emotion??p),start_word:Number(C.start_word??0),end_word:Number(C.end_word??0)})}}N(),V("metadata",I())}else if(m.event==="error")throw new Error(String(m.data.message??"avatar_ttsWithPoses stream error"))}}};for(;;){if(ee!==_)return{displayText:de,spokenText:H,aborted:!0};const{done:d,value:m}=await me.read();m&&(K+=he.decode(m,{stream:!0}));const k=K.split(`
2
2
 
3
- `);ae=x.pop()??"";for(const A of x)await W(A);if(b){ae.trim()&&await W(ae.trim()),L.markStreamComplete(i),P("bot_stopped",B());break}}}catch(Y){if(S!==O)return{displayText:ce,spokenText:X,aborted:!0};if(Y instanceof DOMException&&Y.name==="AbortError")return{displayText:ce,spokenText:X,aborted:!0};throw console.error("[avatarTtsLipsync]",Y),oe(),e("error"),Y}return{displayText:ce,spokenText:X}};return{setDeveloperToken:D=>{w=D},setTtsEngineId:D=>{T=D},getTtsEngineId:()=>T,speak:async(D,S)=>{const{engineId:J,voiceId:X,speakingRate:ce,language:Y}=ue(S),z={user_query:D,ttsEngineId:J,speakingRate:ce,tenant:"aiTwin"};$n.has(J)&&(z.voice_id=X),Y&&(z.language=Y),await Se({requestBody:z,engineId:J,debugSpokenFallback:D})},speakWithReply:async(D,S)=>{const J=D.trim();if(!J)throw new Error("Message is required");const{engineId:X,voiceId:ce,speakingRate:Y,language:z}=ue(S),$={generateReply:!0,message:J,ttsEngineId:X,speakingRate:Y,tenant:"aiTwin",history:S?.history??[]};$n.has(X)&&($.voice_id=ce),z&&($.language=z);const ve=S?.brainId?.trim();ve&&($.brainId=ve);const ae=S?.brainUrl?.trim();ae&&($.brainUrl=ae);const _=S?.userName?.trim();_&&($.userName=_);const B=S?.userEmail?.trim();B&&($.userEmail=B);const W=S?.userContext?.trim();W&&($.userContext=W);const b=await Se({requestBody:$,engineId:X,debugSpokenFallback:J,onSpokenText:S?.onSpokenText,onDisplayText:S?.onDisplayText});if(b.aborted)return{spokenText:b.spokenText,displayText:b.displayText};if(!b.spokenText&&!b.displayText)throw new Error("avatar_ttsWithPoses generateReply stream missing spokenText or displayText");return{spokenText:b.spokenText||b.displayText,displayText:b.displayText||b.spokenText}},stop:oe,getVisemeQueue:()=>i,getWordQueue:()=>s,getFullVisemeQueue:()=>o,getFullWordQueue:()=>a,getSentenceEmotions:()=>d,getStreamMood:()=>f,getPlaybackElapsedMs:()=>L.getPlaybackElapsedMs(),isSpeaking:()=>L.isSpeaking(),isWarmingUp:()=>L.isWarmingUp(),releaseWarmupHold:()=>L.releaseWarmupHold(),setLipsyncWarmupHold:(D,S)=>{S&&(V=S),L.setLipsyncWarmupHoldEnabled(D)},getVoiceStream:()=>L.getVoiceStream(),setMuted:D=>{L.setMuted(D)},isMuted:()=>L.isMuted(),setPlaybackSpeed:D=>{L.setPlaybackSpeed(D)},getPlaybackSpeed:()=>L.getPlaybackSpeed(),subscribe:D=>(h.add(D),()=>h.delete(D))}}function Wt(e){if(e==null)return!1;if(typeof e=="object"){const r=e;if(r.type==="permissions"||r.name==="NotAllowedError"||r.name==="PermissionDeniedError")return!0}const n=(e instanceof Error?`${e.name} ${e.message}`:typeof e=="string"?e:String(e)).toLowerCase();return!!(n.includes("notallowederror")||n.includes("permissiondeniederror")||n.includes("permission denied")||n.includes("permissions denied")||n.includes("microphone access denied")||(n.includes("microphone")||n.includes(" mic"))&&(n.includes("denied")||n.includes("blocked")||n.includes("not allowed")||n.includes("permission")))}async function va(){if(typeof navigator>"u"||!navigator.permissions?.query)return!1;try{return(await navigator.permissions.query({name:"microphone"})).state==="denied"}catch{return!1}}const wr=16e3,gr=16e3;class _a extends nr.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 ba extends nr.DailyMediaManager{constructor(){super(!0,!0,void 0,void 0,512,wr,gr)}bufferBotAudio(t,n){}}const Sa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function zr(e){return Sa.test(e.trim())}function Ta(e){const t=e.replace(/\/$/,"");return t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t}function Xi(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??Pt,r=new URL(`${Ta(n)}/ws/voice`);r.searchParams.set("authToken",t),r.searchParams.set("tenant","aiTwin");const i=it(e.ttsEngineId,e.voiceId),s=i.ttsEngineId;s&&r.searchParams.set("ttsEngineId",s);const o=i.voiceId?.trim();o&&(s&&_i(s)?zr(o)||r.searchParams.set("voiceId",o):zr(o)&&r.searchParams.set("voiceId",o));const a=vn(e.language);a&&r.searchParams.set("language",a);const u=e.brainId?.trim()||e.personaId?.trim();u&&r.searchParams.set("brainId",u);const d=e.brainUrl?.trim();d&&r.searchParams.set("brainUrl",d);const l=e.speakingRate??Kt;r.searchParams.set("speaking_rate",String(Math.max(kn,Math.min(xn,l)))),e.ttsStream===!1?r.searchParams.set("tts_stream","false"):r.searchParams.set("tts_stream","true"),e.speakOnlyWhenSpokenTo&&r.searchParams.set("speakOnlyWhenSpokenTo","true");const c=e.avatarName?.trim();c&&r.searchParams.set("avatarName",c);const f=e.userName?.trim();f&&r.searchParams.set("userName",f);const w=e.userEmail?.trim();w&&r.searchParams.set("userEmail",w);const T=e.userContext?.trim();return T&&r.searchParams.set("userContext",T),r.toString()}function Un(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 ka(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 Hr(e){return e.is_new_segment===!0||Number(e.audio_offset_ms??-1)===0?!0:Number(e.chunk_index??-1)===0}function xa(e){return e?.transport?._mediaManager?._wavStreamPlayer??null}function Ji(e,t={}){const n=[],r=[],i=[],s=[];let o=0;const a=[],u=[];let d="",l="neutral",c=st,f=!1,w=null,T=null,h={...t},I=0,H=null;const O=new Set,v=[];let E=!1,V=null,L=!0,se="default";const re=new Set;let P=null,q=0,Q=!1,ee=!1,oe=null,ue=!1;const Se=()=>{oe!=null&&(clearTimeout(oe),oe=null)},We=()=>{Se(),oe=setTimeout(()=>{oe=null,L&&(S.markStreamComplete(n),z("bot_stopped"))},450)},ne=()=>O.forEach(p=>p());let D=()=>!1;const S=Yi({onSpeakingStart:()=>e("speaking"),onSpeakingDone:()=>{ue=!1,ee=!1,e("done")},onNotify:ne,shouldHoldForWarmup:()=>D()},c),J=()=>{if(V)return V;const p=new MessageChannel;return p.port1.onmessage=()=>{const C=v.shift();C!==void 0&&Ae(C),v.length>0?p.port2.postMessage(null):E=!1},V=p,p},X=p=>{v.push(p),!E&&(E=!0,J().port2.postMessage(null))},ce=()=>S.getPlaybackElapsedMs(),Y=(p,C=d)=>{if(!h.onLipsyncDebug)return;const ie=ce(),he=n,ge=Tn(i).map(Me=>({viseme:Me.viseme,vtimeMs:Me.vtime}));h.onLipsyncDebug({event:p,spokenText:C,mood:l,playbackAnchorPerf:S.getPlaybackStartPerf(),playbackElapsedMs:ie,queueLength:he.length,activeViseme:$t(he,ie),segments:u.map(Me=>({...Me,visemes:[...Me.visemes]})),fullQueueLength:i.length,compactionSkipped:ge})},z=(p,C)=>{h.onLipsyncDebug&&(H={event:p,spokenText:C},I===0&&(I=requestAnimationFrame(()=>{I=0;const ie=H;H=null,ie&&Y(ie.event,ie.spokenText)})))},$=()=>{L=!0,re.clear(),S.clearAborted()},ve=()=>{const p=xa(w);if(p){se=`bot-${Date.now()}`,p.interruptedTrackIds={[se]:!0};try{p.interrupt?.()}catch{}}const C=T;try{C?.interrupt?.()}catch{}},ae=p=>{if(ue&&S.isSpeaking())return!0;const C=p.context_id?.trim();return C&&re.has(C)?!0:L?!1:!(p.type==="avatar_metadata"||Hr(p))},_=p=>{L=!1,ue=!1;const C=p.context_id?.trim();C&&re.add(C),Se(),Q=!1,ee=!1,v.length=0,E=!1,P?.abort(),P=null,q+=1,ve(),S.bargeIn(),B(),e("idle"),z("interrupt"),ne()},B=()=>{n.length=0,r.length=0,i.length=0,s.length=0,o=0,u.length=0,d="",l="neutral",a.length=0},W=()=>{Se(),ee=!1,Q=!1,S.stop(),B(),z("reset"),ne()},b=()=>{W(),e("idle"),ne()},y=(p,C)=>{typeof p.mood=="string"&&p.mood.trim()&&(l=p.mood.trim()),Array.isArray(p.sentence_emotions)&&p.sentence_emotions.length>0&&(C&&(a.length=0),a.push(...Un(p.sentence_emotions,l)))},x=p=>{if(ae({...p,type:"avatar_metadata"}))return;$(),Q=!0;const C=String(p.spoken_text??p.text??"").trim();C&&(d=C),S.resetForNewStream(c),typeof p.mood=="string"&&p.mood.trim()&&(l=p.mood.trim()),a.length=0,a.push(...Un(p.sentence_emotions,l)),Array.isArray(p.gestures)&&p.gestures,z("metadata",C),ne()},A=(p,C,ie,he)=>{if(!h.onLipsyncDebug)return;const ge=n.slice(ie),Me=he.filter(Re=>String(Re.symbol??Re.viseme??"").trim());u.push({spokenText:C,audioOffsetMs:ge[0]?.vtime??0,isNewSegment:!!p.is_new_segment,chunkDurationMs:p.chunk_duration_ms!=null?Number(p.chunk_duration_ms):null,receivedAtMs:performance.now(),visemes:ge.map((Re,je)=>{const ze=Me[je];return{rawSymbol:String(ze?.symbol??ze?.viseme??Re.viseme).trim(),viseme:Re.viseme,startSec:Number(ze?.start??0),durationSec:Number(ze?.duration??0),vtimeMs:Re.vtime,vdurationMs:Re.vduration}})})},U=(p,C,ie,he)=>{if(p.length===0&&C.length===0)return;$i(i,s,p,C,o,c);const ge=Ki(p,o);let Me=null;const Re=ie.trim();if(Re)try{const je=atob(Re.replace(/\s+/g,"")).length,ze=Number.isFinite(he)&&(he??0)>0?Number(he):16e3;Me=je/2/ze*1e3}catch{Me=null}o=Math.max(ge,Me!=null?o+Me:o)},j=p=>{if(ae(p))return;const C=Hr(p);C&&(Se(),$());const ie=String(p.spoken_text??p.text??"").trim(),he=p.visemes??[],ge=p.words??[],Me=String(p.chunk??"").trim(),Re=Q||C||!ee;Q&&(Q=!1),Re&&(ee=!0),ie&&(d=ie),y(p,C),Re?(S.resetForNewStream(c),i.length=0,s.length=0,o=0):C&&S.resumeBotStream(),U(he,ge,Me,p.sample_rate);const je=n.length;S.playAudioChunk(n,r,Me,he,ge,C,{sampleRate:p.sample_rate,newStream:Re,audioOffsetMs:Number(p.audio_offset_ms??0),onNewStream:()=>{u.length=0}}).then(()=>{A(p,ie,je,he),z("audio_chunk",ie),We()})},Z=p=>{if(ae(p))return;(p.is_new_segment||Number(p.audio_offset_ms??-1)===0)&&$(),console.warn("[realtimeVoice] avatar_lipsync is deprecated — expect avatar_audio_chunk");const C=String(p.spoken_text??p.text??"").trim();C&&(d=C),y(p,!!p.is_new_segment),U(p.visemes??[],p.words??[],"",void 0);const ie=n.length;S.queueTimingsOnly(n,r,p.visemes??[],p.words??[],!!p.is_new_segment,{audioOffsetMs:Number(p.audio_offset_ms??0)}),A(p,C,ie,p.visemes??[]),z("lipsync",C),ne()},Te=async p=>{const C=String(p.text??"").trim();if(!C)return;const ie=h.authToken?.trim();if(!ie){console.error("[realtimeVoice] avatar_speak requires authToken");return}P?.abort();const he=new AbortController;P=he;const ge=++q;$(),S.resetForNewStream(c),d=C;const Re=`${(h.apiBase??Pt).replace(/\/$/,"")}/avatar_ttsWithPoses`,je=it(c,h.voiceId);je.ttsEngineId&&(c=je.ttsEngineId,S.setStreamTtsEngineId(c));const ze=je.voiceId?.trim()||(c===at?yn:pr),Gt=h.speakingRate??Kt,In=Math.max(kn,Math.min(xn,Gt)),mt={user_query:C,ttsEngineId:c,speakingRate:In,tenant:"aiTwin"};$n.has(c)&&(mt.voice_id=ze);const Ft=vn(h.language);Ft&&(mt.language=Ft);try{const ht=await fetch(Re,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ie}`},body:JSON.stringify(mt),signal:he.signal});if(!ht.ok)throw new Error(`avatar_ttsWithPoses failed (${ht.status})`);const qt=ht.body;if(!qt)throw new Error("No response body");const Lt=qt.getReader(),Ze=new TextDecoder;let Ve="",ct=!0;const xe=async Fe=>{if(ge!==q||he.signal.aborted||!L)return;const ke=Ci(Fe);if(ke){if(ke.event==="audio"){const De=ke.data.chunk,Le=ke.data.visemes??[],lt=ke.data.words??[],et=ke.data.is_new_segment??!1,Yt=ke.data.sample_rate,ut=Number(ke.data.audio_offset_ms??0);if(De){const Ke=ct;ct=!1,await S.playAudioChunk(n,r,De,Le,lt,et,{sampleRate:Yt,newStream:Ke,audioOffsetMs:ut})}else(Le.length>0||lt.length>0)&&S.queueTimingsOnly(n,r,Le,lt,et,{audioOffsetMs:ut,newStream:ct})}else if(ke.event==="metadata"){const De=ke.data.mood;typeof De=="string"&&De.trim()&&(l=De.trim());const Le=ke.data.sentence_emotions;Array.isArray(Le)&&(a.length=0,a.push(...Un(Le,l))),ne()}else if(ke.event==="error")throw new Error(String(ke.data.message??"avatar_ttsWithPoses stream error"))}};for(;!(ge!==q||he.signal.aborted||!L);){const{done:Fe,value:ke}=await Lt.read();ke&&(Ve+=Ze.decode(ke,{stream:!0}));const De=Ve.split(`
3
+ `);K=k.pop()??"";for(const O of k)await b(O);if(d){K.trim()&&await b(K.trim()),G.markStreamComplete(i),V("bot_stopped",I());break}}}catch(X){if(ee!==_)return{displayText:de,spokenText:H,aborted:!0};if(X instanceof DOMException&&X.name==="AbortError")return{displayText:de,spokenText:H,aborted:!0};throw console.error("[avatarTtsLipsync]",X),ae(),e("error"),X}return{displayText:de,spokenText:H}};return{setDeveloperToken:S=>{y=S},setTtsEngineId:S=>{E=S},getTtsEngineId:()=>E,speak:async(S,ee)=>{const{engineId:$,voiceId:H,speakingRate:de,language:X}=Re(ee),se={user_query:S,ttsEngineId:$,speakingRate:de,tenant:"aiTwin"};an.has($)&&(se.voice_id=H),X&&(se.language=X),(ee?.fullBody??g)&&(se.fullBody=!0),await ke({requestBody:se,engineId:$,debugSpokenFallback:S,delayPlayback:ee?.delayPlayback})},speakWithReply:async(S,ee)=>{const $=S.trim();if(!$)throw new Error("Message is required");const{engineId:H,voiceId:de,speakingRate:X,language:se}=Re(ee),me={generateReply:!0,message:$,ttsEngineId:H,speakingRate:X,tenant:"aiTwin",history:ee?.history??[]};an.has(H)&&(me.voice_id=de),se&&(me.language=se),(ee?.fullBody??g)&&(me.fullBody=!0);const K=ee?.brainId?.trim();K&&(me.brainId=K);const re=ee?.brainUrl?.trim();re&&(me.brainUrl=re);const I=ee?.userName?.trim();I&&(me.userName=I);const b=ee?.userEmail?.trim();b&&(me.userEmail=b);const d=ee?.userContext?.trim();d&&(me.userContext=d);const m=await ke({requestBody:me,engineId:H,debugSpokenFallback:$,delayPlayback:ee?.delayPlayback,onSpokenText:ee?.onSpokenText,onDisplayText:ee?.onDisplayText});if(m.aborted)return{spokenText:m.spokenText,displayText:m.displayText};if(!m.spokenText&&!m.displayText)throw new Error("avatar_ttsWithPoses generateReply stream missing spokenText or displayText");return{spokenText:m.spokenText||m.displayText,displayText:m.displayText||m.spokenText}},stop:ae,releasePlaybackHold:()=>G.releaseStartHold(),getVisemeQueue:()=>i,getWordQueue:()=>s,getFullVisemeQueue:()=>o,getFullWordQueue:()=>a,getSentenceEmotions:()=>h,getStreamMood:()=>p,getPlaybackElapsedMs:()=>G.getPlaybackElapsedMs(),isSpeaking:()=>G.isSpeaking(),isWarmingUp:()=>G.isWarmingUp(),releaseWarmupHold:()=>G.releaseWarmupHold(),setLipsyncWarmupHold:(S,ee)=>{ee&&(j=ee),G.setLipsyncWarmupHoldEnabled(S)},getVoiceStream:()=>G.getVoiceStream(),setMuted:S=>{G.setMuted(S)},isMuted:()=>G.isMuted(),setPlaybackSpeed:S=>{G.setPlaybackSpeed(S)},getPlaybackSpeed:()=>G.getPlaybackSpeed(),subscribe:S=>(M.add(S),()=>M.delete(S))}}function rr(e){if(e==null)return!1;if(typeof e=="object"){const n=e;if(n.type==="permissions"||n.name==="NotAllowedError"||n.name==="PermissionDeniedError")return!0}const r=(e instanceof Error?`${e.name} ${e.message}`:typeof e=="string"?e:String(e)).toLowerCase();return!!(r.includes("notallowederror")||r.includes("permissiondeniederror")||r.includes("permission denied")||r.includes("permissions denied")||r.includes("microphone access denied")||(r.includes("microphone")||r.includes(" mic"))&&(r.includes("denied")||r.includes("blocked")||r.includes("not allowed")||r.includes("permission")))}async function eo(){if(typeof navigator>"u"||!navigator.permissions?.query)return!1;try{return(await navigator.permissions.query({name:"microphone"})).state==="denied"}catch{return!1}}const Mn=16e3,Pn=16e3;class to extends wn.ProtobufFrameSerializer{async deserialize(t){try{return await super.deserialize(t)}catch(r){if(r instanceof Error&&r.message==="Unknown frame kind")return{type:"raw",message:null};throw r}}}class ro extends wn.DailyMediaManager{constructor(){super(!0,!0,void 0,void 0,512,Mn,Pn)}bufferBotAudio(t,r){}}const no=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ai(e){return no.test(e.trim())}function io(e){const t=e.replace(/\/$/,"");return t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t}function Ts(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 r=e.apiBase??ut,n=new URL(`${io(r)}/ws/voice`);n.searchParams.set("authToken",t),n.searchParams.set("tenant","aiTwin");const i=lt(e.ttsEngineId,e.voiceId),s=i.ttsEngineId;s&&n.searchParams.set("ttsEngineId",s);const o=i.voiceId?.trim();o&&(s&&Oi(s)?ai(o)||n.searchParams.set("voiceId",o):ai(o)&&n.searchParams.set("voiceId",o));const a=Br(e.language);a&&n.searchParams.set("language",a);const f=e.brainId?.trim()||e.personaId?.trim();f&&n.searchParams.set("brainId",f);const h=e.brainUrl?.trim();h&&n.searchParams.set("brainUrl",h);const l=e.speakingRate??or;n.searchParams.set("speaking_rate",String(Math.max(Ur,Math.min(Vr,l)))),e.ttsStream===!1?n.searchParams.set("tts_stream","false"):n.searchParams.set("tts_stream","true"),e.speakOnlyWhenSpokenTo&&n.searchParams.set("speakOnlyWhenSpokenTo","true");const c=e.avatarName?.trim();c&&n.searchParams.set("avatarName",c);const p=e.userName?.trim();p&&n.searchParams.set("userName",p);const y=e.userEmail?.trim();y&&n.searchParams.set("userEmail",y);const E=e.userContext?.trim();return E&&n.searchParams.set("userContext",E),n.toString()}function Zr(e,t){if(!Array.isArray(e))return[];const r=[];for(const n of e)!n||typeof n!="object"||r.push({sentence_index:Number(n.sentence_index??0),text:String(n.text??""),sentiment:typeof n.sentiment=="string"?n.sentiment:void 0,emotion:String(n.emotion??t),start_word:Number(n.start_word??0),end_word:Number(n.end_word??0)});return r}function so(e){if(!e||typeof e!="object")return null;const t=e,n=(t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:null)||t;return{...n,type:String(n.type??t.type??"server-message")}}function oi(e){return e.is_new_segment===!0||Number(e.audio_offset_ms??-1)===0?!0:Number(e.chunk_index??-1)===0}function ao(e){return e?.transport?._mediaManager?._wavStreamPlayer??null}function ks(e,t={}){const r=[],n=[],i=[],s=[];let o=0;const a=[],f=[];let h="",l="neutral",c=dt,p=!1,y=null,E=null,g={...t},M=0,W=null;const B=new Set,_=[];let x=!1,N=null,j=!0,G="default";const ie=new Set;let P=null,V=0,Z=!1,Q=!1,ue=null,ae=!1;const Re=()=>{ue!=null&&(clearTimeout(ue),ue=null)},ke=()=>{Re(),ue=setTimeout(()=>{ue=null,j&&(S.markStreamComplete(r),X("bot_stopped"))},450)},ne=()=>B.forEach(w=>w());let ze=()=>!1;const S=_s({onSpeakingStart:()=>e("speaking"),onSpeakingDone:()=>{ae=!1,Q=!1,e("done")},onNotify:ne,shouldHoldForWarmup:()=>ze()},c),ee=()=>{if(N)return N;const w=new MessageChannel;return w.port1.onmessage=()=>{const D=_.shift();D!==void 0&&J(D),_.length>0?w.port2.postMessage(null):x=!1},N=w,w},$=w=>{_.push(w),!x&&(x=!0,ee().port2.postMessage(null))},H=()=>S.getPlaybackElapsedMs(),de=(w,D=h)=>{if(!g.onLipsyncDebug)return;const oe=H(),fe=r,we=Nr(i).map(ge=>({viseme:ge.viseme,vtimeMs:ge.vtime}));g.onLipsyncDebug({event:w,spokenText:D,mood:l,playbackAnchorPerf:S.getPlaybackStartPerf(),playbackElapsedMs:oe,queueLength:fe.length,activeViseme:ar(fe,oe),segments:f.map(ge=>({...ge,visemes:[...ge.visemes]})),fullQueueLength:i.length,compactionSkipped:we})},X=(w,D)=>{g.onLipsyncDebug&&(W={event:w,spokenText:D},M===0&&(M=requestAnimationFrame(()=>{M=0;const oe=W;W=null,oe&&de(oe.event,oe.spokenText)})))},se=()=>{j=!0,ie.clear(),S.clearAborted()},me=()=>{const w=ao(y);if(w){G=`bot-${Date.now()}`,w.interruptedTrackIds={[G]:!0};try{w.interrupt?.()}catch{}}const D=E;try{D?.interrupt?.()}catch{}},he=w=>{if(ae&&S.isSpeaking())return!0;const D=w.context_id?.trim();return D&&ie.has(D)?!0:j?!1:!(w.type==="avatar_metadata"||oi(w))},K=w=>{j=!1,ae=!1;const D=w.context_id?.trim();D&&ie.add(D),Re(),Z=!1,Q=!1,_.length=0,x=!1,P?.abort(),P=null,V+=1,me(),S.bargeIn(),re(),e("idle"),X("interrupt"),ne()},re=()=>{r.length=0,n.length=0,i.length=0,s.length=0,o=0,f.length=0,h="",l="neutral",a.length=0},I=()=>{Re(),Q=!1,Z=!1,S.stop(),re(),X("reset"),ne()},b=()=>{I(),e("idle"),ne()},d=(w,D)=>{typeof w.mood=="string"&&w.mood.trim()&&(l=w.mood.trim()),Array.isArray(w.sentence_emotions)&&w.sentence_emotions.length>0&&(D&&(a.length=0),a.push(...Zr(w.sentence_emotions,l)))},m=w=>{if(he({...w,type:"avatar_metadata"}))return;se(),Z=!0;const D=String(w.spoken_text??w.text??"").trim();D&&(h=D),S.resetForNewStream(c),typeof w.mood=="string"&&w.mood.trim()&&(l=w.mood.trim()),a.length=0,a.push(...Zr(w.sentence_emotions,l)),Array.isArray(w.gestures)&&w.gestures,X("metadata",D),ne()},k=(w,D,oe,fe)=>{if(!g.onLipsyncDebug)return;const we=r.slice(oe),ge=fe.filter(Me=>String(Me.symbol??Me.viseme??"").trim());f.push({spokenText:D,audioOffsetMs:we[0]?.vtime??0,isNewSegment:!!w.is_new_segment,chunkDurationMs:w.chunk_duration_ms!=null?Number(w.chunk_duration_ms):null,receivedAtMs:performance.now(),visemes:we.map((Me,Ge)=>{const Ne=ge[Ge];return{rawSymbol:String(Ne?.symbol??Ne?.viseme??Me.viseme).trim(),viseme:Me.viseme,startSec:Number(Ne?.start??0),durationSec:Number(Ne?.duration??0),vtimeMs:Me.vtime,vdurationMs:Me.vduration}})})},O=(w,D,oe,fe)=>{if(w.length===0&&D.length===0)return;gs(i,s,w,D,o,c);const we=ws(w,o);let ge=null;const Me=oe.trim();if(Me)try{const Ge=atob(Me.replace(/\s+/g,"")).length,Ne=Number.isFinite(fe)&&(fe??0)>0?Number(fe):16e3;ge=Ge/2/Ne*1e3}catch{ge=null}o=Math.max(we,ge!=null?o+ge:o)},F=w=>{if(he(w))return;const D=oi(w);D&&(Re(),se());const oe=String(w.spoken_text??w.text??"").trim(),fe=w.visemes??[],we=w.words??[],ge=String(w.chunk??"").trim(),Me=Z||D||!Q;Z&&(Z=!1),Me&&(Q=!0),oe&&(h=oe),d(w,D),Me?(S.resetForNewStream(c),i.length=0,s.length=0,o=0):D&&S.resumeBotStream(),O(fe,we,ge,w.sample_rate);const Ge=r.length;S.playAudioChunk(r,n,ge,fe,we,D,{sampleRate:w.sample_rate,newStream:Me,audioOffsetMs:Number(w.audio_offset_ms??0),onNewStream:()=>{f.length=0}}).then(()=>{k(w,oe,Ge,fe),X("audio_chunk",oe),ke()})},te=w=>{if(he(w))return;(w.is_new_segment||Number(w.audio_offset_ms??-1)===0)&&se(),console.warn("[realtimeVoice] avatar_lipsync is deprecated — expect avatar_audio_chunk");const D=String(w.spoken_text??w.text??"").trim();D&&(h=D),d(w,!!w.is_new_segment),O(w.visemes??[],w.words??[],"",void 0);const oe=r.length;S.queueTimingsOnly(r,n,w.visemes??[],w.words??[],!!w.is_new_segment,{audioOffsetMs:Number(w.audio_offset_ms??0)}),k(w,D,oe,w.visemes??[]),X("lipsync",D),ne()},C=async w=>{const D=String(w.text??"").trim();if(!D)return;const oe=g.authToken?.trim();if(!oe){console.error("[realtimeVoice] avatar_speak requires authToken");return}P?.abort();const fe=new AbortController;P=fe;const we=++V;se(),S.resetForNewStream(c),h=D;const Me=`${(g.apiBase??ut).replace(/\/$/,"")}/avatar_ttsWithPoses`,Ge=lt(c,g.voiceId);Ge.ttsEngineId&&(c=Ge.ttsEngineId,S.setStreamTtsEngineId(c));const Ne=Ge.voiceId?.trim()||(c===ft?Fr:Rn),Ke=g.speakingRate??or,zt=Math.max(Ur,Math.min(Vr,Ke)),nt={user_query:D,ttsEngineId:c,speakingRate:zt,tenant:"aiTwin"};an.has(c)&&(nt.voice_id=Ne);const Gt=Br(g.language);Gt&&(nt.language=Gt),g.fullBody&&(nt.fullBody=!0);const Mt=g.fullBody?g.waitForBodyIdle?.()??null:null;let cr=!1;const Pt=()=>{cr||(cr=!0,S.releaseStartHold())};Mt&&(S.armStartHold(),Mt.promise.then(Pt));try{const mt=await fetch(Me,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${oe}`},body:JSON.stringify(nt),signal:fe.signal});if(!mt.ok)throw new Error(`avatar_ttsWithPoses failed (${mt.status})`);const lr=mt.body;if(!lr)throw new Error("No response body");const jr=lr.getReader(),ur=new TextDecoder;let vt="",Kt=!0;const Ct=async qt=>{if(we!==V||fe.signal.aborted||!j)return;const Le=rs(qt);if(Le){if(Le.event==="audio"){const Ve=Le.data.chunk,We=Le.data.visemes??[],_t=Le.data.words??[],Je=Le.data.is_new_segment??!1,it=Le.data.sample_rate,bt=Number(Le.data.audio_offset_ms??0);if(Ve){const Fe=Kt;Kt=!1,await S.playAudioChunk(r,n,Ve,We,_t,Je,{sampleRate:it,newStream:Fe,audioOffsetMs:bt})}else(We.length>0||_t.length>0)&&S.queueTimingsOnly(r,n,We,_t,Je,{audioOffsetMs:bt,newStream:Kt})}else if(Le.event==="metadata"){const Ve=Le.data.mood;typeof Ve=="string"&&Ve.trim()&&(l=Ve.trim());const We=Le.data.sentence_emotions;Array.isArray(We)&&(a.length=0,a.push(...Zr(We,l))),ne()}else if(Le.event==="error")throw new Error(String(Le.data.message??"avatar_ttsWithPoses stream error"))}};for(;!(we!==V||fe.signal.aborted||!j);){const{done:qt,value:Le}=await jr.read();Le&&(vt+=ur.decode(Le,{stream:!0}));const Ve=vt.split(`
4
4
 
5
- `);Ve=De.pop()??"";for(const Le of De)await xe(Le);if(Fe){Ve.trim()&&await xe(Ve.trim()),ge===q&&!he.signal.aborted&&L&&S.markStreamComplete(n);break}}}catch(ht){if(he.signal.aborted||!L)return;console.error("[realtimeVoice] avatar_speak failed:",ht),e("error"),ne()}finally{P===he&&(P=null)}},Ae=p=>{const C=ka(p);if(!C){console.warn("[realtimeVoice] server message with no payload",p);return}const ie=String(C.type??"unknown");switch(ie!=="avatar_metadata"&&ie!=="avatar_audio_chunk"&&ie!=="avatar_lipsync"&&ie!=="avatar_interrupt"&&ie!=="error"&&console.debug("[realtimeVoice] server message",ie,C),ie){case"avatar_metadata":x(C);break;case"avatar_audio_chunk":j(C);break;case"avatar_lipsync":Z(C);break;case"avatar_interrupt":_(C);break;case"error":{const he=String(C.message??"Voice session error");console.error("[realtimeVoice] server error:",he),e("error"),ne();break}case"avatar_speak":Te(C);break}},F=()=>w||(T=new ba,w=new bs.PipecatClient({transport:new nr.WebSocketTransport({mediaManager:T,serializer:new _a,recorderSampleRate:wr,playerSampleRate:gr}),enableCam:!1,enableMic:!0,callbacks:{onBotReady:()=>{f=!0,e("idle"),ne()},onDisconnected:()=>{f=!1,b()},onError:p=>{const C=typeof p=="object"&&p!==null&&"data"in p?String(p.data??p):String(p);console.error("[realtimeVoice]",C,p),e("error"),ne()},onTransportStateChanged:p=>{p==="error"&&(e("error"),ne())},onServerMessage:p=>{X(p)},onUserStartedSpeaking:()=>{},onBotStartedSpeaking:()=>{$(),z("bot_started")},onBotStoppedSpeaking:()=>{L&&We()},onUserTranscript:p=>{String(p.text??""),h.onUserTranscript?.(p.text,!!p.final)},onBotOutput:p=>{h.onBotOutput?.(p.text)}}}),w);return{setDeveloperToken:p=>{},setTtsEngineId:p=>{c=p,S.setStreamTtsEngineId(p)},getTtsEngineId:()=>c,speak:async(p,C)=>{const ie=p.trim();if(ie){if(!w||!f)throw new Error("Realtime voice is not connected. Call connect() first.");W(),await w.sendText(ie)}},speakWithReply:async(p,C)=>{throw new Error("speakWithReply is not available on the voice session; use AiTwin.speakWithReply()")},stop:()=>{P?.abort(),P=null,q+=1,$(),W(),e("idle"),ne()},connect:async p=>{p&&(h={...h,...p});const C=it(h.ttsEngineId,h.voiceId);if(C.ttsEngineId&&(c=C.ttsEngineId,S.setStreamTtsEngineId(c)),h={...h,ttsEngineId:c,...C.voiceId?{voiceId:C.voiceId}:{}},!h.authToken?.trim())throw new Error("Voice connect requires authToken (same JWT as SSE Authorization Bearer).");e("loading");const ie=F();try{await ie.initDevices()}catch(ge){throw f=!1,e("idle"),ne(),Wt(ge)?new Error("Microphone access denied"):ge instanceof Error?ge:new Error("Failed to initialize microphone")}const he=Xi({...h,ttsEngineId:c});console.info("[realtimeVoice] connecting (avatar_audio_chunk RTVI):",he);try{await ie.connect({wsUrl:he})}catch(ge){if(f=!1,e("error"),ne(),Wt(ge))throw e("idle"),new Error("Microphone access denied");const Me=ge instanceof Error?ge.message:"Realtime voice connect failed (WebSocket 101 only means upgrade OK — check authToken/origin/RTVI handshake)";throw new Error(`${Me} — ${he}`)}f=!0,e("idle"),ne()},disconnect:async()=>{if(Se(),Q=!1,ee=!1,v.length=0,E=!1,P?.abort(),P=null,q+=1,$(),w)try{await w.disconnect()}catch(p){console.error("[realtimeVoice] disconnect failed:",p)}f=!1,b()},isConnected:()=>f,unlockAudio:async()=>{await S.primeAudioContext()},getVisemeQueue:()=>n,getWordQueue:()=>r,getFullVisemeQueue:()=>i,getFullWordQueue:()=>s,getSentenceEmotions:()=>a,getStreamMood:()=>l,getPlaybackElapsedMs:ce,isSpeaking:()=>S.isSpeaking(),isWarmingUp:()=>S.isWarmingUp(),releaseWarmupHold:()=>S.releaseWarmupHold(),setLipsyncWarmupHold:(p,C)=>{C&&(D=C),S.setLipsyncWarmupHoldEnabled(p)},getVoiceStream:()=>S.getVoiceStream(),setMuted:p=>{S.setMuted(p)},isMuted:()=>S.isMuted(),setPlaybackSpeed:p=>{S.setPlaybackSpeed(p)},getPlaybackSpeed:()=>S.getPlaybackSpeed(),subscribe:p=>(O.add(p),()=>O.delete(p))}}function Zi(e,t,n){return{width:e.crop?.source_width??t,height:e.crop?.source_height??n}}function es(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 ts(e){return e?(e.w??0)>0&&(e.h??0)>0:!1}async function Dt(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 Hs(r,t)}async function ns(e,t){if(!t)throw new Error("Missing asset key for encrypted JSON");const n=await Dt(e,t),r=new TextDecoder().decode(n);return JSON.parse(r)}async function Ea(e){const t=new Blob([e],{type:"image/webp"});return createImageBitmap(t)}async function Ia(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 Aa(e){const t=new Blob([e],{type:"image/png"});return createImageBitmap(t)}async function Ma(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 Ra(e){const t=new Blob([e],{type:"video/mp4"});return URL.createObjectURL(t)}async function Ca(e){const t=Ks();if(!Ht())return t;if(!e)throw new Error("Missing asset key for encrypted idle video");const n=await Dt(t,e);return Ra(n)}function It(e,t){return`${e}/${t}_minus_sil.png`}const rs=5;function En(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:rs}const Pa=["aa","E","I","O","U","PP","FF","DD","SS","TH","CH","RR","kk","nn"],Jn=["t01_0.25","t02_0.50","t03_0.75"],Da=Jn.length,$r=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 Kr(e,t){return`${e}__${t}`}function Gr(e,t){return`pairs/${e}/${t}_minus_sil.png`}function Mt(e){return`${e}_minus_sil.png`}function yr(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=Mt(r);return t.has(i)?i:null}function is(e,t){return e.filter(n=>t.has(n))}function Ba(e,t,n){const r=vr(e,t);return is(r,n).length>0}function vr(e,t){if(e===t)return[];const n=[],r=Kr(e,t);if($r.has(r)){for(const s of Jn)n.push(Gr(r,s));return n}const i=Kr(t,e);if($r.has(i)){for(let s=Da-1;s>=0;s--)n.push(Gr(i,Jn[s]));return n}return[]}function Fa(e){return e<16?[1]:e<24?[1]:e<35?[0,1,2]:[0,1,2]}function La(e,t){return Fa(t).map(r=>e[r]).filter(r=>r!=null)}function Na(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 ss(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 Oa=[.32,.24,.16,.08,0],Ua=Oa.map(e=>`eyes_${e.toFixed(2)}`),Va=["eyes_0.32","eyes_0.16","eyes_0.00"],Wa=["eyes_0.32","eyes_0.16","eyes_0.08","eyes_0.00"],$e=2,ja=-20,mn=16,as={fear:-20,anger:-20,sad:-10,neutral:0,love:0,happy:0,disgust:10};function jt(e){return`brow_${e}`}function _t(e){return as[e]}function Je(e){return Math.max(ja,Math.min(mn,e))}function za(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 qr(e){const t=Je(e);if(t%$e===0)return[t];const n=Math.floor(t/$e)*$e,r=Math.min(mn,n+$e),i=Je(n);return t-i<=r-t?i===r?[i]:[i,r]:i===r?[r]:[r,i]}const Ha=["fear","anger","sad","neutral","love","happy","disgust"],$a={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 rt(e,t="neutral"){const n=String(e??"").trim().toLowerCase();return n?$a[n]??t:t}function os(e){return e===0?null:It(jt(e),"eyes_standard")}function cs(e){return os(_t(e))}const Ka={[-20]:"anger",[-10]:"sad",0:"neutral",10:"disgust"};function _r(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 qr(i)){if(a===i)continue;const u=It(jt(a),s);if(t(u))return u}const o=Ka[i];if(o){const a=It(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=_t(i);for(const a of[o,...qr(o)]){const u=It(jt(a),s);if(t(u))return u}}return null}function Yr(e,t){const n=jt(_t(e));return!t||t==="eyes_standard"?cs(e):e==="neutral"&&t==="eyes_standard"?null:It(n,t)}function Ga(e,t){const n=[];for(const r of t)n.push(Yr(e,r));for(let r=t.length-2;r>=0;r--)n.push(Yr(e,t[r]));return n.push(cs(e)),n}function qa(e){return It(jt(e),"eyes_standard")}function Ya(e,t){return za(e,t).map(qa)}const Qa=6;function Xa(e,t){for(const n of e)if(t>=n.wtime&&t<n.wtime+n.wduration)return n;return null}function Ja(e){const t=Je(e);return t>=mn?mn:Je(t+Qa)}function Za(e,t,n){const r=Je(n);return Xa(t,e)?.emphasis?Ja(r):r}function Qr(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 Xe(e,t){return e+Math.random()*(t-e)}function Xr(){return Xe(14,32)}function eo(e){if(e)return{holdMinMs:10,holdMaxMs:18,closedExtraMs:0};const t=Math.random();return t<.18?{holdMinMs:38,holdMaxMs:62,closedExtraMs:Xe(40,90)}:t<.42?{holdMinMs:26,holdMaxMs:44,closedExtraMs:Xe(12,36)}:t<.82?{holdMinMs:14,holdMaxMs:28,closedExtraMs:Math.random()<.35?Xe(8,22):0}:{holdMinMs:10,holdMaxMs:18,closedExtraMs:0}}function Jr(e,t){const n=Xe(e.holdMinMs,e.holdMaxMs);return t?n+e.closedExtraMs:n}function to(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:u=380,minDwellMs:d=550}=e;let l="neutral",c="neutral",f=0,w=0,T=0,h={kind:"idle",nextBlinkAt:performance.now()+t},I=null,H="__eyes_open__|neutral|brow:0";function O(P=l){H=`${I??"__eyes_open__"}|${P}|brow:${w}`}function v(P,q=l){I=P;const Q=Qr(P);Q!=null?w=Q:P==null&&(w=0),O(q)}function E(P){return os(P)}function V(P,q,Q){const ee=Je(q),oe=Je(Q);if(f=oe,ee===oe){v(E(oe));return}const ue=[...Ya(ee,oe),E(oe)];h={kind:"browBlend",paths:ue,index:0,holdUntil:P+Xr(),targetBrow:oe},v(ue[0]??null)}function L(P,q){h={kind:"idle",nextBlinkAt:P+Xe(n,r)},c=q,v(E(f),q)}function se(P,q,Q){const ee=Q?Va:Math.random()<a?Ua:Wa,oe=eo(Q),ue=ee.length-1;h={kind:"playing",paths:Ga(q,ee),index:0,holdUntil:P+Jr(oe,ue===0),after:"idle",blinkEmotion:q,pace:oe,closedFrameIndex:ue},c=q,v(h.paths[0]??null,q)}function re(P){if(h.kind==="browBlend"){for(;P>=h.holdUntil&&h.index<h.paths.length-1;)h.index+=1,h.holdUntil=P+Xr();const q=h.paths[h.index]??null;v(q),P>=h.holdUntil&&h.index>=h.paths.length-1&&(w=h.targetBrow,f=h.targetBrow,v(E(h.targetBrow)),h={kind:"idle",nextBlinkAt:P+u});return}if(h.kind==="idle"){v(E(f),c),P>=h.nextBlinkAt&&se(P,c,!1);return}if(h.kind==="doublePause"){v(E(f),h.blinkEmotion),P>=h.resumeAt&&se(P,h.blinkEmotion,!0);return}if(h.kind==="playing"){for(;P>=h.holdUntil&&h.index<h.paths.length-1;)h.index+=1,h.holdUntil=P+Jr(h.pace,h.index===h.closedFrameIndex);if(v(h.paths[h.index]??null,h.blinkEmotion),P>=h.holdUntil&&h.index>=h.paths.length-1){if(h.after==="resumeIdle"){L(P+u,l);return}if(h.after==="doublePause"){h={kind:"doublePause",resumeAt:P+Xe(s,o),blinkEmotion:h.blinkEmotion},v(E(f),h.blinkEmotion);return}if(h.after==="idle"&&Math.random()<i){h={kind:"doublePause",resumeAt:P+Xe(s,o),blinkEmotion:h.blinkEmotion},v(E(f),h.blinkEmotion);return}L(P,h.blinkEmotion)}}}return{advance:re,setTargetEmotion(P,q){const Q=rt(P,l);if(Q===l)return;const ee=performance.now();!q?.force&&d>0&&!(l==="neutral"&&Q!=="neutral")&&ee-T<d||(l=Q,c=Q,T=ee)},setTargetEyebrow(P){const q=Je(P);if(q===f)return;const Q=performance.now(),ee=h.kind==="browBlend"?Qr(I)??w:w;f=q,!(q===ee&&h.kind!=="browBlend")&&(h.kind==="playing"||h.kind==="doublePause"||V(Q,ee,q))},snapToEmotion(P){const q=rt(P),Q=_t(q);l=q,c=q,f=Q,w=Q,T=performance.now(),h={kind:"idle",nextBlinkAt:performance.now()+Xe(4e3,7e3)},v(E(Q),q)},getTargetEmotion:()=>l,getTargetEyebrow:()=>f,getExpressionPath:()=>I,getDrawKey:()=>H,reset(){l="neutral",c="neutral",f=0,w=0,T=0,L(performance.now()+Xe(n,r),"neutral")}}}function no(){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 u=()=>{const d=e.duration;if(!Number.isFinite(d)||d<=0){a(new Error(`Idle video has invalid duration: ${s}`));return}t=!0,e.currentTime=0,o()};e.addEventListener("loadeddata",u,{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())},setLooping(s){e.loop=s},restart(){t&&(e.currentTime=0)},dispose(){e.pause(),e.removeAttribute("src"),e.load(),i(),t=!1,r=""}}}const ro=50,ls=400;function io(e,t,n){return e.filter(r=>{const i=r.queueIndex??-1;return i>=t&&i<=n})}function so(e,t){const n=[];for(const r of e){const i=io(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-ro),endMs:o.wtime+o.wduration+ls})}return n.sort((r,i)=>r.startMs-i.startMs)}function ao(e,t,n,r="neutral"){const i=rt(r);if(t.length===0)return i;if(n.length===0||e<n[0].wtime)return rt(t[0]?.emotion,i);const s=so(t,n);let o=null;for(const d of s)e>=d.startMs&&e<=d.endMs&&(o=d);if(o)return rt(o.sentence.emotion,i);const a=n[n.length-1],u=a.wtime+a.wduration;return e>u+ls?rt(t[t.length-1]?.emotion,i):i}function br(e,t,n,r,i=rs){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),u=o.createImageData(n,r);u.data.set(a.data);const l=new OffscreenCanvas(n,r).getContext("2d",{willReadFrequently:!0});for(const c of t){l.clearRect(0,0,n,r),l.drawImage(c,0,0,n,r);const f=l.getImageData(0,0,n,r);for(let w=0;w<u.data.length;w+=4){const T=f.data[w],h=f.data[w+1],I=f.data[w+2];f.data[w+3]>0&&Math.max(T,h,I)>i&&(u.data[w]=T,u.data[w+1]=h,u.data[w+2]=I,u.data[w+3]=255)}}return o.putImageData(u,0,0),s}let gt=null,Rt=null;const hn=new Map;function oo(){gt=null,Rt=null,hn.clear()}xi(oo);function co(e){return e??Rt??void 0}function Sr(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 lo(e){return Ht()?Ma(await Dt(fn(),e??"")):Sr(fn())}async function Zr(e,t,n,r){const i=n?await ns(e,r):await fetch(e).then(d=>{if(!d.ok)throw new Error(`Failed to load ${e}`);return d.json()}),s=i.sheets?.[0];if(!s?.path)throw new Error(`${e} has no sheets[0].path`);const o=n?await Ia(await Dt(ss(t,s.path,n),r??"")):await Sr(`${t}/${s.path}`),a=new Map;for(const d of i.cells??[])d.path&&a.set(d.path,d);const u=new Map;for(const d of i.sheets??[])u.set(d.index,d);return{atlas:o,atlasMeta:i,cellByPath:a,sheetByIndex:u,diffBase:t}}async function Zn(e){const t=co(e),n=Ht();if(n&&!t)throw new Error("Encrypted assets enabled but no key provided");if(gt&&(!n||Rt===(t??null))){const s=await gt;return{...Ct(s),visemePaths:[...s.viseme.cellByPath.keys()]}}Rt=t??null,hn.clear();const r=Ei();gt=(async()=>{const s=await lo(t),o=await Zr(Ii(),r,n,t);let a=null;try{a=await Zr(Ai(),r,n,t)}catch{a=null}return{sil:s,viseme:o,expression:a}})();const i=await gt;return{...Ct(i),visemePaths:[...i.viseme.cellByPath.keys()]}}async function Tr(e){if(await Zn(e),!gt)throw new Error("Assets not loaded");return gt}function Ct(e){return Zi(e.viseme.atlasMeta,e.sil.naturalWidth,e.sil.naturalHeight)}function uo(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 pn(e,t,n){const r=`${t.diffBase}::${n}`,i=hn.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=es(t.atlasMeta,o),u=Ct(e);if(ts(o)){const c=uo(t,o),f=document.createElement("canvas");f.width=u.width,f.height=u.height;const w=f.getContext("2d");return w.fillStyle="#000",w.fillRect(0,0,u.width,u.height),w.drawImage(c,a.x,a.y),f}const d=`${t.diffBase}/${n}`,l=await Sr(d);if(l.naturalWidth===u.width&&l.naturalHeight===u.height)return l;throw new Error(`Diff PNG wrong size for ${n}`)})();return hn.set(r,s),s}async function Vn(e,t,n,r,i,s){if(i){const{width:w,height:T}=i;if(s&&!s()||t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)return;const h=document.createElement("canvas");h.width=w,h.height=T;const I=h.getContext("2d");if(I.clearRect(0,0,w,T),I.drawImage(t,0,0,w,T),s&&!s())return;(e.width!==w||e.height!==T)&&(e.width=w,e.height=T);const H=e.getContext("2d");H.clearRect(0,0,w,T),H.drawImage(h,0,0);return}const o=await Tr(),a=En(o.viseme.atlasMeta),{width:u,height:d}=Ct(o);(e.width!==u||e.height!==d)&&(e.width=u,e.height=d);const l=[],c=e.getContext("2d");if(c.clearRect(0,0,u,d),t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){const w=o.sil;c.drawImage(w,0,0,u,d);return}if(l.length===0){c.drawImage(t,0,0,u,d);return}const f=br(t,l,u,d,a);c.drawImage(f,0,0)}async function er(e,t,n){const r=await Tr(Rt??void 0),i=En(r.viseme.atlasMeta),{width:s,height:o}=Ct(r);(e.width!==s||e.height!==o)&&(e.width=s,e.height=o);const a=[];if(t.mouthPath){const l=new Set(r.viseme.cellByPath.keys()),c=yr(t.mouthPath,l)??(l.has(t.mouthPath)?t.mouthPath:null);c&&a.push(await pn(r,r.viseme,c))}if(t.expressionPath&&r.expression){const l=_r(t.expressionPath,c=>r.expression.cellByPath.has(c));l&&a.push(await pn(r,r.expression,l))}const u=e.getContext("2d");if(u.clearRect(0,0,s,o),a.length===0){u.drawImage(r.sil,0,0,s,o);return}const d=br(r.sil,a,s,o,i);u.drawImage(d,0,0)}async function fo(e,t){const n=await Tr(Rt??void 0),r=En(n.viseme.atlasMeta),{width:i,height:s}=Ct(n),o=[];if(e.mouthPath){const l=new Set(n.viseme.cellByPath.keys()),c=yr(e.mouthPath,l)??(l.has(e.mouthPath)?e.mouthPath:null);c&&o.push(await pn(n,n.viseme,c))}if(e.expressionPath&&n.expression){const l=_r(e.expressionPath,c=>n.expression.cellByPath.has(c));l&&o.push(await pn(n,n.expression,l))}const a=new OffscreenCanvas(i,s),u=a.getContext("2d");if(o.length===0)return u.drawImage(n.sil,0,0,i,s),a.transferToImageBitmap();const d=br(n.sil,o,i,s,r);return u.drawImage(d,0,0),a.transferToImageBitmap()}async function mo(e){await er(e,{mouthPath:null,expressionPath:null})}const on={fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"clamp(0.875rem, 2.5vw, 1.125rem)",color:"rgba(255,255,255,0.85)"};function ho(e){return e.length===0?"":e.map(t=>t.word).join(" ")}function po(e){if(!e)return{enabled:!1,style:on};const t=e===!0?{}:e;return{enabled:!0,style:{fontFamily:t.fontFamily??on.fontFamily,fontSize:t.fontSize??on.fontSize,color:t.color??on.color}}}const wo={position:"absolute",bottom:0,left:0,right:0,display:"flex",justifyContent:"center",padding:"0.75rem 1rem",pointerEvents:"none"},go={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"},yo={display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",maxWidth:"100%",margin:0};function vo({text:e,style:t}){return M.jsx("div",{style:wo,"aria-live":"polite","aria-atomic":"true",children:M.jsx("div",{style:{...go,fontFamily:t.fontFamily,fontSize:t.fontSize,color:t.color},children:M.jsx("p",{style:yo,children:e})})})}const _o={inset:0,overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:3},bo={filter:"blur(22px)",height:"100%",inset:0,objectFit:"cover",objectPosition:"top",position:"absolute",transform:"scale(1.08)",width:"100%"},So={backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",inset:0,position:"absolute"};function To({thumbnailUrl:e}){const[t,n]=m.useState(!1);m.useEffect(()=>{n(!1)},[e]);const r=!!e&&t;return M.jsxs("div",{style:_o,"aria-hidden":!0,children:[e?M.jsx("img",{src:e,alt:"",style:{...bo,opacity:r?1:0,transition:"opacity 0.45s ease"},onLoad:()=>n(!0),onError:()=>n(!1)}):null,M.jsx("div",{style:{...So,background:r?"rgba(0, 0, 0, 0.28)":"rgba(10, 10, 11, 0.92)"}})]})}let us=null;function ei(e){us=e}function ft(){return us}function ko(e){return`${e.from}→${e.to}@${e.fromVtime}`}function ti(){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 xo(){let e=ti();const t=new Set,n=new Set,r=new Set;let i="",s=-1,o="";const a=()=>{e=ti(),t.clear(),n.clear(),r.clear(),i="",s=-1,o=""},u=l=>{t.add(l)},d=l=>{l&&r.add(l)};return{reset:a,onRafTickSpeaking(){e.rafTicksSpeaking+=1},onDrawDeduped(){e.rafTicksDeduped+=1},onDrawRequested(){e.drawsRequested+=1},onQueueSuperseded(){e.queueSuperseded+=1},onWorkerStale(){e.workerStale+=1},onTransitionSample(l,c){const f=ko(l);e.transitionFramesSampled+=1,f!==i&&(i=f,s=-1,o!==f&&(o=f,e.rifeFramesOmittedByGap+=l.omittedByGap)),c&&n.add(c),s>=0&&l.frameIdx>s+1&&(e.transitionFramesMissed+=l.frameIdx-s-1),s=l.frameIdx},onBufferTick(){e.bufferTicks+=1},onBufferHit(){e.bufferHits+=1},onBufferUnderrun(){e.bufferUnderruns+=1},onBufferPrefetched(){e.bufferPrefetched+=1},onBufferReset(){},onDrawDisplayed(l,c){if(e.drawsDisplayed+=1,l.transitionMeta){e.transitionFramesDisplayed+=1;const w=l.transitionMeta;u(w.fromVtime),u(w.toVtime),d(l.mouthPath);return}if(l.label.includes("→")){e.transitionFramesDisplayed+=1;return}const f=l.label.trim();if(!(!f||f==="sil")){for(const w of c)if(w.viseme===f&&l.elapsedMs>=w.vtime&&l.elapsedMs<w.vtime+w.vduration){u(w.vtime);break}}},snapshot(l,c){let f=0,w=0;for(const O of l)if(O.viseme!=="sil"){if(O.vtime>=c)break;f+=1,t.has(O.vtime)&&(w+=1)}const T=f>0?Math.round(w/f*100):100,h=e.queueSuperseded+e.workerStale+Math.max(0,e.drawsRequested-e.drawsDisplayed),I=f-w,H=e.bufferTicks>0?Math.round(e.bufferHits/e.bufferTicks*100):100;return{...e,bufferHitRate:H,renderLoss:h,visemeSlotsTotal:f,visemeSlotsCovered:w,visemeCoveragePct:T,transitionFramesUniqueSampled:n.size,transitionFramesUniquePainted:r.size,drawsDeduped:e.rafTicksDeduped,renderSkips:e.rafTicksDeduped+h,visemesShown:w,visemesSkipped:I,rifeTransitionFramesSkipped:e.transitionFramesMissed}}}}const ds=ir,Eo=500,ni=500,Io=450,Wn=.05,Ao=100,Mo=600,fs="__sil__";function ri(e){return e.lastDrawnKey?e.lastDrawnKey.split("|")[0]===fs:!1}function kr(){return{lastDrawnKey:""}}function Ue(e){e.lastDrawnKey="",e.transitionCache=void 0}function Ro(e,t){if(t?.transitionCache&&t.transitionCache.queueLength===e.length)return t.transitionCache.transitions;const n=zi(e);return t&&(t.transitionCache={queueLength:e.length,transitions:n}),n}function Co(e,t){let n="sil";for(const r of e)r.viseme!=="sil"&&(t!=null&&r.vtime>t||(n=r.viseme));return n}function Po(e,t,n,r=120){if(n!=="sil")return n;const i=Qi(e,t,r);return i!=="sil"?i:Co(e,t)}function Do(e,t){return e==="sil"?!1:t?Ba(e,"sil",t):vr(e,"sil").length>0}function Bo(){return ds+Mo}function wn(e){return e??fs}function xr(e,t,n,r,i=Ao){if(e.length===0)return{diffPath:null,label:"sil"};if(t>=wt(e))return{diffPath:null,label:"sil"};const s=r?.holdPp===!0,o=Ro(e,r),a=ma(o,t,s);if(a){const l=Hi(a.fromVtime,a.toVtime,a.from,a.to,s);if(t>=l.transStart&&t<l.transEnd){let c=vr(a.from,a.to);n&&(c=is(c,n));const f=La(c,l.effectiveGapMs);if(f.length>0){const w=Na(t,l.transStart,l.transEnd,f.length);return{diffPath:f[w]??f[f.length-1],label:`${a.from}→${a.to}`,transitionMeta:{from:a.from,to:a.to,fromVtime:a.fromVtime,toVtime:a.toVtime,frameIdx:w,frameCount:f.length,fullFrameCount:c.length,omittedByGap:Math.max(0,c.length-f.length)}}}return{diffPath:Mt(a.to),label:a.to}}}const u=Sn(e);let d=Ui(u,t);return d==="sil"&&(d=Qi(e,t,i)),d==="sil"?{diffPath:null,label:"sil"}:{diffPath:Mt(d),label:d}}function zt(e,t){const n=t??wn(e.expressionPath);return`${wn(e.mouthPath)}|${n}`}function ii(e,t,n,r,i,s,o,a,u,d){const l=xr(t,n,u,s),c={mouthPath:l.diffPath,expressionPath:r},f=zt(c,i),w=ft();if(l.transitionMeta&&w?.onTransitionSample(l.transitionMeta,l.diffPath),f===s.lastDrawnKey){w?.onDrawDeduped();return}w?.onDrawRequested(),a(l),s.lastDrawnKey=f,o(e,c,f,T=>{T===f&&(s.lastDrawnKey=f)})}function jn(e,t,n,r,i,s,o=null,a=null){const u={mouthPath:a,expressionPath:t},d=o!=null?`|idle@${Math.round(o*1e3)}`:"",l=zt(u,n)+d;!(o!=null)&&l===r.lastDrawnKey||(s(o!=null?t?"idle · blink":"idle":t?"blink":"sil"),i(e,u,l,f=>{f===l&&(r.lastDrawnKey=l)}))}function ms(e,t,n,r,i=Vt,s){if(n<=t||e.length===0)return[];const o=s??kr(),a=[];let u="";for(let d=t;d<n;d+=i){const l=xr(e,d,r,o),c=wn(l.diffPath);c!==u&&(u=c,a.push({displayAtMs:d,mouthPath:l.diffPath,mouthKey:c,label:l.label}))}return a}const Fo=3;function Er(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(),u=++t;await e(a.diffs,u,a)&&u===t&&a.onDisplayed?.(a.drawKey)}}finally{r=!1,n.length>0&&s()}}},o=()=>{i||(i=!0,queueMicrotask(()=>{i=!1,s()}))};return{enqueue(a,u,d){const l=n.findIndex(c=>c.drawKey===u);l>=0?n[l]={diffs:a,drawKey:u,onDisplayed:d}:(n.length>=Fo&&(n.shift(),ft()?.onQueueSuperseded()),n.push({diffs:a,drawKey:u,onDisplayed:d})),o()},reset(){t+=1,n.length=0},isLatestSeq(a){return a===t},getLatestSeq(){return t}}}function Lo(e,t=2){const n=[],r=new Set;let i=0,s=!1,o=0;const a=(d,l)=>`${d}|${l}`,u=async()=>{if(!s){s=!0;try{for(;i<t&&n.length>0;){const d=n.shift(),l=a(d.displayAtMs,d.drawKey);if(r.has(l))continue;r.add(l),i+=1;const c=o;try{await e(d)}finally{if(r.delete(l),i-=1,c!==o)return}}}finally{s=!1,n.length>0&&i<t&&u()}}};return{enqueue(d){const l=a(d.displayAtMs,d.drawKey);r.has(l)||n.some(c=>a(c.displayAtMs,c.drawKey)===l)||(n.push(d),u())},isQueuedOrInflight(d,l){const c=a(d,l);return r.has(c)?!0:n.some(f=>a(f.displayAtMs,f.drawKey)===c)},reset(){o+=1,n.length=0,r.clear(),i=0},pendingCount(){return n.length+i}}}function No(){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 Oo(e,t,n,r,i,s){const o=ms(t,n,r,i,Vt,s);if(o.length===0)return{ready:0,total:0};let a=0;for(const u of o)e.has(u.displayAtMs,u.mouthKey)&&(a+=1);return{ready:a,total:o.length}}function Uo(e){const t=No(),n=kr(),r=new Set;let i="",s=null;const o=Lo(async c=>{try{if(!e.supportsBufferedPlayback)return;const f=await e.compositePrefetchFrame(c.diffs,c.mouthKey);if(!f)return;t.markRendered(c.displayAtMs,c.mouthKey,c.label,c.mouthPath,f),ft()?.onBufferPrefetched()}finally{r.delete(c.mouthKey)}},Cs),a=c=>{for(const f of c)t.has(f.displayAtMs,f.mouthKey)||r.has(f.mouthKey)||o.isQueuedOrInflight(0,f.mouthKey)||(r.add(f.mouthKey),o.enqueue({...f,displayAtMs:0,drawKey:f.mouthKey,diffs:{mouthPath:f.mouthPath,expressionPath:null}}))},u=(c,f,w,T=On)=>{if(!e.supportsBufferedPlayback)return;const h=Math.max(0,f-Vt*4),I=ms(c,h,f+T,w,Vt,n);a(I)},d=(c,f)=>{i=c,s=f},l=(c,f)=>!(i!==c||s!==f);return{reset(){t.reset(),o.reset(),r.clear(),Ue(n),i="",s=null,ft()?.onBufferReset()},setHoldPp(c){n.holdPp=c},markExternallyDisplayed(c,f){d(c.split("|")[0]??c,f)},warmupTick(c){e.supportsBufferedPlayback&&u(c.queue,0,c.availablePaths,Math.max(Nr,On))},isWarmupReady(c,f=Nr){if(!e.supportsBufferedPlayback)return!0;const{ready:w,total:T}=Oo(t,c.queue,0,f,c.availablePaths,n);return T===0?!1:w/T>=Rs},getBufferedFrameCount:()=>t.size(),tick(c){n.holdPp=c.playbackState.holdPp===!0;const f=ft();f?.onBufferTick(),u(c.queue,c.elapsedMs,c.availablePaths),t.pruneBefore(c.elapsedMs-On);const w=xr(c.queue,c.elapsedMs,c.availablePaths,n),T=wn(w.diffPath),h=zt({mouthPath:w.diffPath,expressionPath:c.expressionPath},c.expressionDrawKey),I=()=>(d(T,c.expressionPath),f?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!0});if(l(T,c.expressionPath)||c.playbackState.lastDrawnKey===h)return I();const H=t.findForMouthKey(T,c.elapsedMs,Vt);return H&&c.expressionPath!=null?(f?.onBufferHit(),{usedBuffer:!1,underrun:!1,held:!1}):H?(e.blitBitmap(c.canvas,H.bitmap),d(H.mouthKey,c.expressionPath),c.playbackState.lastDrawnKey=h,c.onStatus({diffPath:H.mouthPath,label:H.label}),c.onDisplayed(h,H.mouthPath,H.label),f?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!1}):(f?.onBufferUnderrun(),{usedBuffer:!1,underrun:!0,held:!1})}}}const Vo=`
5
+ `);vt=Ve.pop()??"";for(const We of Ve)await Ct(We);if(qt){vt.trim()&&await Ct(vt.trim()),we===V&&!fe.signal.aborted&&j&&S.markStreamComplete(r);break}}}catch(mt){if(Mt?.cancel(),g.onBodyIdleCancelled?.(),Pt(),fe.signal.aborted||!j)return;console.error("[realtimeVoice] avatar_speak failed:",mt),e("error"),ne()}finally{P===fe&&(P=null)}},J=w=>{const D=so(w);if(!D){console.warn("[realtimeVoice] server message with no payload",w);return}const oe=String(D.type??"unknown");switch(oe!=="avatar_metadata"&&oe!=="avatar_audio_chunk"&&oe!=="avatar_lipsync"&&oe!=="avatar_interrupt"&&oe!=="error"&&console.debug("[realtimeVoice] server message",oe,D),oe){case"avatar_metadata":m(D);break;case"avatar_audio_chunk":F(D);break;case"avatar_lipsync":te(D);break;case"avatar_interrupt":K(D);break;case"error":{const fe=String(D.message??"Voice session error");console.error("[realtimeVoice] server error:",fe),e("error"),ne();break}case"avatar_speak":C(D);break}},T=()=>y||(E=new ro,y=new Ks.PipecatClient({transport:new wn.WebSocketTransport({mediaManager:E,serializer:new to,recorderSampleRate:Mn,playerSampleRate:Pn}),enableCam:!1,enableMic:!0,callbacks:{onBotReady:()=>{p=!0,e("idle"),ne()},onDisconnected:()=>{p=!1,b()},onError:w=>{const D=typeof w=="object"&&w!==null&&"data"in w?String(w.data??w):String(w);console.error("[realtimeVoice]",D,w),e("error"),ne()},onTransportStateChanged:w=>{w==="error"&&(e("error"),ne())},onServerMessage:w=>{$(w)},onUserStartedSpeaking:()=>{},onBotStartedSpeaking:()=>{se(),X("bot_started")},onBotStoppedSpeaking:()=>{j&&ke()},onUserTranscript:w=>{String(w.text??""),g.onUserTranscript?.(w.text,!!w.final)},onBotOutput:w=>{g.onBotOutput?.(w.text)}}}),y);return{setDeveloperToken:w=>{},setTtsEngineId:w=>{c=w,S.setStreamTtsEngineId(w)},getTtsEngineId:()=>c,speak:async(w,D)=>{const oe=w.trim();if(oe){if(!y||!p)throw new Error("Realtime voice is not connected. Call connect() first.");I(),await y.sendText(oe)}},speakWithReply:async(w,D)=>{throw new Error("speakWithReply is not available on the voice session; use AiTwin.speakWithReply()")},stop:()=>{P?.abort(),P=null,V+=1,se(),I(),e("idle"),ne()},connect:async w=>{w&&(g={...g,...w});const D=lt(g.ttsEngineId,g.voiceId);if(D.ttsEngineId&&(c=D.ttsEngineId,S.setStreamTtsEngineId(c)),g={...g,ttsEngineId:c,...D.voiceId?{voiceId:D.voiceId}:{}},!g.authToken?.trim())throw new Error("Voice connect requires authToken (same JWT as SSE Authorization Bearer).");e("loading");const oe=T();try{await oe.initDevices()}catch(we){throw p=!1,e("idle"),ne(),rr(we)?new Error("Microphone access denied"):we instanceof Error?we:new Error("Failed to initialize microphone")}const fe=Ts({...g,ttsEngineId:c});console.info("[realtimeVoice] connecting (avatar_audio_chunk RTVI):",fe);try{await oe.connect({wsUrl:fe})}catch(we){if(p=!1,e("error"),ne(),rr(we))throw e("idle"),new Error("Microphone access denied");const ge=we instanceof Error?we.message:"Realtime voice connect failed (WebSocket 101 only means upgrade OK — check authToken/origin/RTVI handshake)";throw new Error(`${ge} — ${fe}`)}p=!0,e("idle"),ne()},disconnect:async()=>{if(Re(),Z=!1,Q=!1,_.length=0,x=!1,P?.abort(),P=null,V+=1,se(),y)try{await y.disconnect()}catch(w){console.error("[realtimeVoice] disconnect failed:",w)}p=!1,b()},isConnected:()=>p,unlockAudio:async()=>{await S.primeAudioContext()},getVisemeQueue:()=>r,getWordQueue:()=>n,getFullVisemeQueue:()=>i,getFullWordQueue:()=>s,getSentenceEmotions:()=>a,getStreamMood:()=>l,getPlaybackElapsedMs:H,isSpeaking:()=>S.isSpeaking(),isWarmingUp:()=>S.isWarmingUp(),releaseWarmupHold:()=>S.releaseWarmupHold(),releasePlaybackHold:()=>S.releaseStartHold(),setLipsyncWarmupHold:(w,D)=>{D&&(ze=D),S.setLipsyncWarmupHoldEnabled(w)},getVoiceStream:()=>S.getVoiceStream(),setMuted:w=>{S.setMuted(w)},isMuted:()=>S.isMuted(),setPlaybackSpeed:w=>{S.setPlaybackSpeed(w)},getPlaybackSpeed:()=>S.getPlaybackSpeed(),subscribe:w=>(B.add(w),()=>B.delete(w))}}function Es(e,t,r){return{width:e.crop?.source_width??t,height:e.crop?.source_height??r}}function xs(e,t){const r=e.crop;return{x:t?.source_x??r?.x??0,y:t?.source_y??r?.y??0,width:t?.source_w??r?.width??e.frame_width??0,height:t?.source_h??r?.height??e.frame_height??0}}function Is(e){return e?(e.w??0)>0&&(e.h??0)>0:!1}function Ut(e,t){return`${e}/${t}_minus_sil.png`}const As=5;function Wr(e){const t=e?.composite_threshold;if(typeof t=="number"&&t>0)return t;const r=e?.crop?.content_threshold;return typeof r=="number"&&r>0?r:As}const oo=["aa","E","I","O","U","PP","FF","DD","SS","TH","CH","RR","kk","nn"],mn=["t01_0.25","t02_0.50","t03_0.75"],co=mn.length,ci=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 li(e,t){return`${e}__${t}`}function ui(e,t){return`pairs/${e}/${t}_minus_sil.png`}function Wt(e){return`${e}_minus_sil.png`}function Cn(e,t){if(t.has(e))return e;const r=/^pairs\/([^/]+)\//.exec(e);if(!r)return null;const n=r[1].split("__")[1];if(!n||n==="sil")return null;const i=Wt(n);return t.has(i)?i:null}function Rs(e,t){return e.filter(r=>t.has(r))}function lo(e,t,r){const n=Fn(e,t);return Rs(n,r).length>0}function Fn(e,t){if(e===t)return[];const r=[],n=li(e,t);if(ci.has(n)){for(const s of mn)r.push(ui(n,s));return r}const i=li(t,e);if(ci.has(i)){for(let s=co-1;s>=0;s--)r.push(ui(i,mn[s]));return r}return[]}function uo(e){return e<16?[1]:e<24?[1]:e<35?[0,1,2]:[0,1,2]}function fo(e,t){return uo(t).map(n=>e[n]).filter(n=>n!=null)}function mo(e,t,r,n){if(n<=0)return 0;const s=Math.max(1,r-t)/n,o=e-t,a=Math.floor(o/s);return Math.min(n-1,Math.max(0,a))}function Ms(e,t,r){if(!r)return`${e}/${t}`;const n=t.split("/").pop()??t,i=n.includes(".")?n.slice(0,n.lastIndexOf(".")):n;return`${e}/${i}.bin`}const ho=[.32,.24,.16,.08,0],po=ho.map(e=>`eyes_${e.toFixed(2)}`),go=["eyes_0.32","eyes_0.16","eyes_0.00"],wo=["eyes_0.32","eyes_0.16","eyes_0.08","eyes_0.00"],Xe=2,yo=-20,Ir=16,Ps={fear:-20,anger:-20,sad:-10,neutral:0,love:0,happy:0,disgust:10};function nr(e){return`brow_${e}`}function It(e){return Ps[e]}function rt(e){return Math.max(yo,Math.min(Ir,e))}function vo(e,t){if(e===t)return[];const r=e<t,n=r?Xe:-Xe,i=[];let s=e;if(s%Xe!==0){const o=r?Math.ceil(s/Xe)*Xe:Math.floor(s/Xe)*Xe,a=rt(o);if(r?a>=t:a<=t)return[t];s=a,i.push(s)}for(;;){const o=s+n;if(r?o>=t:o<=t){t!==s&&i.push(t);break}s=o,i.push(s)}return i}function di(e){const t=rt(e);if(t%Xe===0)return[t];const r=Math.floor(t/Xe)*Xe,n=Math.min(Ir,r+Xe),i=rt(r);return t-i<=n-t?i===n?[i]:[i,n]:i===n?[n]:[n,i]}const _o=["fear","anger","sad","neutral","love","happy","disgust"],bo={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 ct(e,t="neutral"){const r=String(e??"").trim().toLowerCase();return r?bo[r]??t:t}function Cs(e){return e===0?null:Ut(nr(e),"eyes_standard")}function Fs(e){return Cs(It(e))}const So={[-20]:"anger",[-10]:"sad",0:"neutral",10:"disgust"};function Bn(e,t){if(!e)return null;if(t(e))return e;const r=e.match(/^brow_(-?\d+)\/(eyes_[^/]+)_minus_sil\.png$/);if(r){const i=Number(r[1]),s=r[2];for(const a of di(i)){if(a===i)continue;const f=Ut(nr(a),s);if(t(f))return f}const o=So[i];if(o){const a=Ut(o,s);if(t(a))return a}return null}const n=e.match(/^(fear|anger|sad|neutral|love|happy|disgust)\/(eyes_[^/]+)_minus_sil\.png$/);if(n){const i=n[1],s=n[2],o=It(i);for(const a of[o,...di(o)]){const f=Ut(nr(a),s);if(t(f))return f}}return null}function fi(e,t){const r=nr(It(e));return!t||t==="eyes_standard"?Fs(e):e==="neutral"&&t==="eyes_standard"?null:Ut(r,t)}function To(e,t){const r=[];for(const n of t)r.push(fi(e,n));for(let n=t.length-2;n>=0;n--)r.push(fi(e,t[n]));return r.push(Fs(e)),r}function ko(e){return Ut(nr(e),"eyes_standard")}function Eo(e,t){return vo(e,t).map(ko)}const xo=6;function Io(e,t){for(const r of e)if(t>=r.wtime&&t<r.wtime+r.wduration)return r;return null}function Ao(e){const t=rt(e);return t>=Ir?Ir:rt(t+xo)}function Ro(e,t,r){const n=rt(r);return Io(t,e)?.emphasis?Ao(n):n}function mi(e){if(!e)return 0;const t=e.match(/^brow_(-?\d+)\//);if(!t?.[1])return null;const r=Number.parseInt(t[1],10);return Number.isFinite(r)?rt(r):null}function tt(e,t){return e+Math.random()*(t-e)}function hi(){return tt(14,32)}function Mo(e){if(e)return{holdMinMs:10,holdMaxMs:18,closedExtraMs:0};const t=Math.random();return t<.18?{holdMinMs:38,holdMaxMs:62,closedExtraMs:tt(40,90)}:t<.42?{holdMinMs:26,holdMaxMs:44,closedExtraMs:tt(12,36)}:t<.82?{holdMinMs:14,holdMaxMs:28,closedExtraMs:Math.random()<.35?tt(8,22):0}:{holdMinMs:10,holdMaxMs:18,closedExtraMs:0}}function pi(e,t){const r=tt(e.holdMinMs,e.holdMaxMs);return t?r+e.closedExtraMs:r}function Po(e={}){const{initialDelayMs:t=800+Math.random()*1200,intervalMinMs:r=2200,intervalMaxMs:n=5800,doubleBlinkChance:i=.18,doubleBlinkGapMinMs:s=120,doubleBlinkGapMaxMs:o=220,fullBlinkChance:a=.75,postEmotionChangeDelayMs:f=380,minDwellMs:h=550}=e;let l="neutral",c="neutral",p=0,y=0,E=0,g={kind:"idle",nextBlinkAt:performance.now()+t},M=null,W="__eyes_open__|neutral|brow:0";function B(P=l){W=`${M??"__eyes_open__"}|${P}|brow:${y}`}function _(P,V=l){M=P;const Z=mi(P);Z!=null?y=Z:P==null&&(y=0),B(V)}function x(P){return Cs(P)}function N(P,V,Z){const Q=rt(V),ue=rt(Z);if(p=ue,Q===ue){_(x(ue));return}const ae=[...Eo(Q,ue),x(ue)];g={kind:"browBlend",paths:ae,index:0,holdUntil:P+hi(),targetBrow:ue},_(ae[0]??null)}function j(P,V){g={kind:"idle",nextBlinkAt:P+tt(r,n)},c=V,_(x(p),V)}function G(P,V,Z){const Q=Z?go:Math.random()<a?po:wo,ue=Mo(Z),ae=Q.length-1;g={kind:"playing",paths:To(V,Q),index:0,holdUntil:P+pi(ue,ae===0),after:"idle",blinkEmotion:V,pace:ue,closedFrameIndex:ae},c=V,_(g.paths[0]??null,V)}function ie(P){if(g.kind==="browBlend"){for(;P>=g.holdUntil&&g.index<g.paths.length-1;)g.index+=1,g.holdUntil=P+hi();const V=g.paths[g.index]??null;_(V),P>=g.holdUntil&&g.index>=g.paths.length-1&&(y=g.targetBrow,p=g.targetBrow,_(x(g.targetBrow)),g={kind:"idle",nextBlinkAt:P+f});return}if(g.kind==="idle"){_(x(p),c),P>=g.nextBlinkAt&&G(P,c,!1);return}if(g.kind==="doublePause"){_(x(p),g.blinkEmotion),P>=g.resumeAt&&G(P,g.blinkEmotion,!0);return}if(g.kind==="playing"){for(;P>=g.holdUntil&&g.index<g.paths.length-1;)g.index+=1,g.holdUntil=P+pi(g.pace,g.index===g.closedFrameIndex);if(_(g.paths[g.index]??null,g.blinkEmotion),P>=g.holdUntil&&g.index>=g.paths.length-1){if(g.after==="resumeIdle"){j(P+f,l);return}if(g.after==="doublePause"){g={kind:"doublePause",resumeAt:P+tt(s,o),blinkEmotion:g.blinkEmotion},_(x(p),g.blinkEmotion);return}if(g.after==="idle"&&Math.random()<i){g={kind:"doublePause",resumeAt:P+tt(s,o),blinkEmotion:g.blinkEmotion},_(x(p),g.blinkEmotion);return}j(P,g.blinkEmotion)}}}return{advance:ie,setTargetEmotion(P,V){const Z=ct(P,l);if(Z===l)return;const Q=performance.now();!V?.force&&h>0&&!(l==="neutral"&&Z!=="neutral")&&Q-E<h||(l=Z,c=Z,E=Q)},setTargetEyebrow(P){const V=rt(P);if(V===p)return;const Z=performance.now(),Q=g.kind==="browBlend"?mi(M)??y:y;p=V,!(V===Q&&g.kind!=="browBlend")&&(g.kind==="playing"||g.kind==="doublePause"||N(Z,Q,V))},snapToEmotion(P){const V=ct(P),Z=It(V);l=V,c=V,p=Z,y=Z,E=performance.now(),g={kind:"idle",nextBlinkAt:performance.now()+tt(4e3,7e3)},_(x(Z),V)},getTargetEmotion:()=>l,getTargetEyebrow:()=>p,getExpressionPath:()=>M,getDrawKey:()=>W,reset(){l="neutral",c="neutral",p=0,y=0,E=0,j(performance.now()+tt(r,n),"neutral")}}}function Co(){const e=document.createElement("video");e.muted=!0,e.playsInline=!0,e.preload="auto",e.setAttribute("playsinline",""),e.loop=!0;let t=!1,r=null,n="";const i=()=>{r&&(URL.revokeObjectURL(r),r=null)};return{async load(s){t&&n===s||(i(),t=!1,n=s,s.startsWith("blob:")&&(r=s),await new Promise((o,a)=>{const f=()=>{const h=e.duration;if(!Number.isFinite(h)||h<=0){a(new Error(`Idle video has invalid duration: ${s}`));return}t=!0,e.currentTime=0,o()};e.addEventListener("loadeddata",f,{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())},setLooping(s){e.loop=s},restart(){t&&(e.currentTime=0)},dispose(){e.pause(),e.removeAttribute("src"),e.load(),i(),t=!1,n=""}}}const Fo=50,Bs=400;function Bo(e,t,r){return e.filter(n=>{const i=n.queueIndex??-1;return i>=t&&i<=r})}function Do(e,t){const r=[];for(const n of e){const i=Bo(t,n.start_word,n.end_word);if(i.length===0)continue;const s=i[0],o=i[i.length-1];r.push({sentence:n,startMs:Math.max(0,s.wtime-Fo),endMs:o.wtime+o.wduration+Bs})}return r.sort((n,i)=>n.startMs-i.startMs)}function Lo(e,t,r,n="neutral"){const i=ct(n);if(t.length===0)return i;if(r.length===0||e<r[0].wtime)return ct(t[0]?.emotion,i);const s=Do(t,r);let o=null;for(const h of s)e>=h.startMs&&e<=h.endMs&&(o=h);if(o)return ct(o.sentence.emotion,i);const a=r[r.length-1],f=a.wtime+a.wduration;return e>f+Bs?ct(t[t.length-1]?.emotion,i):i}function Dn(e,t,r,n,i=As){const s=new OffscreenCanvas(r,n),o=s.getContext("2d",{willReadFrequently:!0});o.drawImage(e,0,0,r,n);const a=o.getImageData(0,0,r,n),f=o.createImageData(r,n);f.data.set(a.data);const l=new OffscreenCanvas(r,n).getContext("2d",{willReadFrequently:!0});for(const c of t){l.clearRect(0,0,r,n),l.drawImage(c,0,0,r,n);const p=l.getImageData(0,0,r,n);for(let y=0;y<f.data.length;y+=4){const E=p.data[y],g=p.data[y+1],M=p.data[y+2];p.data[y+3]>0&&Math.max(E,g,M)>i&&(f.data[y]=E,f.data[y+1]=g,f.data[y+2]=M,f.data[y+3]=255)}}return o.putImageData(f,0,0),s}let kt=null,jt=null;const Ar=new Map;function Oo(){kt=null,jt=null,Ar.clear()}ji(Oo);function No(e){return e??jt??void 0}function Ln(e){return new Promise((t,r)=>{const n=new Image;n.decoding="async",n.onload=()=>t(n),n.onerror=()=>r(new Error(`Failed to load image: ${e}`)),n.src=e})}async function Uo(e){return $t()?Ki(await yt(tr(),e??"")):Ln(tr())}async function gi(e,t,r,n){const i=r?await Gi(e,n):await fetch(e).then(h=>{if(!h.ok)throw new Error(`Failed to load ${e}`);return h.json()}),s=i.sheets?.[0];if(!s?.path)throw new Error(`${e} has no sheets[0].path`);const o=r?await _a(await yt(Ms(t,s.path,r),n??"")):await Ln(`${t}/${s.path}`),a=new Map;for(const h of i.cells??[])h.path&&a.set(h.path,h);const f=new Map;for(const h of i.sheets??[])f.set(h.index,h);return{atlas:o,atlasMeta:i,cellByPath:a,sheetByIndex:f,diffBase:t}}async function hn(e){const t=No(e),r=$t();if(r&&!t)throw new Error("Encrypted assets enabled but no key provided");if(kt&&(!r||jt===(t??null))){const s=await kt;return{...Ht(s),visemePaths:[...s.viseme.cellByPath.keys()]}}jt=t??null,Ar.clear();const n=Hi();kt=(async()=>{const s=await Uo(t),o=await gi($i(),n,r,t);let a=null;try{a=await gi(zi(),n,r,t)}catch{a=null}return{sil:s,viseme:o,expression:a}})();const i=await kt;return{...Ht(i),visemePaths:[...i.viseme.cellByPath.keys()]}}async function On(e){if(await hn(e),!kt)throw new Error("Assets not loaded");return kt}function Ht(e){return Es(e.viseme.atlasMeta,e.sil.naturalWidth,e.sil.naturalHeight)}function Vo(e,t){const r=document.createElement("canvas");return r.width=t.w,r.height=t.h,r.getContext("2d",{willReadFrequently:!0}).drawImage(e.atlas,t.x,t.y,t.w,t.h,0,0,t.w,t.h),r}async function Rr(e,t,r){const n=`${t.diffBase}::${r}`,i=Ar.get(n);if(i)return i;const s=(async()=>{const o=t.cellByPath.get(r);if(!o)throw new Error(`No atlas cell for path: ${r}`);const a=xs(t.atlasMeta,o),f=Ht(e);if(Is(o)){const c=Vo(t,o),p=document.createElement("canvas");p.width=f.width,p.height=f.height;const y=p.getContext("2d");return y.fillStyle="#000",y.fillRect(0,0,f.width,f.height),y.drawImage(c,a.x,a.y),p}const h=`${t.diffBase}/${r}`,l=await Ln(h);if(l.naturalWidth===f.width&&l.naturalHeight===f.height)return l;throw new Error(`Diff PNG wrong size for ${r}`)})();return Ar.set(n,s),s}async function en(e,t,r,n,i,s){if(i){const{width:y,height:E}=i;if(s&&!s()||t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA)return;const g=document.createElement("canvas");g.width=y,g.height=E;const M=g.getContext("2d");if(M.clearRect(0,0,y,E),M.drawImage(t,0,0,y,E),s&&!s())return;(e.width!==y||e.height!==E)&&(e.width=y,e.height=E);const W=e.getContext("2d");W.clearRect(0,0,y,E),W.drawImage(g,0,0);return}const o=await On(),a=Wr(o.viseme.atlasMeta),{width:f,height:h}=Ht(o);(e.width!==f||e.height!==h)&&(e.width=f,e.height=h);const l=[],c=e.getContext("2d");if(c.clearRect(0,0,f,h),t.readyState<HTMLMediaElement.HAVE_CURRENT_DATA){const y=o.sil;c.drawImage(y,0,0,f,h);return}if(l.length===0){c.drawImage(t,0,0,f,h);return}const p=Dn(t,l,f,h,a);c.drawImage(p,0,0)}async function pn(e,t,r){const n=await On(jt??void 0),i=Wr(n.viseme.atlasMeta),{width:s,height:o}=Ht(n);(e.width!==s||e.height!==o)&&(e.width=s,e.height=o);const a=[];if(t.mouthPath){const l=new Set(n.viseme.cellByPath.keys()),c=Cn(t.mouthPath,l)??(l.has(t.mouthPath)?t.mouthPath:null);c&&a.push(await Rr(n,n.viseme,c))}if(t.expressionPath&&n.expression){const l=Bn(t.expressionPath,c=>n.expression.cellByPath.has(c));l&&a.push(await Rr(n,n.expression,l))}const f=e.getContext("2d");if(f.clearRect(0,0,s,o),a.length===0){f.drawImage(n.sil,0,0,s,o);return}const h=Dn(n.sil,a,s,o,i);f.drawImage(h,0,0)}async function Wo(e,t){const r=await On(jt??void 0),n=Wr(r.viseme.atlasMeta),{width:i,height:s}=Ht(r),o=[];if(e.mouthPath){const l=new Set(r.viseme.cellByPath.keys()),c=Cn(e.mouthPath,l)??(l.has(e.mouthPath)?e.mouthPath:null);c&&o.push(await Rr(r,r.viseme,c))}if(e.expressionPath&&r.expression){const l=Bn(e.expressionPath,c=>r.expression.cellByPath.has(c));l&&o.push(await Rr(r,r.expression,l))}const a=new OffscreenCanvas(i,s),f=a.getContext("2d");if(o.length===0)return f.drawImage(r.sil,0,0,i,s),a.transferToImageBitmap();const h=Dn(r.sil,o,i,s,n);return f.drawImage(h,0,0),a.transferToImageBitmap()}async function jo(e){await pn(e,{mouthPath:null,expressionPath:null})}const br={fontFamily:"system-ui, -apple-system, sans-serif",fontSize:"clamp(0.875rem, 2.5vw, 1.125rem)",color:"rgba(255,255,255,0.85)"};function Ho(e){return e.length===0?"":e.map(t=>t.word).join(" ")}function $o(e){if(!e)return{enabled:!1,style:br};const t=e===!0?{}:e;return{enabled:!0,style:{fontFamily:t.fontFamily??br.fontFamily,fontSize:t.fontSize??br.fontSize,color:t.color??br.color}}}const zo={position:"absolute",bottom:0,left:0,right:0,display:"flex",justifyContent:"center",padding:"0.75rem 1rem",pointerEvents:"none"},Go={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"},Ko={display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden",maxWidth:"100%",margin:0};function qo({text:e,style:t}){return R.jsx("div",{style:zo,"aria-live":"polite","aria-atomic":"true",children:R.jsx("div",{style:{...Go,fontFamily:t.fontFamily,fontSize:t.fontSize,color:t.color},children:R.jsx("p",{style:Ko,children:e})})})}const Yo={inset:0,overflow:"hidden",pointerEvents:"none",position:"absolute",zIndex:3},Qo={filter:"blur(22px)",height:"100%",inset:0,objectFit:"cover",objectPosition:"top",position:"absolute",transform:"scale(1.08)",width:"100%"},Xo={backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",inset:0,position:"absolute"};function Jo({thumbnailUrl:e}){const[t,r]=u.useState(!1);u.useEffect(()=>{r(!1)},[e]);const n=!!e&&t;return R.jsxs("div",{style:Yo,"aria-hidden":!0,children:[e?R.jsx("img",{src:e,alt:"",style:{...Qo,opacity:n?1:0,transition:"opacity 0.45s ease"},onLoad:()=>r(!0),onError:()=>r(!1)}):null,R.jsx("div",{style:{...Xo,background:n?"rgba(0, 0, 0, 0.28)":"rgba(10, 10, 11, 0.92)"}})]})}let Ds=null;function wi(e){Ds=e}function wt(){return Ds}function Zo(e){return`${e.from}→${e.to}@${e.fromVtime}`}function yi(){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 ec(){let e=yi();const t=new Set,r=new Set,n=new Set;let i="",s=-1,o="";const a=()=>{e=yi(),t.clear(),r.clear(),n.clear(),i="",s=-1,o=""},f=l=>{t.add(l)},h=l=>{l&&n.add(l)};return{reset:a,onRafTickSpeaking(){e.rafTicksSpeaking+=1},onDrawDeduped(){e.rafTicksDeduped+=1},onDrawRequested(){e.drawsRequested+=1},onQueueSuperseded(){e.queueSuperseded+=1},onWorkerStale(){e.workerStale+=1},onTransitionSample(l,c){const p=Zo(l);e.transitionFramesSampled+=1,p!==i&&(i=p,s=-1,o!==p&&(o=p,e.rifeFramesOmittedByGap+=l.omittedByGap)),c&&r.add(c),s>=0&&l.frameIdx>s+1&&(e.transitionFramesMissed+=l.frameIdx-s-1),s=l.frameIdx},onBufferTick(){e.bufferTicks+=1},onBufferHit(){e.bufferHits+=1},onBufferUnderrun(){e.bufferUnderruns+=1},onBufferPrefetched(){e.bufferPrefetched+=1},onBufferReset(){},onDrawDisplayed(l,c){if(e.drawsDisplayed+=1,l.transitionMeta){e.transitionFramesDisplayed+=1;const y=l.transitionMeta;f(y.fromVtime),f(y.toVtime),h(l.mouthPath);return}if(l.label.includes("→")){e.transitionFramesDisplayed+=1;return}const p=l.label.trim();if(!(!p||p==="sil")){for(const y of c)if(y.viseme===p&&l.elapsedMs>=y.vtime&&l.elapsedMs<y.vtime+y.vduration){f(y.vtime);break}}},snapshot(l,c){let p=0,y=0;for(const B of l)if(B.viseme!=="sil"){if(B.vtime>=c)break;p+=1,t.has(B.vtime)&&(y+=1)}const E=p>0?Math.round(y/p*100):100,g=e.queueSuperseded+e.workerStale+Math.max(0,e.drawsRequested-e.drawsDisplayed),M=p-y,W=e.bufferTicks>0?Math.round(e.bufferHits/e.bufferTicks*100):100;return{...e,bufferHitRate:W,renderLoss:g,visemeSlotsTotal:p,visemeSlotsCovered:y,visemeCoveragePct:E,transitionFramesUniqueSampled:r.size,transitionFramesUniquePainted:n.size,drawsDeduped:e.rafTicksDeduped,renderSkips:e.rafTicksDeduped+g,visemesShown:y,visemesSkipped:M,rifeTransitionFramesSkipped:e.transitionFramesMissed}}}}const Ls=yn,tc=500,vi=500,rc=450,tn=.05,nc=100,ic=600,Os="__sil__";function _i(e){return e.lastDrawnKey?e.lastDrawnKey.split("|")[0]===Os:!1}function Nn(){return{lastDrawnKey:""}}function $e(e){e.lastDrawnKey="",e.transitionCache=void 0}function sc(e,t){if(t?.transitionCache&&t.transitionCache.queueLength===e.length)return t.transitionCache.transitions;const r=hs(e);return t&&(t.transitionCache={queueLength:e.length,transitions:r}),r}function ac(e,t){let r="sil";for(const n of e)n.viseme!=="sil"&&(t!=null&&n.vtime>t||(r=n.viseme));return r}function oc(e,t,r,n=120){if(r!=="sil")return r;const i=bs(e,t,n);return i!=="sil"?i:ac(e,t)}function cc(e,t){return e==="sil"?!1:t?lo(e,"sil",t):Fn(e,"sil").length>0}function lc(){return Ls+ic}function Mr(e){return e??Os}function Un(e,t,r,n,i=nc){if(e.length===0)return{diffPath:null,label:"sil"};if(t>=Tt(e))return{diffPath:null,label:"sil"};const s=n?.holdPp===!0,o=sc(e,n),a=Ya(o,t,s);if(a){const l=ps(a.fromVtime,a.toVtime,a.from,a.to,s);if(t>=l.transStart&&t<l.transEnd){let c=Fn(a.from,a.to);r&&(c=Rs(c,r));const p=fo(c,l.effectiveGapMs);if(p.length>0){const y=mo(t,l.transStart,l.transEnd,p.length);return{diffPath:p[y]??p[p.length-1],label:`${a.from}→${a.to}`,transitionMeta:{from:a.from,to:a.to,fromVtime:a.fromVtime,toVtime:a.toVtime,frameIdx:y,frameCount:p.length,fullFrameCount:c.length,omittedByGap:Math.max(0,c.length-p.length)}}}return{diffPath:Wt(a.to),label:a.to}}}const f=Or(e);let h=us(f,t);return h==="sil"&&(h=bs(e,t,i)),h==="sil"?{diffPath:null,label:"sil"}:{diffPath:Wt(h),label:h}}function ir(e,t){const r=t??Mr(e.expressionPath);return`${Mr(e.mouthPath)}|${r}`}function bi(e,t,r,n,i,s,o,a,f,h){const l=Un(t,r,f,s),c={mouthPath:l.diffPath,expressionPath:n},p=ir(c,i),y=wt();if(l.transitionMeta&&y?.onTransitionSample(l.transitionMeta,l.diffPath),p===s.lastDrawnKey){y?.onDrawDeduped();return}y?.onDrawRequested(),a(l),s.lastDrawnKey=p,o(e,c,p,E=>{E===p&&(s.lastDrawnKey=p)})}function rn(e,t,r,n,i,s,o=null,a=null){const f={mouthPath:a,expressionPath:t},h=o!=null?`|idle@${Math.round(o*1e3)}`:"",l=ir(f,r)+h;!(o!=null)&&l===n.lastDrawnKey||(s(o!=null?t?"idle · blink":"idle":t?"blink":"sil"),i(e,f,l,p=>{p===l&&(n.lastDrawnKey=l)}))}function Ns(e,t,r,n,i=er,s){if(r<=t||e.length===0)return[];const o=s??Nn(),a=[];let f="";for(let h=t;h<r;h+=i){const l=Un(e,h,n,o),c=Mr(l.diffPath);c!==f&&(f=c,a.push({displayAtMs:h,mouthPath:l.diffPath,mouthKey:c,label:l.label}))}return a}const uc=3;function Vn(e){let t=0;const r=[];let n=!1,i=!1;const s=async()=>{if(!n){n=!0;try{for(;r.length>0;){const a=r.shift(),f=++t;await e(a.diffs,f,a)&&f===t&&a.onDisplayed?.(a.drawKey)}}finally{n=!1,r.length>0&&s()}}},o=()=>{i||(i=!0,queueMicrotask(()=>{i=!1,s()}))};return{enqueue(a,f,h){const l=r.findIndex(c=>c.drawKey===f);l>=0?r[l]={diffs:a,drawKey:f,onDisplayed:h}:(r.length>=uc&&(r.shift(),wt()?.onQueueSuperseded()),r.push({diffs:a,drawKey:f,onDisplayed:h})),o()},reset(){t+=1,r.length=0},isLatestSeq(a){return a===t},getLatestSeq(){return t}}}function dc(e,t=2){const r=[],n=new Set;let i=0,s=!1,o=0;const a=(h,l)=>`${h}|${l}`,f=async()=>{if(!s){s=!0;try{for(;i<t&&r.length>0;){const h=r.shift(),l=a(h.displayAtMs,h.drawKey);if(n.has(l))continue;n.add(l),i+=1;const c=o;try{await e(h)}finally{if(n.delete(l),i-=1,c!==o)return}}}finally{s=!1,r.length>0&&i<t&&f()}}};return{enqueue(h){const l=a(h.displayAtMs,h.drawKey);n.has(l)||r.some(c=>a(c.displayAtMs,c.drawKey)===l)||(r.push(h),f())},isQueuedOrInflight(h,l){const c=a(h,l);return n.has(c)?!0:r.some(p=>a(p.displayAtMs,p.drawKey)===c)},reset(){o+=1,r.length=0,n.clear(),i=0},pendingCount(){return r.length+i}}}function fc(){const e=new Map,t=r=>{r.bitmap.close()};return{has(r,n){return e.has(n)},markRendered(r,n,i,s,o){const a=e.get(n);a&&t(a),e.set(n,{displayAtMs:r,mouthKey:n,label:i,mouthPath:s,bitmap:o})},findForMouthKey(r){return e.get(r)??null},removeThrough(r){},pruneBefore(r){},reset(){for(const r of e.values())t(r);e.clear()},size(){return e.size}}}function mc(e,t,r,n,i,s){const o=Ns(t,r,n,i,er,s);if(o.length===0)return{ready:0,total:0};let a=0;for(const f of o)e.has(f.displayAtMs,f.mouthKey)&&(a+=1);return{ready:a,total:o.length}}function hc(e){const t=fc(),r=Nn(),n=new Set;let i="",s=null;const o=dc(async c=>{try{if(!e.supportsBufferedPlayback)return;const p=await e.compositePrefetchFrame(c.diffs,c.mouthKey);if(!p)return;t.markRendered(c.displayAtMs,c.mouthKey,c.label,c.mouthPath,p),wt()?.onBufferPrefetched()}finally{n.delete(c.mouthKey)}},na),a=c=>{for(const p of c)t.has(p.displayAtMs,p.mouthKey)||n.has(p.mouthKey)||o.isQueuedOrInflight(0,p.mouthKey)||(n.add(p.mouthKey),o.enqueue({...p,displayAtMs:0,drawKey:p.mouthKey,diffs:{mouthPath:p.mouthPath,expressionPath:null}}))},f=(c,p,y,E=Jr)=>{if(!e.supportsBufferedPlayback)return;const g=Math.max(0,p-er*4),M=Ns(c,g,p+E,y,er,r);a(M)},h=(c,p)=>{i=c,s=p},l=(c,p)=>!(i!==c||s!==p);return{reset(){t.reset(),o.reset(),n.clear(),$e(r),i="",s=null,wt()?.onBufferReset()},setHoldPp(c){r.holdPp=c},markExternallyDisplayed(c,p){h(c.split("|")[0]??c,p)},warmupTick(c){e.supportsBufferedPlayback&&f(c.queue,0,c.availablePaths,Math.max(Jn,Jr))},isWarmupReady(c,p=Jn){if(!e.supportsBufferedPlayback)return!0;const{ready:y,total:E}=mc(t,c.queue,0,p,c.availablePaths,r);return E===0?!1:y/E>=ra},getBufferedFrameCount:()=>t.size(),tick(c){r.holdPp=c.playbackState.holdPp===!0;const p=wt();p?.onBufferTick(),f(c.queue,c.elapsedMs,c.availablePaths),t.pruneBefore(c.elapsedMs-Jr);const y=Un(c.queue,c.elapsedMs,c.availablePaths,r),E=Mr(y.diffPath),g=ir({mouthPath:y.diffPath,expressionPath:c.expressionPath},c.expressionDrawKey),M=()=>(h(E,c.expressionPath),p?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!0});if(l(E,c.expressionPath)||c.playbackState.lastDrawnKey===g)return M();const W=t.findForMouthKey(E,c.elapsedMs,er);return W&&c.expressionPath!=null?(p?.onBufferHit(),{usedBuffer:!1,underrun:!1,held:!1}):W?(e.blitBitmap(c.canvas,W.bitmap),h(W.mouthKey,c.expressionPath),c.playbackState.lastDrawnKey=g,c.onStatus({diffPath:W.mouthPath,label:W.label}),c.onDisplayed(g,W.mouthPath,W.label),p?.onBufferHit(),{usedBuffer:!0,underrun:!1,held:!1}):(p?.onBufferUnderrun(),{usedBuffer:!1,underrun:!0,held:!1})}}}const pc=`
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
- `,Wo=`
33
+ `,gc=`
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) * color.a;
45
45
  finalColor = vec4(color.rgb, keep);
46
46
  }
47
- `;function si(e=5){const t=new we.Filter({glProgram:we.GlProgram.from({vertex:Vo,fragment:Wo,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 jo(e,t,n){return e>n||t>n}function zo(e){return e?e.getParameter(e.MAX_TEXTURE_SIZE):4096}function Ho(e,t){return t!=null&&t>0?Math.floor(t):zo(e)}function $o(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 hs(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 ai(e,t,n,r,i){const s=n?await ns(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,u=async(c,f)=>{const w=ss(t,f,n),T=n?await Ea(await Dt(w,i??"")):await hs(w);if(jo(T.width,T.height,r))return console.info(`[PixiVisemeCompositor] Sheet ${f} (${T.width}x${T.height}) exceeds MAX_TEXTURE_SIZE=${r}; using per-cell crops.`),{mode:"cells",bitmap:T};const h=we.Texture.from(T);return h.source.scaleMode="nearest",{mode:"full",texture:h}};a.set(o.index,await u(o.index,o.path));for(const c of s.sheets??[])c.index!==o.index&&c.path&&a.set(c.index,await u(c.index,c.path));const d=new Map;for(const c of s.cells??[])c.path&&d.set(c.path,c);const l=new Map;for(const c of s.sheets??[])l.set(c.index,c);return{atlasMeta:s,cellByPath:d,sheetByIndex:l,diffBase:t,sheets:a}}async function Ko(e,t={}){const n=new we.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(b){throw n.destroy({removeView:!1}),b}if(n.renderer.type!==we.RendererType.WEBGL)throw n.destroy({removeView:!1}),new Error("Pixi did not initialize a WebGL renderer");const r=Ho(n.renderer.gl,t.maxTextureSize);let i=!1,s=!1,o=!1;const a=n.canvas,u=()=>{i=!0,!s&&!o&&(s=!0,t.onWebGlContextLost?.())};a.addEventListener("webglcontextlost",u);const d=new we.Sprite(we.Texture.EMPTY),l=new we.Sprite(we.Texture.EMPTY);l.visible=!1,l.alpha=0;const c=new we.Sprite(we.Texture.EMPTY),f=new we.Sprite(we.Texture.EMPTY),w=new we.Sprite(we.Texture.EMPTY);w.visible=!1;const T=si(5),h=si(5);c.filters=[T],f.filters=[h],n.stage.addChild(d),n.stage.addChild(l),n.stage.addChild(c),n.stage.addChild(f),n.stage.addChild(w);let I=null,H=null,O=null,v=null,E=null,V=null,L=null,se=842,re=1264,P=null,q=5;const Q=new Map;let ee=null,oe=null,ue=null;const Se=xi(()=>{Q.clear(),V=null,L=null,I=null,P=null}),We=(b,y)=>{se=b,re=y,n.renderer.resize(b,y),(e.width!==b||e.height!==y)&&(e.width=b,e.height=y)},ne=()=>{c.visible=!1,f.visible=!1,c.texture=we.Texture.EMPTY,f.texture=we.Texture.EMPTY,ee=null,oe=null},D=()=>{E=null,l.visible=!1,l.alpha=0},S=()=>{d.visible=!0,d.width=se,d.height=re,d.x=0,d.y=0},J=()=>{l.width=se,l.height=re,l.x=0,l.y=0},X=()=>{w.visible=!1,D(),I&&(d.texture=I,S())},ce=()=>{E&&X()},Y=b=>{if(o||i||!I){X();return}const y=Math.max(0,b);if(!H||y<=0){X();return}ne(),w.visible=!1,d.texture=I,S(),l.texture=H,J(),l.alpha=1,l.visible=!0,E={startMs:performance.now(),durationMs:y},W()},z=(b=performance.now())=>{if(!E)return!1;if(o||i)return ce(),!1;const y=(b-E.startMs)/Math.max(1,E.durationMs);if(y>=1)return X(),W(),!1;const x=Math.min(1,Math.max(0,y)),A=x*x*(3-2*x);return l.alpha=1-A,l.visible=!0,W(),!0},$=()=>{if(O){try{O.resource=null}catch{}O.destroy(),O=null}H&&(H.destroy(!1),H=null),v=null},ve=(b,y)=>{const x=b.cellByPath.get(y);if(!x||!ts(x))return null;const A=`${b.diffBase}::${y}`;let U=Q.get(A);if(!U){const j=x.sheet??0,Z=b.sheets.get(j);if(!Z)return null;let Te,Ae=!1;if(Z.mode==="full")Te=new we.Texture({source:Z.texture.source,frame:new we.Rectangle(x.x,x.y,x.w,x.h)});else{const F=$o(Z.bitmap,x);Te=we.Texture.from(F),Te.source.scaleMode="nearest",Ae=!0}U={texture:Te,ownsSource:Ae},Q.set(A,U)}return{texture:U.texture,cell:x}},ae=(b,y,x,A)=>{if(!A||!x)return b.visible=!1,b.texture=we.Texture.EMPTY,!1;const U=ve(x,A);if(!U)return b.visible=!1,b.texture=we.Texture.EMPTY,!1;const j=es(x.atlasMeta,U.cell);return y.setThreshold(q),b.texture=U.texture,b.x=j.x,b.y=j.y,b.width=U.cell.w,b.height=U.cell.h,b.visible=!0,!0},_=b=>{if(!b||!V)return null;const y=P??new Set(V.cellByPath.keys());return yr(b,y)??(y.has(b)?b:null)},B=b=>{w.visible=!1,X();const y=_(b.mouthPath),x=b.expressionPath&&L?_r(b.expressionPath,A=>L.cellByPath.has(A)):null;y!==ee?(ae(c,T,V,y),ee=y):y?c.visible=!0:c.visible=!1,x!==oe?(ae(f,h,L,x),oe=x):x?f.visible=!0:f.visible=!1},W=()=>{if(!(o||i||document.hidden))try{n.render()}catch{}};return{async loadAssets(b){if(o)return{width:se,height:re,visemePaths:[]};const y=Ht();if(y&&!b)throw new Error("Encrypted assets enabled but no key provided");const x=y?await Aa(await Dt(fn(),b??"")):await hs(fn());I&&I.destroy(!0),I=we.Texture.from(x),I.source.scaleMode="linear";const A=Ei();V=await ai(Ii(),A,y,r,b);try{L=await ai(Ai(),A,y,r,b)}catch(j){console.warn("[PixiVisemeCompositor] expression atlas unavailable:",j),L=null}const U=Zi(V.atlasMeta,x.width,x.height);return We(U.width,U.height),q=En(V.atlasMeta),T.setThreshold(q),h.setThreshold(q),P=new Set(V.cellByPath.keys()),Q.clear(),X(),ne(),W(),{width:U.width,height:U.height,visemePaths:[...V.cellByPath.keys()]}},getVisemeAtlasPaths(){return P},drawLiveFrame(b){o||i||!I||(ce(),B(b),W())},drawIdleVideo(b,y){o||i||document.hidden||y&&!y()||b.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||(E=null,ne(),w.visible=!1,I&&(d.texture=I,S()),!H||v!==b?($(),O=new we.VideoSource({resource:b,autoPlay:!1,updateFPS:0}),O.autoUpdate=!1,H=new we.Texture({source:O}),v=b):H.source.update(),l.texture=H,J(),l.alpha=1,l.visible=!0,W())},beginIdleToSilCrossfade:Y,tickIdleToSilCrossfade:z,finishIdleToSilCrossfade:ce,isIdleToSilCrossfading(){return E!=null},renderSilOnly(){o||i||!I||(ne(),X(),W())},blitBitmap(b){o||i||(ce(),ne(),ue&&(ue.destroy(!0),ue=null),ue=we.Texture.from(b),w.texture=ue,w.visible=!0,w.x=0,w.y=0,w.width=se,w.height=re,d.visible=!1,W())},async compositePrefetchFrame(b){return null},renderFrame:W,isContextLost(){return i},dispose(){if(o)return;o=!0,a.removeEventListener("webglcontextlost",u),Se(),$(),ue&&(ue.destroy(!0),ue=null);for(const{texture:y,ownsSource:x}of Q.values())y.destroy(x);Q.clear(),I&&(I.destroy(!0),I=null);const b=y=>{y.mode==="full"?y.texture.destroy(!0):y.bitmap.close()};if(V)for(const y of V.sheets.values())b(y);if(L)for(const y of L.sheets.values())b(y);T.destroy(!0),h.destroy(!0),n.destroy({removeView:!1},{children:!0,texture:!0})}}}const oi=-1,cn=1e5,ci=new Map;async function Go(e){let t=ci.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),ci.set(e,t)}return new Worker(t,{name:"visemeDiffPreview"})}function qo(){return typeof Worker<"u"&&typeof OffscreenCanvas<"u"}function tr(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 li(e,t){let n=0,r=null;const i=Er(async(s,o)=>(await Zn(),await er(e,s),i.isLatestSeq(o)));return{usesWorker:!1,usesPixi:!1,async loadAssets(s){const o=await Zn(s);return r=o.visemePaths?new Set(o.visemePaths):null,o},getVisemeAtlasPaths(){return r},async renderSilOnly(){n+=1,i.reset(),await mo(e)},drawLiveFrame(s,o,a,u){i.enqueue(o,a,u)},async compositePrefetchFrame(s,o){try{return await fo(s)}catch{return null}},blitBitmap(s,o){tr(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 er(s,{mouthPath:Mt(o),expressionPath:null})},dispose(){n+=1,i.reset()}}}function Yo(e,t,n){let r=null,i=1,s=0,o=!1,a=!1,u=null;const d=new Map,l=new Map;let c=cn;const f=Er(async(O,v,E)=>(d.set(v,{drawKey:E.drawKey,onDisplayed:E.onDisplayed}),await I({type:"drawFrame",diffPath:O.mouthPath,expressionDiffPath:O.expressionPath,liveSeq:v},void 0,!0),!1)),w=O=>{if(O===oi){let V=-1,L;for(const[se,re]of d)se>=V&&(V=se,L=re);V>=0&&d.delete(V),L?.onDisplayed?.(L.drawKey);return}const v=-O,E=d.get(v);d.delete(v),E?.onDisplayed?.(E.drawKey)},T=new Map,h=(O,v)=>{a||!r||r.postMessage(O,[])},I=(O,v,E=!1)=>{if(a)return Promise.resolve();const V=i++;return new Promise((L,se)=>{T.set(V,{resolve:re=>L(re),reject:se,generation:typeof O.generation=="number"?O.generation:void 0,expectRenderDone:E}),h({...O,requestId:V})})},H=(async()=>{r=await Go(n),r.onmessage=O=>{if(a)return;const v=O.data;if(v.type==="status"){t.onStatus?.(v.label);return}if(v.type==="frame"){if(v.generation<=-cn){const L=-v.generation,se=l.get(L);l.delete(L),se?.resolve(v.bitmap);return}const V=v.generation<0;if(!V&&v.generation!==s){v.bitmap.close();return}if(V&&!(v.generation===oi)){const se=-v.generation;if(!f.isLatestSeq(se)){ft()?.onWorkerStale(),v.bitmap.close();return}}if(V&&t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()){ft()?.onWorkerStale(),v.bitmap.close();return}tr(e,v.bitmap),v.bitmap.close(),V&&w(v.generation);return}const E=T.get(v.requestId);if(E)switch(v.type){case"ready":T.delete(v.requestId),E.resolve();break;case"loadAssetsDone":T.delete(v.requestId),u=v.visemePaths?.length?new Set(v.visemePaths):null,E.resolve({width:v.width,height:v.height,visemePaths:v.visemePaths});break;case"renderDone":if(E.expectRenderDone&&E.generation!=null&&v.generation!==E.generation)return;T.delete(v.requestId),E.resolve();break;case"renderAborted":T.delete(v.requestId),E.resolve();break;case"error":T.delete(v.requestId),t.onError?.(v.message),E.reject(new Error(v.message));break}},r.onerror=O=>{if(a)return;const v=O.message||"Worker error";t.onError?.(v);for(const[,E]of T)E.reject(new Error(v));T.clear()},await I({type:"init"}),o=!0})();return{usesWorker:!0,usesPixi:!1,async loadAssets(O){if(a)return{width:842,height:1264};if(await H,a)return{width:842,height:1264};if(!o)throw new Error("Worker init failed");return await I({type:"loadAssets",keyHex:O,urls:$s(St())})??{width:842,height:1264}},getVisemeAtlasPaths(){return u},async renderSilOnly(){if(a||(await H,a))return;s+=1,f.reset(),d.clear(),l.forEach(({resolve:v})=>v(null)),l.clear(),c=cn;const O=s;await I({type:"cancelLiveDraws"}),await I({type:"renderSil",generation:O},void 0,!0)},drawLiveFrame(O,v,E,V){a||H.then(()=>{a||f.enqueue(v,E,V)})},compositePrefetchFrame(O,v){return a?Promise.resolve(null):H.then(()=>{if(a)return null;const E=++c;return new Promise(V=>{l.set(E,{resolve:V}),I({type:"drawFrame",diffPath:O.mouthPath,expressionDiffPath:O.expressionPath,liveSeq:E},void 0,!0).catch(()=>{l.delete(E),V(null)})})})},blitBitmap(O,v){tr(O,v)},drawIdleVideo(){},beginIdleToSilCrossfade(){},tickIdleToSilCrossfade(){return!1},finishIdleToSilCrossfade(){},isIdleToSilCrossfading(){return!1},supportsBufferedPlayback:!0,async renderViseme(O,v,E={}){if(a||(await H,a))return;s+=1,f.reset(),d.clear();const V=s;try{await I({type:"cancelLiveDraws"}),await I({type:"renderViseme",generation:V,to:v,from:E.from,transitionDurationMs:E.transitionDurationMs,gapMs:E.gapMs,threshold:E.threshold},void 0,!0)}catch(L){if(L?.name==="AbortError")return;throw L}},dispose(){if(!a){a=!0,s+=1,f.reset(),d.clear(),l.forEach(({resolve:O})=>O(null)),l.clear(),c=cn;for(const[,O]of T)O.resolve();T.clear(),r?.terminate(),r=null}}}}async function Qo(e,t){const n=await Ko(e,{onWebGlContextLost:t.onWebGlContextLost,maxTextureSize:t.pixiMaxTextureSize});let r=0,i=null,s=!1;const o=Er(async(a,u)=>s?!1:t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()?(ft()?.onWorkerStale(),!1):(n.drawLiveFrame(a),o.isLatestSeq(u)));return{usesWorker:!1,usesPixi:!0,async loadAssets(a){if(s)return{width:842,height:1264};const u=await n.loadAssets(a);return i=u.visemePaths?.length?new Set(u.visemePaths):null,u},getVisemeAtlasPaths(){return i},async renderSilOnly(){s||(r+=1,o.reset(),n.renderSilOnly())},drawLiveFrame(a,u,d,l){s||o.enqueue(u,d,l)},async compositePrefetchFrame(a,u){if(s)return null;try{return await n.compositePrefetchFrame(a)}catch{return null}},blitBitmap(a,u){s||t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()||n.blitBitmap(u)},drawIdleVideo(a,u){s||n.drawIdleVideo(a,u)},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,u){if(s)return;r+=1;const d=r;o.reset(),t.onStatus?.(u),n.drawLiveFrame({mouthPath:Mt(u),expressionPath:null})},dispose(){s||(s=!0,r+=1,o.reset(),n.dispose())}}}function ui(e,t){if(!qo())return li(e,t);const n=Is(t.workerScriptUrl);try{return Yo(e,t,n)}catch{return li(e,t)}}function Xo(e,t={}){if(t.preferLegacyRenderer)return ui(e,t);let n=null,r=!1,i=null,s=!1;const o=()=>n?Promise.resolve(n):(i||(i=(async()=>{try{const a=await Qo(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=ui(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,u,d,l){o().then(c=>{s||c.drawLiveFrame(a,u,d,l)})},async compositePrefetchFrame(a,u){return(await o()).compositePrefetchFrame(a,u)},blitBitmap(a,u){n&&n.blitBitmap(a,u)},drawIdleVideo(a,u){n?.usesPixi&&n.drawIdleVideo(a,u)},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,u,d){return(await o()).renderViseme(a,u,d)},dispose(){s=!0,i=null,n?.dispose(),n=null}}}class Jo extends Error{constructor(t,n){super(`${t} timed out after ${Math.round(n/1e3)}s`),this.name="LoadTimeoutError"}}function zn(e,t,n){return new Promise((r,i)=>{const s=globalThis.setTimeout(()=>{i(new Jo(n,t))},t);e.then(o=>{globalThis.clearTimeout(s),r(o)},o=>{globalThis.clearTimeout(s),i(o)})})}const Zo={overflow:"hidden",position:"relative",display:"inline-block",lineHeight:0},ec={display:"block",maxWidth:"100%",height:"auto"},tc={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 Hn(e){return vi(e)?pr:_i(e)?yn:hr}function nt(e,t){return t?.isSpeaking()||t?.isWarmingUp()?t:e.isSpeaking()||e.isWarmingUp()?e:t?.isConnected()?t:e}const ps=m.forwardRef(function({id:t,avatarId:n,faceId:r,assets:i,authToken:s,apiBase:o,ttsEngineId:a,voiceId:u,language:d,speakingRate:l=Kt,className:c,style:f,canvasStyle:w,onStatusChange:T,onDisplayStatus:h,onError:I,onReady:H,showErrorOverlay:O=!0,loadingThumbnailUrl:v,onUserTranscript:E,onBotOutput:V,onRealtimeLipsyncDebug:L,onFrameRenderStats:se,lipsyncBufferedPlayback:re=!0,lipsyncPlaybackWarmupMs:P=1500,idleHandoffHoldMs:q=Eo,pixiMaxTextureSize:Q,captions:ee,userName:oe,userEmail:ue,userContext:Se},We){const ne=m.useRef(null),D=m.useRef(null),S=m.useRef(null),J=m.useRef(re);J.current=re;const X=m.useRef(P);X.current=P;const ce=m.useRef(q);ce.current=q;const Y=m.useRef(0),z=m.useRef(kr()),$=m.useRef(to()),ve=m.useRef(!1),ae=m.useRef(null),_=m.useRef(null),B=m.useRef(0),W=m.useRef(0),b=m.useRef(0),y=m.useRef(null),x=m.useRef(null),A=m.useRef(!1),U=m.useRef(!1),j=m.useRef(!1),Z=m.useRef(!1),Te=m.useRef(!1),Ae=m.useRef("sil"),F=m.useRef(0),te=m.useRef(!1),le=m.useRef(null),Pe=m.useRef(!1),[ot,Bt]=m.useState("idle"),[Tt,p]=m.useState(null),[C,ie]=m.useState(!1),[he,ge]=m.useState(!1),[Me,Re]=m.useState(!1),[je,ze]=m.useState(),[Gt,In]=m.useState({width:842,height:1264}),[mt,Ft]=m.useState(null),[ht,qt]=m.useState(0),Lt=m.useRef(!1),Ze=m.useRef(s??null),Ve=o?.trim()||Pt,ct=m.useRef(null),xe=m.useRef(null),{ttsEngineId:Fe,voiceId:ke}=m.useMemo(()=>{const g=it(a,u),k=g.ttsEngineId??yt;return{ttsEngineId:k,voiceId:g.voiceId??Hn(k)}},[a,u]),De=m.useCallback(g=>{const k=vi(g);z.current.holdPp=k,S.current?.setHoldPp(k)},[]),Le=m.useRef(!1),lt=m.useRef({width:842,height:1264}),et=m.useRef(null),Yt=m.useRef("sil"),ut=m.useRef(""),Ke=m.useMemo(()=>po(ee),[ee]),Ge=m.useCallback(()=>{ut.current="",Ft(null)},[]);m.useEffect(()=>{Ke.enabled||Ge()},[Ke.enabled,Ge]);const An=m.useCallback(g=>{if(!Ke.enabled)return;const k=g.isSpeaking(),N=g.isWarmingUp();if(!k||N){ut.current&&Ge();return}const R=ho(g.getWordQueue());if(!R){ut.current&&Ge();return}R!==ut.current&&(ut.current=R,Ft(R))},[Ke.enabled,Ge]),Qt=m.useRef(void 0),Mn=m.useRef(new Map),Ir=m.useRef(H),Ar=m.useRef(T),Ee=m.useRef(h),Mr=m.useRef(I),Rr=m.useRef(E),Rn=m.useRef(V),Xt=m.useRef(L),Cr=m.useRef(se),kt=m.useRef(xo());Ir.current=H,Ar.current=T,Ee.current=h,Mr.current=I,Rr.current=E,Rn.current=V,Xt.current=L,Cr.current=se,m.useEffect(()=>{const g=kt.current;return ei(g),()=>ei(null)},[]);const Cn=m.useCallback(g=>{const k=it(g?.ttsEngineId??a,g?.voiceId??u),N=k.ttsEngineId??xe.current?.ttsEngineId??yt,R=k.voiceId??xe.current?.voiceId??Hn(N);return{ttsEngineId:N,voiceId:R}},[a,u]),tt=m.useCallback(g=>{p(g),Re(!0),Mr.current?.(g)},[]),Nt=m.useCallback(g=>{Bt(g),Ar.current?.(g)},[]),fe=m.useRef(Xn(Nt,Ve,{onLipsyncDebug:g=>Xt.current?.(g)})),pe=m.useRef(null),Jt=m.useRef(!1),Pr=m.useRef(()=>{});m.useEffect(()=>(fe.current=Xn(Nt,Ve,{onLipsyncDebug:g=>Xt.current?.(g)}),s&&fe.current.setDeveloperToken(s),fe.current.setTtsEngineId(Fe),fe.current.setMuted(Jt.current),()=>{fe.current.stop();const g=pe.current;g&&(g.disconnect(),pe.current=null)}),[Nt,Ve]);const Dr=m.useCallback(()=>(pe.current||(pe.current=Ji(Nt,{speakingRate:l,language:d,onUserTranscript:(g,k)=>Rr.current?.(g,k),onBotOutput:g=>Rn.current?.(g),onLipsyncDebug:g=>Xt.current?.(g)}),pe.current.setTtsEngineId(Fe),pe.current.setMuted(Jt.current),Pr.current(!0)),pe.current),[Nt,l,d,Fe]),Oe=m.useCallback(()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},[]),Ne=m.useCallback(()=>{x.current!=null&&(clearTimeout(x.current),x.current=null),j.current=!1},[]),Pn=m.useCallback(()=>{Te.current=!0,Ne(),le.current?.setLooping(!1)},[Ne]),He=m.useCallback(()=>{Te.current=!1,le.current?.setLooping(!0)},[]),Ot=m.useCallback(()=>{if(Z.current)return;const g=D.current;if(Z.current=!0,Te.current=!0,Ne(),A.current=!1,U.current=!1,!Pe.current||!le.current){g?.renderSilOnly();return}const k=le.current;k.setLooping(!1),k.setActive(!1);const N=k.getVideo();if(N.ended||Number.isFinite(N.currentTime)&&N.currentTime<=Wn){try{(N.ended||N.currentTime>Wn)&&(N.currentTime=0)}catch{}g?.renderSilOnly(),g?.finishIdleToSilCrossfade();return}if(g?.usesPixi){g.drawIdleVideo(N),g.beginIdleToSilCrossfade(ni);return}(async()=>{const K=ne.current;K&&await Vn(K,N,null,void 0,lt.current).catch(()=>{}),await new Promise(ye=>setTimeout(ye,ni)),Z.current&&await g?.renderSilOnly()})()},[Ne]),Br=m.useCallback(()=>{if(!(!Pe.current||!le.current)){if(Z.current=!1,D.current?.finishIdleToSilCrossfade(),D.current?.renderSilOnly(),Ne(),Te.current){j.current=!1;return}j.current=!0,x.current=setTimeout(()=>{if(x.current=null,nt(fe.current,pe.current).isSpeaking()){j.current=!1;return}if(A.current){j.current=!1;return}if(Te.current){j.current=!1;return}const g=le.current;if(!g){j.current=!1;return}He(),g.setLooping(!0),g.restart(),g.setActive(!0);const k=g.getVideo();let N=!1;const R=()=>{N||(N=!0,k.removeEventListener("playing",K),j.current=!1)},K=()=>{R()};if(k.addEventListener("playing",K,{once:!0}),k.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&!k.paused){R();return}setTimeout(R,300)},ce.current)}},[Ne,He]),xt=m.useCallback(()=>{if(Oe(),Ee.current?.("sil"),A.current=!1,Z.current=!1,!Pe.current||!le.current){j.current=!1,He();return}Br()},[Oe,Br,He]),Dn=m.useCallback(async g=>{const k=W.current,N=D.current,R=ne.current,K=()=>{g?.fallbackOnly||(A.current=!1)};if(!N||!R||!C){K();return}if(nt(fe.current,pe.current).isSpeaking()){K();return}if(g?.fallbackOnly){if(!A.current||(Ue(z.current),await N.renderSilOnly(),k!==W.current)||nt(fe.current,pe.current).isSpeaking())return;xt();return}if(ri(z.current)){Ue(z.current),xt();return}if(J.current&&N.supportsBufferedPlayback&&!g?.fallbackOnly){if(Ue(z.current),S.current?.reset(),await N.renderSilOnly(),k!==W.current||nt(fe.current,pe.current).isSpeaking())return;xt();return}const _e=Po(nt(fe.current,pe.current).getVisemeQueue(),F.current,Ae.current),Be=Do(_e,et.current);if(Ue(z.current),!Be){if(await N.renderSilOnly(),k!==W.current||nt(fe.current,pe.current).isSpeaking())return;xt();return}try{await N.renderViseme(R,"sil",{from:_e,transitionDurationMs:ds})}catch(Ie){if(Ie?.name!=="AbortError")throw Ie}if(k!==W.current){K();return}if(nt(fe.current,pe.current).isSpeaking()){K();return}xt()},[C,xt]),pt=m.useCallback(()=>{if(U.current||A.current)return;U.current=!0,A.current=!0,Oe();const g=W.current;Dn().finally(()=>{U.current=!1}),y.current=setTimeout(()=>{y.current=null,g===W.current&&Dn({fallbackOnly:!0})},Bo())},[Oe,Dn]),Fr=m.useCallback(async()=>{const g=Math.floor(Date.now()/1e3);if(ct.current&&g<ct.current.expiresAt-60)return ct.current.key;const k=Ze.current??await ln();Ze.current=k,fe.current.setDeveloperToken(k);const N=await Ws(k,Ve);return ct.current={key:N.value,expiresAt:N.expiresAt},N.value},[Ve]);m.useEffect(()=>{s&&(Ze.current=s,fe.current.setDeveloperToken(s))},[s]),m.useEffect(()=>{fe.current.setTtsEngineId(Fe),pe.current?.setTtsEngineId(Fe),xe.current&&(xe.current.ttsEngineId=Fe),De(Fe)},[Fe,De]),m.useEffect(()=>{xe.current&&(xe.current.voiceId=ke)},[ke]);const qe=m.useMemo(()=>Ti(n,r),[n,r]),ys=m.useMemo(()=>i?JSON.stringify(i):qe?`face:${qe}`:`id:${t??""}`,[i,qe,t]),vs=m.useMemo(()=>{const g=v?.trim();return g||(Or(qe)??Or(je)??Fs(i))},[v,qe,je,i]);return m.useEffect(()=>{if(!t&&!i&&!qe){tt("AiTwin requires `assets`, `avatarId`/`faceId`, or `id`");return}let g=!1;Le.current=!1,ie(!1),ge(!1),Re(!1),ze(qe),p(null),xe.current=null,le.current=null,Pe.current=!1;const k=ne.current;if(!k)return;let N=null;return(async()=>{try{let R,K,ye,_e,Be;if(i)R=i,K=Fe,ye=ke;else if(qe)Ee.current?.("loadFace"),R=Yn(qe),K=Fe,ye=ke;else{Ee.current?.("getAiTwin");const G=await zn(bi(t),3e4,"getAiTwin");if(g)return;if(!G.faceId?.trim())throw new Error("getAiTwin returned no faceId");ze(G.faceId.trim());const be=it(a,u);K=be.ttsEngineId??G.ttsEngineId,ye=be.voiceId??G.voiceId??Hn(K),_e=or(G),Be=cr(G),R=Yn(G.faceId)}xe.current={ttsEngineId:K,voiceId:ye,brainId:_e,brainUrl:Be},ki(R),le.current=no();const Ie=!!(i&&!bt(i));N=Xo(k,{preferLegacyRenderer:Ie,pixiMaxTextureSize:Q,onStatus:G=>{g||Ee.current?.(G)},onError:G=>{g||tt(G)},shouldAcceptLiveFrame:()=>{if(ve.current)return!0;if(A.current)return!1;const G=nt(fe.current,pe.current);return G.isSpeaking()||G.isWarmingUp()},onWebGlContextLost:()=>{g||Lt.current||(Lt.current=!0,queueMicrotask(()=>{g||qt(G=>G+1)}))}}),D.current=N,S.current=Uo(N),De(K),Lt.current=!1;const Ye=G=>{const be=()=>{if(!G||X.current<=0)return!1;const Ce=D.current;return Ce?J.current&&Ce.supportsBufferedPlayback?!0:Ce.usesPixi:!1};fe.current.setLipsyncWarmupHold(G,be),pe.current?.setLipsyncWarmupHold(G,be)};Pr.current=Ye,Ye(!0),Ee.current?.("auth");const Zt=Ze.current??s??await zn(ln(),3e4,"getAuthToken");if(g)return;Ze.current=Zt,fe.current.setDeveloperToken(Zt),fe.current.setTtsEngineId(K);const me=Ht()?await Fr():void 0;if(g)return;Ee.current?.("loadAssets");const de=await zn(N.loadAssets(me),18e4,"load face assets");if(!g&&de.width>0&&de.height>0&&(lt.current=de,In(de)),g)return;et.current=N.getVisemeAtlasPaths(),Le.current=!0,ie(!0),Ir.current?.(),N.renderSilOnly().then(()=>{g||Ee.current?.("sil")}),(async()=>{try{const G=await Ca(me);if(await le.current.load(G),g||(Pe.current=!0,ge(!0),Ue(z.current),await N.renderSilOnly(),g)||(await new Promise(Ce=>setTimeout(Ce,ce.current)),g))return;le.current.setActive(!0);const be=le.current.getVideo();N.usesPixi?N.drawIdleVideo(be):await Vn(k,be,null,void 0,lt.current)}catch(G){if(g)return;Pe.current=!1,ge(!1),console.warn("[AiTwin] Idle video unavailable:",G)}finally{g||(Re(!0),Ee.current?.("idle"))}})()}catch(R){if(g)return;if(R instanceof un){tt(R.message);return}tt(R instanceof Error?R.message:"Failed to load AI twin")}})(),()=>{g=!0,le.current?.dispose(),N?.dispose(),D.current=null}},[ys,i,qe,t,Fe,ke,a,u,s,Q,Fr,tt,ht,De]),m.useEffect(()=>{const g={current:!1},k=()=>{const N=ne.current,R=D.current,K=nt(fe.current,pe.current);if(!N||!R||!C){B.current=requestAnimationFrame(k);return}if(document.hidden){le.current?.setActive(!1),B.current=requestAnimationFrame(k);return}const ye=K.isSpeaking(),_e=K.isWarmingUp(),Be=ye&&!te.current,Ie=te.current&&!ye;Be&&(Oe(),Ne(),A.current=!1,U.current=!1,Ue(z.current),S.current?.reset(),kt.current.reset(),Qt.current=void 0,b.current=0,Ae.current="sil",F.current=0,Ot()),Ie&&($.current.reset(),le.current?.setActive(!1),S.current?.reset(),R.finishIdleToSilCrossfade(),Ge(),Te.current=!1,pt());const Ye=Ie||A.current||j.current||Z.current,Zt=re&&R.supportsBufferedPlayback;if(Te.current&&!ye&&!_e&&!Ie&&!A.current&&!j.current){if(Z.current){R.usesPixi&&R.isIdleToSilCrossfading()&&R.tickIdleToSilCrossfade(performance.now()),te.current=ye,B.current=requestAnimationFrame(k);return}if(Pe.current&&le.current){const me=le.current.getVideo();if(me.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){const de=me.duration,G=me.currentTime,be=me.ended||Number.isFinite(G)&&G<=Wn,Ce=Number.isFinite(de)&&de>0&&Number.isFinite(G)?Math.max(0,(de-G)*1e3):Number.POSITIVE_INFINITY;if(be||Ce<=Io){Ot(),R.usesPixi&&R.isIdleToSilCrossfading()&&R.tickIdleToSilCrossfade(performance.now()),te.current=ye,B.current=requestAnimationFrame(k);return}}}}if(_e){if(Ot(),Pe.current&&le.current?.setActive(!1),R.usesPixi&&R.isIdleToSilCrossfading()){R.tickIdleToSilCrossfade(performance.now()),K.getVisemeQueue().length>0&&Y.current===0&&(Y.current=performance.now()),te.current=K.isSpeaking(),B.current=requestAnimationFrame(k);return}const me=K.getVisemeQueue();me.length>0&&Y.current===0&&(Y.current=performance.now()),$.current.advance(performance.now());const de=$.current.getExpressionPath(),G=$.current.getDrawKey(),be={queue:me,elapsedMs:0,expressionPath:de,expressionDrawKey:G,availablePaths:et.current};let Ce=!1;Zt&&S.current?(S.current.warmupTick(be),Ce=S.current.isWarmupReady(be,X.current)):R.usesPixi&&ii(N,me,0,de,G,z.current,(Et,en,Bn,tn)=>{R.drawLiveFrame(Et,en,Bn,Qe=>{tn?.(Qe),K.isWarmingUp()&&Qe!==""&&!ri({lastDrawnKey:Qe})&&(Y.current=0,K.releaseWarmupHold())})},Et=>{Ee.current?.(Et.label)},et.current);const dt=Y.current>0&&performance.now()-Y.current>Ms;Ee.current?.(Ce?"buffer ready":"buffering lipsync…"),(Ce||dt)&&(Y.current=0,K.releaseWarmupHold()),An(K),te.current=K.isSpeaking(),B.current=requestAnimationFrame(k);return}if(ye){Ot(),Pe.current&&le.current?.setActive(!1),R.usesPixi&&R.isIdleToSilCrossfading()&&R.finishIdleToSilCrossfade();const me=K.getVisemeQueue(),de=K.getPlaybackElapsedMs();ga(me,de),F.current=de;const G=me.length>0?$t(me,de):"sil";G!=="sil"&&(Ae.current=G);const be=ao(de,K.getSentenceEmotions(),K.getWordQueue(),K.getStreamMood());$.current.setTargetEmotion(be),$.current.setTargetEyebrow(Za(de,K.getWordQueue(),_t(be))),$.current.advance(performance.now());const Ce=$.current.getExpressionPath(),dt=$.current.getDrawKey(),Et=(Qe,Fn,Ut,Ln)=>{const Lr={label:Yt.current,elapsedMs:de,mouthPath:Fn.mouthPath,transitionMeta:Qt.current};Mn.current.set(Ut,Lr),S.current?.markExternallyDisplayed(Ut,Ce),R.drawLiveFrame(Qe,Fn,Ut,nn=>{const _s=Mn.current.get(nn)??Lr;Mn.current.delete(nn),kt.current.onDrawDisplayed(_s,me),S.current?.markExternallyDisplayed(nn,Ce),Ln?.(nn)})},en=Qe=>{Yt.current=Qe.label,Qt.current=Qe.transitionMeta,Ee.current?.(Qe.label)},Bn=re&&R.supportsBufferedPlayback;let tn=!1;Bn&&S.current&&(tn=S.current.tick({canvas:N,queue:me,elapsedMs:de,expressionPath:Ce,expressionDrawKey:dt,playbackState:z.current,availablePaths:et.current,onStatus:en,onDisplayed:(Fn,Ut,Ln)=>{kt.current.onDrawDisplayed({label:Ln,elapsedMs:de,mouthPath:Ut,transitionMeta:Qt.current},me)}}).usedBuffer),tn||ii(N,me,de,Ce,dt,z.current,Et,en,et.current),kt.current.onRafTickSpeaking(),Cr.current?.(kt.current.snapshot(me,de))}else if(!Ye&&ve.current){le.current?.setActive(!1),$.current.advance(performance.now());const me=$.current.getExpressionPath(),de=$.current.getDrawKey();jn(N,me,de,z.current,(G,be,Ce,dt)=>R.drawLiveFrame(G,be,Ce,dt),G=>{if(_.current){Ee.current?.(_.current);return}const be=$.current.getTargetEmotion();Ee.current?.(G==="sil"||G==="blink"?`${be}${G==="blink"?" · blink":""}`:G)},null,ae.current)}else if(!Ye&&Pe.current&&le.current){const me=le.current,de=me.getVideo();if(de.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){me.setActive(!0);const G=()=>!K.isSpeaking()&&!A.current&&!j.current&&!ve.current;R.usesPixi?(R.drawIdleVideo(de,G),G()&&Ee.current?.("idle")):g.current||(g.current=!0,Vn(N,de,null,void 0,lt.current,G).then(()=>Ee.current?.("idle")).finally(()=>{g.current=!1}))}else jn(N,null,"__sil__",z.current,(G,be,Ce,dt)=>R.drawLiveFrame(G,be,Ce,dt),G=>Ee.current?.(G))}else Ye||jn(N,null,"__sil__",z.current,(me,de,G,be)=>R.drawLiveFrame(me,de,G,be),me=>Ee.current?.(me));Ke.enabled&&An(K),te.current=ye,B.current=requestAnimationFrame(k)};return B.current=requestAnimationFrame(k),()=>{cancelAnimationFrame(B.current),Oe(),Ne(),fe.current.stop(),pe.current?.stop()}},[C,he,pt,Oe,Ne,Ot,An,Ge,Ke.enabled]),m.useImperativeHandle(We,()=>({speakText:async(g,k)=>{const N=g.trim();if(!N)return;const R=D.current;if(!R||!Le.current&&!C)throw new Error("AI twin is not ready");const{ttsEngineId:K,voiceId:ye}=Cn(k);p(null),Ge(),W.current+=1,Oe(),Ne(),A.current=!1,U.current=!1,Ae.current="sil",F.current=0,Ue(z.current),De(K),ve.current=!1,ae.current=null,_.current=null,$.current.reset(),te.current=!1,Pn(),Z.current=!1,R.finishIdleToSilCrossfade();try{await fe.current.speak(N,{voiceId:ye,speakingRate:k?.speakingRate??l,ttsEngineId:K,language:k?.language??d})}catch(_e){throw He(),Z.current=!1,R.finishIdleToSilCrossfade(),pt(),tt(_e instanceof Error?_e.message:"TTS failed"),_e}},speakWithReply:async(g,k)=>{const N=g.trim();if(!N)return{displayText:"",spokenText:""};const R=D.current;if(!R||!Le.current&&!C)throw new Error("AI twin is not ready");const{ttsEngineId:K,voiceId:ye}=Cn(k);p(null),Ge(),W.current+=1,Oe(),Ne(),A.current=!1,U.current=!1,Ae.current="sil",F.current=0,Ue(z.current),De(K),ve.current=!1,ae.current=null,_.current=null,$.current.reset(),te.current=!1,Pn(),Z.current=!1,R.finishIdleToSilCrossfade();const _e=k?.brainId?.trim()||xe.current?.brainId?.trim()||void 0,Be=k?.brainUrl?.trim()||xe.current?.brainUrl?.trim()||void 0;try{return await fe.current.speakWithReply(N,{...k,voiceId:ye,speakingRate:k?.speakingRate??l,ttsEngineId:K,language:k?.language??d,brainId:_e,brainUrl:Be,userName:k?.userName?.trim()||oe?.trim()||void 0,userEmail:k?.userEmail?.trim()||ue?.trim()||void 0,userContext:k?.userContext?.trim()||Se?.trim()||void 0,onDisplayText:Ie=>{k?.onDisplayText?.(Ie),Rn.current?.(Ie)}})}catch(Ie){throw He(),Z.current=!1,R.finishIdleToSilCrossfade(),pt(),tt(Ie instanceof Error?Ie.message:"speakWithReply failed"),Ie}},stop:()=>{W.current+=1,Oe(),Ne(),A.current=!1,U.current=!1,Z.current=!1,He(),D.current?.finishIdleToSilCrossfade(),fe.current.stop(),pe.current?.stop(),Ue(z.current),S.current?.reset(),Y.current=0,te.current=!1,Ge(),pt()},setTtsEngineId:g=>{fe.current.setTtsEngineId(g),pe.current?.setTtsEngineId(g),xe.current&&(xe.current.ttsEngineId=g),De(g)},renderViseme:async(g,k)=>{const N=D.current,R=ne.current;if(!N||!R||!Le.current)throw new Error("AI twin is not ready");await N.renderViseme(R,g,{from:k?.from,transitionDurationMs:k?.transitionDurationMs,gapMs:k?.gapMs,onStatus:K=>Ee.current?.(K)})},setEmotion:g=>{if(!Le.current)throw new Error("AI twin is not ready");const k=D.current,N=ne.current;if(!k||!N)throw new Error("AI twin is not ready");W.current+=1,Oe(),Ne(),A.current=!1,U.current=!1,j.current=!1,Z.current=!1,He(),fe.current.stop(),pe.current?.stop(),Ue(z.current),S.current?.reset(),Y.current=0,te.current=!1,k.finishIdleToSilCrossfade(),le.current?.setActive(!1);const R=rt(g);ve.current=!0,ae.current=null,_.current=null,$.current.snapToEmotion(R);const K=$.current.getExpressionPath(),ye=$.current.getDrawKey(),_e={mouthPath:null,expressionPath:K},Be=zt(_e,ye);z.current.lastDrawnKey="",k.drawLiveFrame(N,_e,Be,Ye=>{Ye===Be&&(z.current.lastDrawnKey=Be)});const Ie=_t(R);Ee.current?.(K?`${R} · brow ${Ie>0?"+":""}${Ie}`:`${R} · brow 0 (sil base)`)},getEmotion:()=>ve.current?$.current.getTargetEmotion():null,clearEmotionPreview:()=>{ve.current=!1,ae.current=null,_.current=null,$.current.reset(),Ue(z.current),Ee.current?.("idle")},setViseme:g=>{if(!Le.current)throw new Error("AI twin is not ready");const k=D.current,N=ne.current;if(!k||!N)throw new Error("AI twin is not ready");W.current+=1,Oe(),Ne(),A.current=!1,U.current=!1,j.current=!1,Z.current=!1,He(),fe.current.stop(),pe.current?.stop(),Ue(z.current),S.current?.reset(),Y.current=0,te.current=!1,k.finishIdleToSilCrossfade(),le.current?.setActive(!1);const R=_n(g);ve.current=!0,_.current=R,ae.current=R==="sil"?null:Mt(R),$.current.snapToEmotion("neutral");const K=$.current.getExpressionPath(),ye=$.current.getDrawKey(),Be={mouthPath:ae.current,expressionPath:K},Ie=zt(Be,ye);z.current.lastDrawnKey="",k.drawLiveFrame(N,Be,Ie,Ye=>{Ye===Ie&&(z.current.lastDrawnKey=Ie)}),Ee.current?.(R)},getViseme:()=>ve.current?_.current:null,isReady:()=>Le.current,getStatus:()=>ot,connect:async(g={})=>{p(null);try{let k=g.authToken?.trim();k||(k=Ze.current??s??await ln(),Ze.current=k);const N=it(g.ttsEngineId??a,g.voiceId??u),R=N.voiceId??xe.current?.voiceId,K=g.brainId?.trim()||g.personaId?.trim()||xe.current?.brainId,ye=g.brainUrl?.trim()||xe.current?.brainUrl,_e=N.ttsEngineId??xe.current?.ttsEngineId??Fe,Be=Dr();_e&&Be.setTtsEngineId(_e),_e&&De(_e),await Be.unlockAudio(),await Be.connect({...g,apiBase:g.apiBase?.trim()||Ve,authToken:k,voiceId:R,brainId:K,brainUrl:ye,ttsEngineId:_e,speakingRate:g.speakingRate??l,language:g.language??d,userName:g.userName?.trim()||oe?.trim()||void 0,userEmail:g.userEmail?.trim()||ue?.trim()||void 0,userContext:g.userContext?.trim()||Se?.trim()||void 0})}catch(k){throw Wt(k)||tt(k instanceof Error?k.message:"Voice connect failed"),k}},disconnect:async()=>{const g=pe.current;g&&(W.current+=1,Oe(),Ne(),A.current=!1,U.current=!1,Z.current=!1,He(),D.current?.finishIdleToSilCrossfade(),Ue(z.current),S.current?.reset(),Y.current=0,te.current=!1,await g.disconnect(),pt())},isConnected:()=>pe.current?.isConnected()??!1,getVoiceStream:()=>pe.current?.getVoiceStream()??fe.current?.getVoiceStream()??null,setMuted:g=>{Jt.current=g,fe.current?.setMuted(g),pe.current?.setMuted(g)},isMuted:()=>Jt.current,getBrainId:()=>xe.current?.brainId?.trim()||null,getPersonaId:()=>xe.current?.brainId?.trim()||null,getBrainUrl:()=>xe.current?.brainUrl?.trim()||null}),[C,l,d,s,oe,ue,Se,Fe,ke,Oe,Ne,pt,Pn,He,tt,Cn,Dr,De,ot,Ve]),M.jsxs("div",{className:c,style:{...Zo,...f},children:[M.jsx("canvas",{ref:ne,width:Gt.width,height:Gt.height,style:{...ec,...w},"aria-label":t?`AI twin ${t}`:"AI twin face"}),!Me&&!Tt?M.jsx(To,{thumbnailUrl:vs}):null,O&&Tt?M.jsx("div",{style:tc,children:Tt}):null,Ke.enabled&&mt?M.jsx(vo,{text:mt,style:Ke.style},mt):null]})});function nc({muted:e}){return e?M.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[M.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),M.jsx("path",{d:"m16 9.5 5 5m0-5-5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):M.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[M.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),M.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 rc(){return M.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:M.jsx("path",{d:"M8 5.5v13l11-6.5L8 5.5Z"})})}function ic(){return M.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:M.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}function sc(){return M.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:M.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 ac(){return M.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:M.jsx("path",{d:"M15 6 9 12l6 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function oc(){return M.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:M.jsx("path",{d:"M12 19V5m0 0-6 6m6-6 6 6",stroke:"currentColor",strokeWidth:"2.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function cc(){return M.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:M.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}function di({className:e}){return M.jsx("span",{className:e??"aitwin-widget__spinner","aria-hidden":!0,children:M.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:M.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeDasharray:"40 20"})})})}function lc({muted:e,onToggle:t}){return M.jsx("button",{type:"button",className:"aitwin-widget__mute",onClick:t,"aria-label":e?"Unmute":"Mute","aria-pressed":e,children:M.jsx(nc,{muted:e})})}function uc(e){const t=e.status==="speaking",n=e.connecting||e.textSending||e.status==="loading"||t,r=e.connected?"End":"Talk",i=["aitwin-widget__action","aitwin-widget__action--primary",e.connecting?"aitwin-widget__action--connecting":""].filter(Boolean).join(" ");return M.jsxs("div",{className:e.textMode?"aitwin-widget__controls aitwin-widget__controls--text":"aitwin-widget__controls",children:[e.textMode?M.jsxs("form",{className:"aitwin-widget__composer",onSubmit:s=>{if(s.preventDefault(),t){e.onStopSpeech();return}e.onSendText()},children:[M.jsx("button",{type:"button",className:"aitwin-widget__composer-back",onClick:e.onTextMode,disabled:e.textSending&&!t,"aria-label":"Back",children:M.jsx(ac,{})}),M.jsx("input",{type:"text",className:"aitwin-widget__composer-input",value:e.textDraft,onChange:s=>e.onTextDraftChange(s.target.value),placeholder:t?"Speaking…":e.textSending?"Getting reply...":"Type a message...",autoComplete:"off",disabled:!e.ready||n&&!t,autoFocus:!0}),t?M.jsx("button",{type:"button",className:"aitwin-widget__composer-send aitwin-widget__composer-send--stop",onClick:e.onStopSpeech,"aria-label":"Stop",children:M.jsx(cc,{})}):M.jsx("button",{type:"submit",className:"aitwin-widget__composer-send",disabled:!e.ready||n||!e.textDraft.trim()&&!e.textSending,"aria-label":"Send","aria-busy":e.textSending,children:e.textSending?M.jsx(di,{className:"aitwin-widget__spinner aitwin-widget__spinner--on-accent"}):M.jsx(oc,{})})]}):M.jsxs("div",{className:"aitwin-widget__actions",children:[M.jsxs("button",{type:"button",className:i,onClick:e.onTalk,disabled:!e.ready||e.connecting||e.textSending,"aria-busy":e.connecting,"aria-label":e.connecting?"Connecting":r,children:[e.connecting?M.jsx(di,{className:"aitwin-widget__spinner aitwin-widget__spinner--on-accent"}):e.connected?M.jsx(ic,{}):M.jsx(rc,{}),M.jsx("span",{children:r})]}),M.jsxs("button",{type:"button",className:"aitwin-widget__action",onClick:e.onTextMode,disabled:!e.ready||e.connecting||e.textSending,"aria-pressed":!1,children:[M.jsx(sc,{}),M.jsx("span",{children:"Text"})]})]}),e.error?M.jsx("p",{className:"aitwin-widget__controls-error",role:"alert",children:e.error}):null]})}const fi=97,dc=3500;function fc(e,t){const n=Math.max(0,e),r=1-Math.exp(-n/dc);return Math.min(fi,Math.round(r*fi))}function mc(e){const[t,n]=m.useState(null),[r,i]=m.useState(()=>Date.now());return m.useEffect(()=>{if(!e){n(null);return}const s=Date.now();n(s),i(s);let o=0;const a=()=>{i(Date.now()),o=window.requestAnimationFrame(a)};return o=window.requestAnimationFrame(a),()=>{window.cancelAnimationFrame(o)}},[e]),e?t==null?0:fc(r-t):100}const hc="M259.01,593.87v-101.49c.33-6.31,4.94-11.26,10.21-11.88,6.42-.75,13.18,4.99,13.13,12.92-.42,45.09-.83,90.17-1.25,135.26.03,1.56.56,15.43,11.95,23.2,6.18,4.21,12.57,4.6,15.42,4.58-.42-112.77-.83-225.54-1.25-338.31-.08-2.55-1.03-46.36,21.17-55.34,2.05-.83,4.42-1.41,7.17-1.56v453.42c.07,12.06,1.98,37.84,19.03,62.73,7.01,10.23,14.79,17.71,21.4,22.99V222.42c-.01-3.72.48-11.67,5.35-19.87,7-11.77,18.13-15.82,21.4-16.95,10.42-3.61,19.49-2.06,23.48-1.11v684.96c.59,4.03,1.78,9.72,4.45,16.12,1.93,4.63,8.84,20.57,26.47,31.26,13.48,8.18,26.56,9.23,32.86,9.31-1.3-256.11-2.59-512.22-3.89-768.33.76-16.43,14.57-28.94,29.73-28.34,13.53.53,25.39,11.39,27.23,25.84-1.1,264.68-2.2,529.35-3.3,794.03,4.33.92,22.38,4.25,38.94-6.53,10.26-6.68,15.24-15.72,17.09-19.17,5.55-10.36,6.42-19.98,6.53-25.01-.72-246.99-1.43-493.97-2.15-740.96,2.27-.06,34.75-.44,48.29,22.68,3.41,5.83,4.87,11.86,5.34,17.19v674.68c5.92-2.16,39.19-14.94,50.16-47.79,3.12-9.34,3.68-18.03,3.33-25.01.03-193.22.06-386.43.09-579.65,4.12,1.18,28.28,8.48,36.17,30.08,1.64,4.49,2.32,8.88,2.43,12.92.02,146.42.05,292.84.07,439.25,3.82-1.71,19.51-9.22,25.56-26.47,2.15-6.12,2.48-11.73,2.29-15.89.01-114.91.03-229.81.04-344.72,2.36-.1,7.51.02,12.74,3.13,9.1,5.4,10.87,15.35,11.12,16.88.35,11.49.69,22.97,1.04,34.46.46,37.05.93,74.1,1.39,111.15v152.69c3.39-.72,9.77-2.67,14.31-8.34,3.62-4.52,4.51-9.46,5.56-15.28.91-5.04.95-9.31.83-12.23.02-38.81.03-77.62.05-116.43";function pc({className:e="aitwin-widget__logo",strokeWidth:t=15,durationMs:n=2600,delayMs:r=0,loop:i=!1}){return M.jsx("svg",{viewBox:"0 0 1080 1080",className:e,role:"img","aria-label":"AITWIN logo",children:M.jsx("path",{className:i?"aitwin-widget__logo-draw aitwin-widget__logo-draw--loop":"aitwin-widget__logo-draw",d:hc,fill:"none",stroke:"currentColor",strokeWidth:t,strokeMiterlimit:10,pathLength:1,style:{animationDuration:`${n}ms`,animationDelay:`${r}ms`}})})}function wc({progress:e}){const t=Math.max(0,Math.min(100,Math.round(e)));return M.jsx("div",{className:"aitwin-widget__face-loading","aria-live":"polite","aria-label":`Loading ${t} percent`,children:M.jsxs("div",{className:"aitwin-widget__face-loading-content",children:[M.jsx(pc,{className:"aitwin-widget__logo",loop:!0,durationMs:2600}),M.jsxs("div",{className:"aitwin-widget__face-loading-bar-wrap",children:[M.jsx("div",{role:"progressbar","aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":100,className:"aitwin-widget__face-loading-track",children:M.jsx("div",{className:"aitwin-widget__face-loading-fill",style:{width:`${t}%`}})}),M.jsxs("p",{className:"aitwin-widget__face-loading-pct",children:[t,"%"]})]})]})})}function mi(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,language:e.language}}function gc(e){return[e.id??"",e.faceId??"",e.authToken?.slice(0,16)??"",e.voiceId??"",e.apiBase??"",String(e.speakingRate??"")].join("|")}const hi={display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",lineHeight:0},yc={display:"block",height:"100%",width:"100%",objectFit:"cover",objectPosition:"top"},vc=m.forwardRef(function({options:t},n){const r=m.useRef(null),i=m.useRef(t);i.current={...i.current,onReady:t.onReady,onStatusChange:t.onStatusChange,onError:t.onError,onUserTranscript:t.onUserTranscript,onBotOutput:t.onBotOutput};const[s,o]=m.useState(!!t.showControls),[a,u]=m.useState(()=>mi(t)),[d,l]=m.useState(!1),[c,f]=m.useState(!1),[w,T]=m.useState(!1),[h,I]=m.useState(!1),[H,O]=m.useState("idle"),[v,E]=m.useState(null),[V,L]=m.useState(!1),[se,re]=m.useState(!1),[P,q]=m.useState(""),[Q,ee]=m.useState(!1),[oe,ue]=m.useState([]),[Se,We]=m.useState(t.brainId?.trim()||t.personaId?.trim()||void 0),[ne,D]=m.useState(t.brainUrl?.trim()||void 0),S=m.useCallback(F=>{i.current={...i.current,...F},F.showControls!==void 0&&o(!!F.showControls),(F.brainId!==void 0||F.personaId!==void 0)&&We((F.brainId??F.personaId)?.trim()||void 0),F.brainUrl!==void 0&&D(F.brainUrl.trim()||void 0),u(te=>mi({id:F.id??te.id,faceId:F.faceId??F.avatarId??te.faceId,authToken:F.authToken??te.authToken,apiBase:F.apiBase??te.apiBase,voiceId:F.voiceId??te.voiceId,speakingRate:F.speakingRate??te.speakingRate,language:F.language??te.language}))},[]);m.useImperativeHandle(n,()=>({getTwin:()=>r.current,applyOptions:S}),[S]),m.useEffect(()=>{S(t)},[S,t.id,t.faceId,t.avatarId,t.authToken,t.apiBase,t.voiceId,t.speakingRate,t.showControls,t.brainId,t.personaId,t.brainUrl]);const J=m.useCallback(()=>{l(!0),E(null)},[]),X=m.useCallback(F=>{F==="idle"&&f(!0)},[]),ce=m.useCallback(F=>{O(F),i.current.onStatusChange?.(F)},[]),Y=m.useRef(!1);Y.current=d&&c;const z=m.useCallback(F=>{if(I(!1),Wt(F)){re(!0),E(null);return}E(F),Y.current||(l(!1),f(!1)),i.current.onError?.(F)},[]),$=m.useCallback((F,te)=>{i.current.onUserTranscript?.(F,te)},[]),ve=m.useCallback(F=>{i.current.onBotOutput?.(F)},[]);m.useEffect(()=>{if(!s)return;const F=window.setInterval(()=>{T(!!r.current?.isConnected())},400);return()=>window.clearInterval(F)},[s,a]);const ae=gc(a),_=!!(a.id||a.faceId),B=d&&c,W=_&&!B&&!v,b=mc(W),y=m.useRef(ae);m.useEffect(()=>{B&&i.current.onReady?.()},[B]),m.useEffect(()=>{B&&r.current?.setMuted(V)},[B,V,a]),m.useEffect(()=>{ue([])},[a.id,a.faceId]),m.useEffect(()=>{y.current!==ae&&(y.current=ae,l(!1),f(!1),E(null),I(!1),T(!1),O("idle"))},[ae]);const x=m.useCallback(()=>{re(!0),E(null),I(!1),T(!1)},[]),A=()=>{const F=r.current;if(!F?.isReady())return;if(E(null),F.isConnected()){I(!1),re(!1),F.disconnect().finally(()=>{T(!1)});return}I(!0);const te={authToken:a.authToken,voiceId:a.voiceId,speakingRate:a.speakingRate,language:a.language,apiBase:a.apiBase,...Se?{brainId:Se}:{},...ne?{brainUrl:ne}:{}};(async()=>{if(await va()){x();return}re(!1);try{await F.connect(te),T(!!F.isConnected())}catch(le){if(Wt(le)){x();return}const Pe=le instanceof Error?le.message:"Failed to connect voice.";E(Pe),i.current.onError?.(Pe)}finally{I(!1)}})()},U=()=>{re(F=>!F),E(null)},j=m.useRef(0),Z=()=>{const F=P.trim(),te=r.current;if(!F||!te?.isReady()||Q)return;E(null),q(""),ee(!0);const le=++j.current;i.current.onUserTranscript?.(F,!0),(async()=>{try{const Pe=Se||te.getBrainId()?.trim()||void 0,ot=ne||te.getBrainUrl()?.trim()||void 0,Bt=await te.speakWithReply(F,{brainId:Pe,brainUrl:ot,history:oe,voiceId:a.voiceId,speakingRate:a.speakingRate,language:a.language});if(le!==j.current)return;Bt.displayText&&ue(Tt=>[...Tt,{role:"user",content:F},{role:"assistant",content:Bt.displayText}])}catch(Pe){if(le!==j.current)return;const ot=Pe instanceof Error?Pe.message:"Failed to get reply.";E(ot),i.current.onError?.(ot)}finally{le===j.current&&ee(!1)}})()},Te=()=>{j.current+=1,r.current?.stop(),ee(!1)},Ae=()=>{const F=!V;L(F),r.current?.setMuted(F)};return M.jsxs("div",{className:"aitwin-widget__layout",children:[M.jsxs("div",{className:"aitwin-widget__stage",children:[_?M.jsx("div",{style:hi,children:M.jsx(ps,{ref:r,id:a.id,faceId:a.faceId,authToken:a.authToken,apiBase:a.apiBase,voiceId:a.voiceId,speakingRate:a.speakingRate,language:a.language,style:hi,canvasStyle:yc,onReady:J,onDisplayStatus:X,onStatusChange:ce,onError:z,onUserTranscript:$,onBotOutput:ve,loadingThumbnailUrl:t.loadingThumbnailUrl},ae)}):M.jsx("p",{className:"aitwin-widget__hint",style:{padding:16},children:"Pass id or faceId to load a twin."}),W?M.jsx(wc,{progress:b}):null,s?M.jsx(lc,{muted:V,onToggle:Ae}):null]}),s?M.jsx(uc,{ready:B,connected:w,connecting:h,status:H,textMode:se,textDraft:P,textSending:Q,error:v,onTalk:A,onTextMode:U,onTextDraftChange:q,onSendText:Z,onStopSpeech:Te}):null]})}),_c=".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-composer-width: calc(340px * var(--aitwin-size));--aitwin-composer-height: calc(40px * var(--aitwin-size));--aitwin-action-height: calc(32px * 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));--aitwin-float-inset: 20px;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{align-items:flex-end;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__controls--text{max-width:calc(100vw - (2 * var(--aitwin-float-inset)));width:var(--aitwin-composer-width)}.aitwin-widget__actions{align-items:center;display:flex;gap:var(--aitwin-action-gap);width:100%}.aitwin-widget__action{align-items:center;appearance:none;background:transparent;border:1.5px solid var(--aitwin-accent);border-radius:999px;box-sizing:border-box;color:var(--aitwin-accent);cursor:pointer;display:inline-flex;flex:1 1 0;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;line-height:1;margin:0;min-height:var(--aitwin-action-height);min-width:0;overflow:hidden;padding:0 calc(10px * var(--aitwin-size))}.aitwin-widget__action span{display:inline-flex;line-height:1}.aitwin-widget__action svg{display:block;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:var(--aitwin-accent);color:#fff}.aitwin-widget__action--primary:hover:not(:disabled){background:var(--aitwin-accent-hover);border-color:var(--aitwin-accent-hover)}.aitwin-widget__action--connecting:disabled{cursor:progress;opacity:1}.aitwin-widget__spinner{display:inline-flex;flex-shrink:0;height:calc(12px * var(--aitwin-size));width:calc(12px * var(--aitwin-size))}.aitwin-widget__spinner svg{animation:aitwin-widget-spin .8s linear infinite;display:block;height:100%;width:100%}.aitwin-widget__spinner--on-accent,.aitwin-widget__action .aitwin-widget__spinner{color:#fff}@keyframes aitwin-widget-spin{to{transform:rotate(360deg)}}.aitwin-widget__face-loading{background:transparent;inset:0;overflow:hidden;pointer-events:none;position:absolute;z-index:4}.aitwin-widget__face-loading-content{align-items:center;display:flex;flex-direction:column;gap:calc(12px * var(--aitwin-size));inset:0;justify-content:center;padding:calc(24px * var(--aitwin-size));position:absolute;z-index:1}.aitwin-widget__logo{color:#fff;display:block;flex-shrink:0;height:calc(64px * var(--aitwin-size));margin-bottom:calc(4px * var(--aitwin-size));width:calc(64px * var(--aitwin-size))}.aitwin-widget__logo-draw{stroke-dasharray:1;stroke-dashoffset:1;animation:aitwin-widget-logo-draw 2.6s ease-in-out forwards}.aitwin-widget__logo-draw--loop{animation:aitwin-widget-logo-draw-loop 2.6s ease-in-out infinite}@keyframes aitwin-widget-logo-draw{to{stroke-dashoffset:0}}@keyframes aitwin-widget-logo-draw-loop{0%{stroke-dashoffset:1}45%{stroke-dashoffset:0}55%{stroke-dashoffset:0}to{stroke-dashoffset:-1}}@media(prefers-reduced-motion:reduce){.aitwin-widget__logo-draw,.aitwin-widget__logo-draw--loop{animation:none;stroke-dashoffset:0}}.aitwin-widget__face-loading-bar-wrap{max-width:calc(220px * var(--aitwin-size));width:100%}.aitwin-widget__face-loading-track{background:#fff3;border-radius:999px;height:calc(4px * var(--aitwin-size));overflow:hidden;width:100%}.aitwin-widget__face-loading-fill{background:var(--aitwin-accent);border-radius:999px;height:100%;transition:width .3s ease-out}.aitwin-widget__face-loading-pct{color:#ffffffbf;font-size:calc(12px * var(--aitwin-size));margin:calc(8px * var(--aitwin-size)) 0 0;text-align:center}.aitwin-widget__composer{align-items:center;background:#fff;border:1.5px solid var(--aitwin-accent);border-radius:999px;display:flex;gap:calc(4px * var(--aitwin-size));height:var(--aitwin-composer-height);padding:calc(4px * var(--aitwin-size));width:100%}.aitwin-widget__composer-back{align-items:center;background:transparent;border:none;border-radius:999px;color:#9ca3af;cursor:pointer;display:inline-flex;flex-shrink:0;height:calc(30px * var(--aitwin-size));justify-content:center;padding:0;width:calc(30px * var(--aitwin-size))}.aitwin-widget__composer-back:hover:not(:disabled){color:#4b5563}.aitwin-widget__composer-back:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__composer-back svg{display:block;height:calc(16px * var(--aitwin-size));width:calc(16px * var(--aitwin-size))}.aitwin-widget__composer-input{background:transparent;border:none;color:#111827;flex:1;font-family:inherit;font-size:calc(14px * var(--aitwin-size));min-width:0;outline:none;padding:0 calc(4px * var(--aitwin-size))}.aitwin-widget__composer-input::placeholder{color:#9ca3af}.aitwin-widget__composer-input:disabled{opacity:.7}.aitwin-widget__composer-send{align-items:center;background:var(--aitwin-accent);border:none;border-radius:999px;color:#fff;cursor:pointer;display:inline-flex;flex-shrink:0;height:calc(30px * var(--aitwin-size));justify-content:center;padding:0;width:calc(30px * var(--aitwin-size))}.aitwin-widget__composer-send:hover:not(:disabled){background:var(--aitwin-accent-hover)}.aitwin-widget__composer-send:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__composer-send--stop{opacity:1}.aitwin-widget__composer-send svg{display:block;height:calc(14px * var(--aitwin-size));width:calc(14px * var(--aitwin-size))}.aitwin-widget__controls-error{color:#fecaca;font-size:calc(11px * var(--aitwin-size));margin:0}.aitwin-widget--float{bottom:var(--aitwin-float-inset);filter:drop-shadow(0 12px 32px rgba(0,0,0,.45));height:fit-content;margin:0;max-width:calc(100vw - (2 * var(--aitwin-float-inset)));position:fixed;right:var(--aitwin-float-inset);width:fit-content;z-index:2147483000}@media(max-width:640px){.aitwin-widget{--aitwin-composer-width: calc(100vw - (2 * var(--aitwin-float-inset)));--aitwin-composer-height: calc(44px * var(--aitwin-size))}.aitwin-widget__controls--text{width:var(--aitwin-composer-width)}.aitwin-widget__composer-input{font-size:calc(15px * var(--aitwin-size))}}",pi="data-aitwin-widget-style";function ws(){if(typeof document>"u")return;const e=_c.trim();if(!e){console.warn("[AiTwinWidget] styles.css?inline resolved empty — chrome will be unstyled");return}const t=document.querySelector(`style[${pi}]`);if(t){if((t.textContent??"").trim().length>0)return;t.textContent=e;return}const n=document.createElement("style");n.setAttribute(pi,"1"),n.textContent=e,(document.head??document.documentElement).appendChild(n)}typeof document<"u"&&ws();const bc=m.forwardRef(function(t,n){ws();const r=m.useRef(null);m.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)},speakWithReply:async(s,o)=>{const a=r.current?.getTwin();if(!a)throw new Error("AiTwinWidget: twin is not mounted");return a.speakWithReply(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 M.jsx("div",{className:i?"aitwin-widget aitwin-widget--float":"aitwin-widget",children:M.jsx(vc,{ref:r,options:t})})}),Sc=new Set([".png",".jpg",".jpeg",".webp"]);function gs(e=".png"){const t=e.toLowerCase();return Sc.has(t)?`source${t}`:"source.png"}function Tc(e,t=rr,n=".png"){const r=e.trim();if(!r)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${r}/${gs(n)}`}async function kc(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 xc(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()||Pt).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??[],brainId:e.brainId?.trim()||e.personaId?.trim()||"",tenant:"aiTwin"})});if(!i.ok)throw new Error(await kc(i));if(!i.body)throw new Error("avatarReply response body is empty");const s=i.body.getReader(),o=new TextDecoder;let a="",u="",d="",l="";for(;;){const{done:c,value:f}=await s.read();if(c)break;a+=o.decode(f,{stream:!0});const w=a.split(`
48
- `);a=w.pop()||"";for(const T of w){if(T.startsWith("event: ")){l=T.slice(7).trim();continue}if(!T.startsWith("data: "))continue;const h=T.slice(6).trim();if(!h)continue;let I;try{I=JSON.parse(h)}catch{continue}if(l==="spokenText")u=I.text||"",e.onSpokenText?.(u);else if(l==="displayText")d=I.text||"";else if(l==="error")throw new Error(I.error||"avatarReply stream error")}}if(!u.trim()||!d.trim())throw new Error("avatarReply stream missing displayText or spokenText");return{displayText:d.trim(),spokenText:u.trim()}}exports.AI_TWIN_THUMBNAIL_FILENAME=lr;exports.AiTwin=ps;exports.AiTwinNotFoundError=un;exports.AiTwinWidget=bc;exports.CONSONANT_SKIP_GROUP=Li;exports.DEFAULT_TTS_ENGINE_ID=yt;exports.DEFAULT_TTS_LANGUAGE=Qs;exports.EMOTION_TO_EYEBROW=as;exports.EXPRESSION_ATLAS_EMOTIONS=Ha;exports.MIC_SAMPLE_RATE=wr;exports.OCULUS_VISEME_IDS=Pi;exports.PLAYBACK_SAMPLE_RATE=gr;exports.SPEAKING_RATE_MAX=xn;exports.SPEAKING_RATE_MIN=kn;exports.TTS_ENGINE_CARTESIA=st;exports.TTS_ENGINE_GOOGLE=sr;exports.TTS_ENGINE_INWORLD=gn;exports.TTS_ENGINE_VISEMETTS=at;exports.TTS_LANGUAGE_CATALOG=vt;exports.TTS_LANGUAGE_CODES=Mi;exports.VISEME_IDS=Pa;exports.VISEME_SKIP_GAP_MS=Qn;exports.VISEME_TEST_CARTESIA_VOICE_ID=pr;exports.VISEME_TEST_SPEAKING_RATE=Kt;exports.VISEME_TEST_VISEMETTS_VOICE_ID=yn;exports.VISEME_TEST_VOICE_ID=hr;exports.VISEME_VTIME_GRID_MS=ur;exports.VOWEL_SKIP_GROUP=Fi;exports.aiTwinSourceFilename=gs;exports.buildPlaybackTransitions=zi;exports.buildPlaybackVisemeSeries=Sn;exports.buildRawVisemeTransitions=ji;exports.buildVoiceWebSocketUrl=Xi;exports.compactSkippableVisemes=fr;exports.createAvatarTtsLipsyncController=Xn;exports.createRealtimeVoiceLipsyncController=Ji;exports.emotionToEyebrow=_t;exports.faceAssetUrls=Yn;exports.fetchAiTwin=bi;exports.fetchAvatarReply=xc;exports.fetchDevAuthToken=ln;exports.getAiTwinSourceUrl=Tc;exports.getAiTwinThumbnailUrl=Si;exports.isTtsLanguageCode=Ri;exports.isTtsLanguageSupported=Js;exports.listSkippedVisemeEntries=Tn;exports.listSkippedVisemes=la;exports.normalizeOculusViseme=_n;exports.normalizeStreamEmotion=rt;exports.normalizeTtsLanguage=vn;exports.parsePackedVoiceId=gi;exports.parseTwinBrainUrl=Bs;exports.resolveDirectFaceId=Ti;exports.resolveTwinBrainId=or;exports.resolveTwinBrainUrl=cr;exports.resolveVisemeAtTime=$t;exports.resolveVisemeFromPlaybackSeries=Ui;exports.resolveWordAtTime=ya;exports.setActiveTwinAssets=ki;exports.snapVisemeQueueToGrid=dr;exports.snapVisemeVtimeToGrid=Ni;exports.splitVoiceIdSpec=it;exports.ttsLanguagesForEngine=Xs;
47
+ `;function Si(e=5){const t=new Te.Filter({glProgram:Te.GlProgram.from({vertex:pc,fragment:gc,name:"threshold-key-filter"}),resources:{thresholdUniforms:{uThreshold:{value:e/255,type:"f32"}}}});return t.setThreshold=r=>{t.resources.thresholdUniforms.uniforms.uThreshold=r/255},t.getThreshold=()=>Math.round(t.resources.thresholdUniforms.uniforms.uThreshold*255),t}function wc(e,t,r){return e>r||t>r}function yc(e){return e?e.getParameter(e.MAX_TEXTURE_SIZE):4096}function vc(e,t){return t!=null&&t>0?Math.floor(t):yc(e)}function _c(e,t){const r=document.createElement("canvas");r.width=t.w,r.height=t.h;const n=r.getContext("2d");if(!n)throw new Error("Failed to acquire 2d context for atlas cell crop");return n.drawImage(e,t.x,t.y,t.w,t.h,0,0,t.w,t.h),r}function Us(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 Ti(e,t,r,n,i){const s=r?await Gi(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,f=async(c,p)=>{const y=Ms(t,p,r),E=r?await va(await yt(y,i??"")):await Us(y);if(wc(E.width,E.height,n))return console.info(`[PixiVisemeCompositor] Sheet ${p} (${E.width}x${E.height}) exceeds MAX_TEXTURE_SIZE=${n}; using per-cell crops.`),{mode:"cells",bitmap:E};const g=Te.Texture.from(E);return g.source.scaleMode="nearest",{mode:"full",texture:g}};a.set(o.index,await f(o.index,o.path));for(const c of s.sheets??[])c.index!==o.index&&c.path&&a.set(c.index,await f(c.index,c.path));const h=new Map;for(const c of s.cells??[])c.path&&h.set(c.path,c);const l=new Map;for(const c of s.sheets??[])l.set(c.index,c);return{atlasMeta:s,cellByPath:h,sheetByIndex:l,diffBase:t,sheets:a}}async function bc(e,t={}){const r=new Te.Application;try{await r.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(b){throw r.destroy({removeView:!1}),b}if(r.renderer.type!==Te.RendererType.WEBGL)throw r.destroy({removeView:!1}),new Error("Pixi did not initialize a WebGL renderer");const n=vc(r.renderer.gl,t.maxTextureSize);let i=!1,s=!1,o=!1;const a=r.canvas,f=()=>{i=!0,!s&&!o&&(s=!0,t.onWebGlContextLost?.())};a.addEventListener("webglcontextlost",f);const h=new Te.Sprite(Te.Texture.EMPTY),l=new Te.Sprite(Te.Texture.EMPTY);l.visible=!1,l.alpha=0;const c=new Te.Sprite(Te.Texture.EMPTY),p=new Te.Sprite(Te.Texture.EMPTY),y=new Te.Sprite(Te.Texture.EMPTY);y.visible=!1;const E=Si(5),g=Si(5);c.filters=[E],p.filters=[g],r.stage.addChild(h),r.stage.addChild(l),r.stage.addChild(c),r.stage.addChild(p),r.stage.addChild(y);let M=null,W=null,B=null,_=null,x=null,N=null,j=null,G=842,ie=1264,P=null,V=5;const Z=new Map;let Q=null,ue=null,ae=null;const Re=ji(()=>{Z.clear(),N=null,j=null,M=null,P=null}),ke=(b,d)=>{G=b,ie=d,r.renderer.resize(b,d),(e.width!==b||e.height!==d)&&(e.width=b,e.height=d)},ne=()=>{c.visible=!1,p.visible=!1,c.texture=Te.Texture.EMPTY,p.texture=Te.Texture.EMPTY,Q=null,ue=null},ze=()=>{x=null,l.visible=!1,l.alpha=0},S=()=>{h.visible=!0,h.width=G,h.height=ie,h.x=0,h.y=0},ee=()=>{l.width=G,l.height=ie,l.x=0,l.y=0},$=()=>{y.visible=!1,ze(),M&&(h.texture=M,S())},H=()=>{x&&$()},de=b=>{if(o||i||!M){$();return}const d=Math.max(0,b);if(!W||d<=0){$();return}ne(),y.visible=!1,h.texture=M,S(),l.texture=W,ee(),l.alpha=1,l.visible=!0,x={startMs:performance.now(),durationMs:d},I()},X=(b=performance.now())=>{if(!x)return!1;if(o||i)return H(),!1;const d=(b-x.startMs)/Math.max(1,x.durationMs);if(d>=1)return $(),I(),!1;const m=Math.min(1,Math.max(0,d)),k=m*m*(3-2*m);return l.alpha=1-k,l.visible=!0,I(),!0},se=()=>{if(B){try{B.resource=null}catch{}B.destroy(),B=null}W&&(W.destroy(!1),W=null),_=null},me=(b,d)=>{const m=b.cellByPath.get(d);if(!m||!Is(m))return null;const k=`${b.diffBase}::${d}`;let O=Z.get(k);if(!O){const F=m.sheet??0,te=b.sheets.get(F);if(!te)return null;let C,J=!1;if(te.mode==="full")C=new Te.Texture({source:te.texture.source,frame:new Te.Rectangle(m.x,m.y,m.w,m.h)});else{const T=_c(te.bitmap,m);C=Te.Texture.from(T),C.source.scaleMode="nearest",J=!0}O={texture:C,ownsSource:J},Z.set(k,O)}return{texture:O.texture,cell:m}},he=(b,d,m,k)=>{if(!k||!m)return b.visible=!1,b.texture=Te.Texture.EMPTY,!1;const O=me(m,k);if(!O)return b.visible=!1,b.texture=Te.Texture.EMPTY,!1;const F=xs(m.atlasMeta,O.cell);return d.setThreshold(V),b.texture=O.texture,b.x=F.x,b.y=F.y,b.width=O.cell.w,b.height=O.cell.h,b.visible=!0,!0},K=b=>{if(!b||!N)return null;const d=P??new Set(N.cellByPath.keys());return Cn(b,d)??(d.has(b)?b:null)},re=b=>{y.visible=!1,$();const d=K(b.mouthPath),m=b.expressionPath&&j?Bn(b.expressionPath,k=>j.cellByPath.has(k)):null;d!==Q?(he(c,E,N,d),Q=d):d?c.visible=!0:c.visible=!1,m!==ue?(he(p,g,j,m),ue=m):m?p.visible=!0:p.visible=!1},I=()=>{if(!(o||i||document.hidden))try{r.render()}catch{}};return{async loadAssets(b){if(o)return{width:G,height:ie,visemePaths:[]};const d=$t();if(d&&!b)throw new Error("Encrypted assets enabled but no key provided");const m=d?await ba(await yt(tr(),b??"")):await Us(tr());M&&M.destroy(!0),M=Te.Texture.from(m),M.source.scaleMode="linear";const k=Hi();N=await Ti($i(),k,d,n,b);try{j=await Ti(zi(),k,d,n,b)}catch(F){console.warn("[PixiVisemeCompositor] expression atlas unavailable:",F),j=null}const O=Es(N.atlasMeta,m.width,m.height);return ke(O.width,O.height),V=Wr(N.atlasMeta),E.setThreshold(V),g.setThreshold(V),P=new Set(N.cellByPath.keys()),Z.clear(),$(),ne(),I(),{width:O.width,height:O.height,visemePaths:[...N.cellByPath.keys()]}},getVisemeAtlasPaths(){return P},drawLiveFrame(b){o||i||!M||(H(),re(b),I())},drawIdleVideo(b,d){o||i||document.hidden||d&&!d()||b.readyState<HTMLMediaElement.HAVE_CURRENT_DATA||(x=null,ne(),y.visible=!1,M&&(h.texture=M,S()),!W||_!==b?(se(),B=new Te.VideoSource({resource:b,autoPlay:!1,updateFPS:0}),B.autoUpdate=!1,W=new Te.Texture({source:B}),_=b):W.source.update(),l.texture=W,ee(),l.alpha=1,l.visible=!0,I())},beginIdleToSilCrossfade:de,tickIdleToSilCrossfade:X,finishIdleToSilCrossfade:H,isIdleToSilCrossfading(){return x!=null},renderSilOnly(){o||i||!M||(ne(),$(),I())},blitBitmap(b){o||i||(H(),ne(),ae&&(ae.destroy(!0),ae=null),ae=Te.Texture.from(b),y.texture=ae,y.visible=!0,y.x=0,y.y=0,y.width=G,y.height=ie,h.visible=!1,I())},async compositePrefetchFrame(b){return null},renderFrame:I,isContextLost(){return i},dispose(){if(o)return;o=!0,a.removeEventListener("webglcontextlost",f),Re(),se(),ae&&(ae.destroy(!0),ae=null);for(const{texture:d,ownsSource:m}of Z.values())d.destroy(m);Z.clear(),M&&(M.destroy(!0),M=null);const b=d=>{d.mode==="full"?d.texture.destroy(!0):d.bitmap.close()};if(N)for(const d of N.sheets.values())b(d);if(j)for(const d of j.sheets.values())b(d);E.destroy(!0),g.destroy(!0),r.destroy({removeView:!1},{children:!0,texture:!0})}}}const ki=-1,Sr=1e5,Ei=new Map;async function Sc(e){let t=Ei.get(e);if(!t){const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch worker script (${r.status}): ${e}`);const n=await r.blob();t=URL.createObjectURL(n),Ei.set(e,t)}return new Worker(t,{name:"visemeDiffPreview"})}function Tc(){return typeof Worker<"u"&&typeof OffscreenCanvas<"u"}function gn(e,t){(e.width!==t.width||e.height!==t.height)&&(e.width=t.width,e.height=t.height);const r=e.getContext("2d");r&&r.drawImage(t,0,0)}function xi(e,t){let r=0,n=null;const i=Vn(async(s,o)=>(await hn(),await pn(e,s),i.isLatestSeq(o)));return{usesWorker:!1,usesPixi:!1,async loadAssets(s){const o=await hn(s);return n=o.visemePaths?new Set(o.visemePaths):null,o},getVisemeAtlasPaths(){return n},async renderSilOnly(){r+=1,i.reset(),await jo(e)},drawLiveFrame(s,o,a,f){i.enqueue(o,a,f)},async compositePrefetchFrame(s,o){try{return await Wo(s)}catch{return null}},blitBitmap(s,o){gn(s,o)},drawIdleVideo(){},beginIdleToSilCrossfade(){},tickIdleToSilCrossfade(){return!1},finishIdleToSilCrossfade(){},isIdleToSilCrossfading(){return!1},supportsBufferedPlayback:!0,async renderViseme(s,o){r+=1;const a=r;t.onStatus?.(o),await pn(s,{mouthPath:Wt(o),expressionPath:null})},dispose(){r+=1,i.reset()}}}function kc(e,t,r){let n=null,i=1,s=0,o=!1,a=!1,f=null;const h=new Map,l=new Map;let c=Sr;const p=Vn(async(B,_,x)=>(h.set(_,{drawKey:x.drawKey,onDisplayed:x.onDisplayed}),await M({type:"drawFrame",diffPath:B.mouthPath,expressionDiffPath:B.expressionPath,liveSeq:_},void 0,!0),!1)),y=B=>{if(B===ki){let N=-1,j;for(const[G,ie]of h)G>=N&&(N=G,j=ie);N>=0&&h.delete(N),j?.onDisplayed?.(j.drawKey);return}const _=-B,x=h.get(_);h.delete(_),x?.onDisplayed?.(x.drawKey)},E=new Map,g=(B,_)=>{a||!n||n.postMessage(B,[])},M=(B,_,x=!1)=>{if(a)return Promise.resolve();const N=i++;return new Promise((j,G)=>{E.set(N,{resolve:ie=>j(ie),reject:G,generation:typeof B.generation=="number"?B.generation:void 0,expectRenderDone:x}),g({...B,requestId:N})})},W=(async()=>{n=await Sc(r),n.onmessage=B=>{if(a)return;const _=B.data;if(_.type==="status"){t.onStatus?.(_.label);return}if(_.type==="frame"){if(_.generation<=-Sr){const j=-_.generation,G=l.get(j);l.delete(j),G?.resolve(_.bitmap);return}const N=_.generation<0;if(!N&&_.generation!==s){_.bitmap.close();return}if(N&&!(_.generation===ki)){const G=-_.generation;if(!p.isLatestSeq(G)){wt()?.onWorkerStale(),_.bitmap.close();return}}if(N&&t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()){wt()?.onWorkerStale(),_.bitmap.close();return}gn(e,_.bitmap),_.bitmap.close(),N&&y(_.generation);return}const x=E.get(_.requestId);if(x)switch(_.type){case"ready":E.delete(_.requestId),x.resolve();break;case"loadAssetsDone":E.delete(_.requestId),f=_.visemePaths?.length?new Set(_.visemePaths):null,x.resolve({width:_.width,height:_.height,visemePaths:_.visemePaths});break;case"renderDone":if(x.expectRenderDone&&x.generation!=null&&_.generation!==x.generation)return;E.delete(_.requestId),x.resolve();break;case"renderAborted":E.delete(_.requestId),x.resolve();break;case"error":E.delete(_.requestId),t.onError?.(_.message),x.reject(new Error(_.message));break}},n.onerror=B=>{if(a)return;const _=B.message||"Worker error";t.onError?.(_);for(const[,x]of E)x.reject(new Error(_));E.clear()},await M({type:"init"}),o=!0})();return{usesWorker:!0,usesPixi:!1,async loadAssets(B){if(a)return{width:842,height:1264};if(await W,a)return{width:842,height:1264};if(!o)throw new Error("Worker init failed");return await M({type:"loadAssets",keyHex:B,urls:wa(Rt())})??{width:842,height:1264}},getVisemeAtlasPaths(){return f},async renderSilOnly(){if(a||(await W,a))return;s+=1,p.reset(),h.clear(),l.forEach(({resolve:_})=>_(null)),l.clear(),c=Sr;const B=s;await M({type:"cancelLiveDraws"}),await M({type:"renderSil",generation:B},void 0,!0)},drawLiveFrame(B,_,x,N){a||W.then(()=>{a||p.enqueue(_,x,N)})},compositePrefetchFrame(B,_){return a?Promise.resolve(null):W.then(()=>{if(a)return null;const x=++c;return new Promise(N=>{l.set(x,{resolve:N}),M({type:"drawFrame",diffPath:B.mouthPath,expressionDiffPath:B.expressionPath,liveSeq:x},void 0,!0).catch(()=>{l.delete(x),N(null)})})})},blitBitmap(B,_){gn(B,_)},drawIdleVideo(){},beginIdleToSilCrossfade(){},tickIdleToSilCrossfade(){return!1},finishIdleToSilCrossfade(){},isIdleToSilCrossfading(){return!1},supportsBufferedPlayback:!0,async renderViseme(B,_,x={}){if(a||(await W,a))return;s+=1,p.reset(),h.clear();const N=s;try{await M({type:"cancelLiveDraws"}),await M({type:"renderViseme",generation:N,to:_,from:x.from,transitionDurationMs:x.transitionDurationMs,gapMs:x.gapMs,threshold:x.threshold},void 0,!0)}catch(j){if(j?.name==="AbortError")return;throw j}},dispose(){if(!a){a=!0,s+=1,p.reset(),h.clear(),l.forEach(({resolve:B})=>B(null)),l.clear(),c=Sr;for(const[,B]of E)B.resolve();E.clear(),n?.terminate(),n=null}}}}async function Ec(e,t){const r=await bc(e,{onWebGlContextLost:t.onWebGlContextLost,maxTextureSize:t.pixiMaxTextureSize});let n=0,i=null,s=!1;const o=Vn(async(a,f)=>s?!1:t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()?(wt()?.onWorkerStale(),!1):(r.drawLiveFrame(a),o.isLatestSeq(f)));return{usesWorker:!1,usesPixi:!0,async loadAssets(a){if(s)return{width:842,height:1264};const f=await r.loadAssets(a);return i=f.visemePaths?.length?new Set(f.visemePaths):null,f},getVisemeAtlasPaths(){return i},async renderSilOnly(){s||(n+=1,o.reset(),r.renderSilOnly())},drawLiveFrame(a,f,h,l){s||o.enqueue(f,h,l)},async compositePrefetchFrame(a,f){if(s)return null;try{return await r.compositePrefetchFrame(a)}catch{return null}},blitBitmap(a,f){s||t.shouldAcceptLiveFrame&&!t.shouldAcceptLiveFrame()||r.blitBitmap(f)},drawIdleVideo(a,f){s||r.drawIdleVideo(a,f)},beginIdleToSilCrossfade(a){s||r.beginIdleToSilCrossfade(a)},tickIdleToSilCrossfade(a){return s?!1:r.tickIdleToSilCrossfade(a)},finishIdleToSilCrossfade(){s||r.finishIdleToSilCrossfade()},isIdleToSilCrossfading(){return s?!1:r.isIdleToSilCrossfading()},supportsBufferedPlayback:!1,async renderViseme(a,f){if(s)return;n+=1;const h=n;o.reset(),t.onStatus?.(f),r.drawLiveFrame({mouthPath:Wt(f),expressionPath:null})},dispose(){s||(s=!0,n+=1,o.reset(),r.dispose())}}}function Ii(e,t){if(!Tc())return xi(e,t);const r=Zs(t.workerScriptUrl);try{return kc(e,t,r)}catch{return xi(e,t)}}function xc(e,t={}){if(t.preferLegacyRenderer)return Ii(e,t);let r=null,n=!1,i=null,s=!1;const o=()=>r?Promise.resolve(r):(i||(i=(async()=>{try{const a=await Ec(e,t);if(s)throw a.dispose(),new Error("Renderer disposed during Pixi init");return n=!0,r=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),r=Ii(e,t),n=!1,r}})()),i);return{get usesWorker(){return r?.usesWorker??!1},get usesPixi(){return n},async loadAssets(a){return(await o()).loadAssets(a)},getVisemeAtlasPaths(){return r?.getVisemeAtlasPaths()??null},async renderSilOnly(){return(await o()).renderSilOnly()},drawLiveFrame(a,f,h,l){o().then(c=>{s||c.drawLiveFrame(a,f,h,l)})},async compositePrefetchFrame(a,f){return(await o()).compositePrefetchFrame(a,f)},blitBitmap(a,f){r&&r.blitBitmap(a,f)},drawIdleVideo(a,f){r?.usesPixi&&r.drawIdleVideo(a,f)},beginIdleToSilCrossfade(a){r?.beginIdleToSilCrossfade(a)},tickIdleToSilCrossfade(a){return r?.tickIdleToSilCrossfade(a)??!1},finishIdleToSilCrossfade(){r?.finishIdleToSilCrossfade()},isIdleToSilCrossfading(){return r?.isIdleToSilCrossfading()??!1},get supportsBufferedPlayback(){return r?.supportsBufferedPlayback??!1},async renderViseme(a,f,h){return(await o()).renderViseme(a,f,h)},dispose(){s=!0,i=null,r?.dispose(),r=null}}}class Ic extends Error{constructor(t,r){super(`${t} timed out after ${Math.round(r/1e3)}s`),this.name="LoadTimeoutError"}}function nn(e,t,r){return new Promise((n,i)=>{const s=globalThis.setTimeout(()=>{i(new Ic(r,t))},t);e.then(o=>{globalThis.clearTimeout(s),n(o)},o=>{globalThis.clearTimeout(s),i(o)})})}const Ac={overflow:"hidden",position:"relative",display:"inline-block",lineHeight:0},Rc={display:"block",maxWidth:"100%",height:"auto"},Mc={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 sn(e){return Li(e)?Rn:Oi(e)?Fr:An}function ot(e,t){return t?.isSpeaking()||t?.isWarmingUp()?t:e.isSpeaking()||e.isWarmingUp()?e:t?.isConnected()?t:e}const Vs=u.forwardRef(function({id:t,avatarId:r,faceId:n,assets:i,authToken:s,apiBase:o,ttsEngineId:a,voiceId:f,language:h,speakingRate:l=or,className:c,style:p,canvasStyle:y,onStatusChange:E,onDisplayStatus:g,onError:M,onReady:W,showErrorOverlay:B=!0,loadingThumbnailUrl:_,onUserTranscript:x,onBotOutput:N,onRealtimeLipsyncDebug:j,onFrameRenderStats:G,lipsyncBufferedPlayback:ie=!0,lipsyncPlaybackWarmupMs:P=1500,idleHandoffHoldMs:V=tc,disableIdleVideo:Z=!1,fullBody:Q=!1,pixiMaxTextureSize:ue,captions:ae,userName:Re,userEmail:ke,userContext:ne},ze){const S=u.useRef(null),ee=Z||Q,$=u.useRef(null),H=u.useRef(null),de=u.useRef(ie);de.current=ie;const X=u.useRef(P);X.current=P;const se=u.useRef(V);se.current=V;const me=u.useRef(ee);me.current=ee;const he=u.useRef(0),K=u.useRef(Nn()),re=u.useRef(Po()),I=u.useRef(!1),b=u.useRef(null),d=u.useRef(null),m=u.useRef(0),k=u.useRef(0),O=u.useRef(0),F=u.useRef(null),te=u.useRef(null),C=u.useRef(!1),J=u.useRef(!1),T=u.useRef(!1),q=u.useRef(!1),Ee=u.useRef(!1),ye=u.useRef("sil"),De=u.useRef(0),Se=u.useRef(!1),ve=u.useRef(null),w=u.useRef(!1),[D,oe]=u.useState("idle"),[fe,we]=u.useState(null),[ge,Me]=u.useState(!1),[Ge,Ne]=u.useState(!1),[Ke,zt]=u.useState(!1),[nt,Gt]=u.useState(),[Mt,cr]=u.useState({width:842,height:1264}),[Pt,mt]=u.useState(null),[lr,jr]=u.useState(0),[ur,vt]=u.useState(null),[Kt,Ct]=u.useState(null),[qt,Le]=u.useState(!1),Ve=u.useRef(null),We=u.useRef(null),_t=u.useRef(!1),Je=u.useRef(s??null),it=o?.trim()||ut,bt=u.useRef(null),Fe=u.useRef(null),{ttsEngineId:qe,voiceId:Ft}=u.useMemo(()=>{const v=lt(a,f),A=v.ttsEngineId??Et;return{ttsEngineId:A,voiceId:v.voiceId??sn(A)}},[a,f]),st=u.useCallback(v=>{const A=Li(v);K.current.holdPp=A,H.current?.setHoldPp(A)},[]),ht=u.useRef(!1),dr=u.useRef({width:842,height:1264}),Bt=u.useRef(null),Wn=u.useRef("sil"),Yt=u.useRef(""),pt=u.useMemo(()=>$o(ae),[ae]),Ze=u.useCallback(()=>{Yt.current="",mt(null)},[]);u.useEffect(()=>{pt.enabled||Ze()},[pt.enabled,Ze]);const Hr=u.useCallback(v=>{if(!pt.enabled)return;const A=v.isSpeaking(),U=v.isWarmingUp();if(!A||U){Yt.current&&Ze();return}const L=Ho(v.getWordQueue());if(!L){Yt.current&&Ze();return}L!==Yt.current&&(Yt.current=L,mt(L))},[pt.enabled,Ze]),fr=u.useRef(void 0),$r=u.useRef(new Map),jn=u.useRef(W),Hn=u.useRef(E),Ce=u.useRef(g),$n=u.useRef(M),zn=u.useRef(x),zr=u.useRef(N),mr=u.useRef(j),Gn=u.useRef(G),Dt=u.useRef(ec());jn.current=W,Hn.current=E,Ce.current=g,$n.current=M,zn.current=x,zr.current=N,mr.current=j,Gn.current=G,u.useEffect(()=>{const v=Dt.current;return wi(v),()=>wi(null)},[]);const Gr=u.useCallback(v=>{const A=lt(v?.ttsEngineId??a,v?.voiceId??f),U=A.ttsEngineId??Fe.current?.ttsEngineId??Et,L=A.voiceId??Fe.current?.voiceId??sn(U);return{ttsEngineId:U,voiceId:L}},[a,f]),at=u.useCallback(v=>{we(v),zt(!0),$n.current?.(v)},[]),Qt=u.useCallback(v=>{oe(v),Hn.current?.(v)},[]),le=u.useRef(fn(Qt,it,{onLipsyncDebug:v=>mr.current?.(v),fullBody:Q})),_e=u.useRef(null),hr=u.useRef(!1),Kn=u.useRef(()=>{});u.useEffect(()=>(le.current=fn(Qt,it,{onLipsyncDebug:v=>mr.current?.(v),fullBody:Q}),s&&le.current.setDeveloperToken(s),le.current.setTtsEngineId(qe),le.current.setMuted(hr.current),()=>{le.current.stop();const v=_e.current;v&&(v.disconnect(),_e.current=null)}),[Qt,it,Q]),u.useEffect(()=>{if(!Q||D!=="speaking"){Le(!1);return}const v=Nt(ii(le.current.getWordQueue(),le.current.getPlaybackElapsedMs(),A=>Nt(A)!=null));We.current=v,Ct(v),Le(!0)},[Q,D]);const qn=u.useCallback(()=>(_e.current||(_e.current=ks(Qt,{speakingRate:l,language:h,fullBody:Q,waitForBodyIdle:()=>Ve.current?.waitForIdleCycleEnd()??null,onBodyIdleCancelled:()=>Ve.current?.resumeIdleLoop(),onUserTranscript:(v,A)=>zn.current?.(v,A),onBotOutput:v=>zr.current?.(v),onLipsyncDebug:v=>mr.current?.(v)}),_e.current.setTtsEngineId(qe),_e.current.setMuted(hr.current),Kn.current(!0)),_e.current),[Qt,l,h,qe,Q]),je=u.useCallback(()=>{F.current!=null&&(clearTimeout(F.current),F.current=null)},[]),Ue=u.useCallback(()=>{te.current!=null&&(clearTimeout(te.current),te.current=null),T.current=!1},[]),Kr=u.useCallback(()=>{Ee.current=!0,Ue(),ve.current?.setLooping(!1)},[Ue]),Qe=u.useCallback(()=>{Ee.current=!1,ve.current?.setLooping(!0)},[]),Xt=u.useCallback(()=>{if(q.current)return;const v=$.current;if(q.current=!0,Ee.current=!0,Ue(),C.current=!1,J.current=!1,!w.current||!ve.current){v?.renderSilOnly();return}const A=ve.current;A.setLooping(!1),A.setActive(!1);const U=A.getVideo();if(U.ended||Number.isFinite(U.currentTime)&&U.currentTime<=tn){try{(U.ended||U.currentTime>tn)&&(U.currentTime=0)}catch{}v?.renderSilOnly(),v?.finishIdleToSilCrossfade();return}if(v?.usesPixi){v.drawIdleVideo(U),v.beginIdleToSilCrossfade(vi);return}(async()=>{const Y=S.current;Y&&await en(Y,U,null,void 0,dr.current).catch(()=>{}),await new Promise(xe=>setTimeout(xe,vi)),q.current&&await v?.renderSilOnly()})()},[Ue]),Yn=u.useCallback(()=>{if(!(!w.current||!ve.current)){if(q.current=!1,$.current?.finishIdleToSilCrossfade(),$.current?.renderSilOnly(),Ue(),Ee.current){T.current=!1;return}T.current=!0,te.current=setTimeout(()=>{if(te.current=null,ot(le.current,_e.current).isSpeaking()){T.current=!1;return}if(C.current){T.current=!1;return}if(Ee.current){T.current=!1;return}const v=ve.current;if(!v){T.current=!1;return}Qe(),v.setLooping(!0),v.restart(),v.setActive(!0);const A=v.getVideo();let U=!1;const L=()=>{U||(U=!0,A.removeEventListener("playing",Y),T.current=!1)},Y=()=>{L()};if(A.addEventListener("playing",Y,{once:!0}),A.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&!A.paused){L();return}setTimeout(L,300)},se.current)}},[Ue,Qe]),Lt=u.useCallback(()=>{if(je(),Ce.current?.("sil"),C.current=!1,q.current=!1,!w.current||!ve.current){T.current=!1,Qe();return}Yn()},[je,Yn,Qe]),qr=u.useCallback(async v=>{const A=k.current,U=$.current,L=S.current,Y=()=>{v?.fallbackOnly||(C.current=!1)};if(!U||!L||!ge){Y();return}if(ot(le.current,_e.current).isSpeaking()){Y();return}if(v?.fallbackOnly){if(!C.current||($e(K.current),await U.renderSilOnly(),A!==k.current)||ot(le.current,_e.current).isSpeaking())return;Lt();return}if(_i(K.current)){$e(K.current),Lt();return}if(de.current&&U.supportsBufferedPlayback&&!v?.fallbackOnly){if($e(K.current),H.current?.reset(),await U.renderSilOnly(),A!==k.current||ot(le.current,_e.current).isSpeaking())return;Lt();return}const be=oc(ot(le.current,_e.current).getVisemeQueue(),De.current,ye.current),Pe=cc(be,Bt.current);if($e(K.current),!Pe){if(await U.renderSilOnly(),A!==k.current||ot(le.current,_e.current).isSpeaking())return;Lt();return}try{await U.renderViseme(L,"sil",{from:be,transitionDurationMs:Ls})}catch(Ie){if(Ie?.name!=="AbortError")throw Ie}if(A!==k.current){Y();return}if(ot(le.current,_e.current).isSpeaking()){Y();return}Lt()},[ge,Lt]),St=u.useCallback(()=>{if(J.current||C.current)return;J.current=!0,C.current=!0,je();const v=k.current;qr().finally(()=>{J.current=!1}),F.current=setTimeout(()=>{F.current=null,v===k.current&&qr({fallbackOnly:!0})},lc())},[je,qr]),Qn=u.useCallback(async()=>{const v=Math.floor(Date.now()/1e3);if(bt.current&&v<bt.current.expiresAt-60)return bt.current.key;const A=Je.current??await Tr();Je.current=A,le.current.setDeveloperToken(A);const U=await ma(A,it);return bt.current={key:U.value,expiresAt:U.expiresAt},U.value},[it]);u.useEffect(()=>{s&&(Je.current=s,le.current.setDeveloperToken(s))},[s]),u.useEffect(()=>{le.current.setTtsEngineId(qe),_e.current?.setTtsEngineId(qe),Fe.current&&(Fe.current.ttsEngineId=qe),st(qe)},[qe,st]),u.useEffect(()=>{Fe.current&&(Fe.current.voiceId=Ft)},[Ft]);const Ye=u.useMemo(()=>Vi(r,n),[r,n]),$s=u.useMemo(()=>i?JSON.stringify(i):Ye?`face:${Ye}`:`id:${t??""}`,[i,Ye,t]),zs=u.useMemo(()=>{const v=_?.trim();return v||(Zn(Ye)??Zn(nt)??oa(i))},[_,Ye,nt,i]);return u.useEffect(()=>{if(!t&&!i&&!Ye){at("AiTwin requires `assets`, `avatarId`/`faceId`, or `id`");return}let v=!1;ht.current=!1,Me(!1),Ne(!1),zt(!1),Gt(Ye),we(null),Fe.current=null,ve.current=null,w.current=!1;const A=S.current;if(!A)return;let U=null;return(async()=>{try{let L,Y,xe,be,Pe;if(i)L=i,Y=qe,xe=Ft;else if(Ye)Ce.current?.("loadFace"),L=un(Ye),Y=qe,xe=Ft;else{Ce.current?.("getAiTwin");const z=await nn(Ni(t),3e4,"getAiTwin");if(v)return;if(!z.faceId?.trim())throw new Error("getAiTwin returned no faceId");Gt(z.faceId.trim());const Ae=lt(a,f);Y=Ae.ttsEngineId??z.ttsEngineId,xe=Ae.voiceId??z.voiceId??sn(Y),be=bn(z),Pe=Sn(z),L=un(z.faceId)}Fe.current={ttsEngineId:Y,voiceId:xe,brainId:be,brainUrl:Pe},Wi(L),ve.current=Co();const Ie=!!(i&&!At(i));U=xc(A,{preferLegacyRenderer:Ie,pixiMaxTextureSize:ue,onStatus:z=>{v||Ce.current?.(z)},onError:z=>{v||at(z)},shouldAcceptLiveFrame:()=>{if(I.current)return!0;if(C.current)return!1;const z=ot(le.current,_e.current);return z.isSpeaking()||z.isWarmingUp()},onWebGlContextLost:()=>{v||_t.current||(_t.current=!0,queueMicrotask(()=>{v||jr(z=>z+1)}))}}),$.current=U,H.current=hc(U),st(Y),_t.current=!1;const Oe=z=>{const Ae=()=>{if(!z||X.current<=0)return!1;const Be=$.current;return Be?de.current&&Be.supportsBufferedPlayback?!0:Be.usesPixi:!1};le.current.setLipsyncWarmupHold(z,Ae),_e.current?.setLipsyncWarmupHold(z,Ae)};Kn.current=Oe,Oe(!0),Ce.current?.("auth");const et=Je.current??s??await nn(Tr(),3e4,"getAuthToken");if(v)return;Je.current=et,le.current.setDeveloperToken(et),le.current.setTtsEngineId(Y);const ce=$t()?await Qn():void 0;if(v)return;ce&&vt(ce),Ce.current?.("loadAssets");const pe=await nn(U.loadAssets(ce),Q?18e4:24e4,"load face assets");if(!v&&pe.width>0&&pe.height>0&&(dr.current=pe,cr(pe)),v)return;Bt.current=U.getVisemeAtlasPaths(),ht.current=!0,Me(!0),jn.current?.(),U.renderSilOnly().then(()=>{v||Ce.current?.("sil")}),(async()=>{try{if(me.current){w.current=!1,Ne(!1),await U.renderSilOnly();return}const z=await Sa(ce);if(await ve.current.load(z),v||(w.current=!0,Ne(!0),$e(K.current),await U.renderSilOnly(),v)||(await new Promise(Be=>setTimeout(Be,se.current)),v))return;ve.current.setActive(!0);const Ae=ve.current.getVideo();U.usesPixi?U.drawIdleVideo(Ae):await en(A,Ae,null,void 0,dr.current)}catch(z){if(v)return;w.current=!1,Ne(!1),console.warn("[AiTwin] Idle video unavailable:",z)}finally{v||(zt(!0),Ce.current?.("idle"))}})()}catch(L){if(v)return;if(L instanceof kr){at(L.message);return}at(L instanceof Error?L.message:"Failed to load AI twin")}})(),()=>{v=!0,ve.current?.dispose(),U?.dispose(),$.current=null}},[$s,i,Ye,t,qe,Ft,a,f,s,ue,ee,Qn,at,lr,st]),u.useEffect(()=>{const v={current:!1},A=()=>{const U=S.current,L=$.current,Y=ot(le.current,_e.current);if(!U||!L||!ge){m.current=requestAnimationFrame(A);return}if(document.hidden){ve.current?.setActive(!1),m.current=requestAnimationFrame(A);return}const xe=Y.isSpeaking(),be=Y.isWarmingUp(),Pe=xe&&!Se.current,Ie=Se.current&&!xe;Pe&&(je(),Ue(),C.current=!1,J.current=!1,$e(K.current),H.current?.reset(),Dt.current.reset(),fr.current=void 0,O.current=0,ye.current="sil",De.current=0,Xt()),Ie&&(re.current.reset(),ve.current?.setActive(!1),H.current?.reset(),L.finishIdleToSilCrossfade(),Ze(),We.current!==null&&(We.current=null,Ct(null)),Ee.current=!1,St());const Oe=Ie||C.current||T.current||q.current,et=ie&&L.supportsBufferedPlayback;if(Ee.current&&!xe&&!be&&!Ie&&!C.current&&!T.current){if(q.current){L.usesPixi&&L.isIdleToSilCrossfading()&&L.tickIdleToSilCrossfade(performance.now()),Se.current=xe,m.current=requestAnimationFrame(A);return}if(w.current&&ve.current){const ce=ve.current.getVideo();if(ce.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){const pe=ce.duration,z=ce.currentTime,Ae=ce.ended||Number.isFinite(z)&&z<=tn,Be=Number.isFinite(pe)&&pe>0&&Number.isFinite(z)?Math.max(0,(pe-z)*1e3):Number.POSITIVE_INFINITY;if(Ae||Be<=rc){Xt(),L.usesPixi&&L.isIdleToSilCrossfading()&&L.tickIdleToSilCrossfade(performance.now()),Se.current=xe,m.current=requestAnimationFrame(A);return}}}}if(be){if(Xt(),w.current&&ve.current?.setActive(!1),L.usesPixi&&L.isIdleToSilCrossfading()){L.tickIdleToSilCrossfade(performance.now()),Y.getVisemeQueue().length>0&&he.current===0&&(he.current=performance.now()),Se.current=Y.isSpeaking(),m.current=requestAnimationFrame(A);return}const ce=Y.getVisemeQueue();ce.length>0&&he.current===0&&(he.current=performance.now()),re.current.advance(performance.now());const pe=re.current.getExpressionPath(),z=re.current.getDrawKey(),Ae={queue:ce,elapsedMs:0,expressionPath:pe,expressionDrawKey:z,availablePaths:Bt.current};let Be=!1;et&&H.current?(H.current.warmupTick(Ae),Be=H.current.isWarmupReady(Ae,X.current)):L.usesPixi&&bi(U,ce,0,pe,z,K.current,(Ot,pr,Yr,gr)=>{L.drawLiveFrame(Ot,pr,Yr,He=>{gr?.(He),Y.isWarmingUp()&&He!==""&&!_i({lastDrawnKey:He})&&(he.current=0,Y.releaseWarmupHold())})},Ot=>{Ce.current?.(Ot.label)},Bt.current);const gt=he.current>0&&performance.now()-he.current>ta;Ce.current?.(Be?"buffer ready":"buffering lipsync…"),(Be||gt)&&(he.current=0,Y.releaseWarmupHold()),Hr(Y),Se.current=Y.isSpeaking(),m.current=requestAnimationFrame(A);return}if(xe){Xt(),w.current&&ve.current?.setActive(!1),L.usesPixi&&L.isIdleToSilCrossfading()&&L.finishIdleToSilCrossfade();const ce=Y.getVisemeQueue(),pe=Y.getPlaybackElapsedMs();Za(ce,pe),De.current=pe;const z=ce.length>0?ar(ce,pe):"sil";z!=="sil"&&(ye.current=z);const Ae=Lo(pe,Y.getSentenceEmotions(),Y.getWordQueue(),Y.getStreamMood());if(Q){const He=Nt(ii(Y.getWordQueue(),pe,Jt=>Nt(Jt)!=null));He!==We.current&&(We.current=He,Ct(He))}re.current.setTargetEmotion(Ae),re.current.setTargetEyebrow(Ro(pe,Y.getWordQueue(),It(Ae))),re.current.advance(performance.now());const Be=re.current.getExpressionPath(),gt=re.current.getDrawKey(),Ot=(He,Jt,Zt,Qr)=>{const Xn={label:Wn.current,elapsedMs:pe,mouthPath:Jt.mouthPath,transitionMeta:fr.current};$r.current.set(Zt,Xn),H.current?.markExternallyDisplayed(Zt,Be),L.drawLiveFrame(He,Jt,Zt,wr=>{const Gs=$r.current.get(wr)??Xn;$r.current.delete(wr),Dt.current.onDrawDisplayed(Gs,ce),H.current?.markExternallyDisplayed(wr,Be),Qr?.(wr)})},pr=He=>{Wn.current=He.label,fr.current=He.transitionMeta,Ce.current?.(He.label)},Yr=ie&&L.supportsBufferedPlayback;let gr=!1;Yr&&H.current&&(gr=H.current.tick({canvas:U,queue:ce,elapsedMs:pe,expressionPath:Be,expressionDrawKey:gt,playbackState:K.current,availablePaths:Bt.current,onStatus:pr,onDisplayed:(Jt,Zt,Qr)=>{Dt.current.onDrawDisplayed({label:Qr,elapsedMs:pe,mouthPath:Zt,transitionMeta:fr.current},ce)}}).usedBuffer),gr||bi(U,ce,pe,Be,gt,K.current,Ot,pr,Bt.current),Dt.current.onRafTickSpeaking(),Gn.current?.(Dt.current.snapshot(ce,pe))}else if(!Oe&&I.current){ve.current?.setActive(!1),re.current.advance(performance.now());const ce=re.current.getExpressionPath(),pe=re.current.getDrawKey();rn(U,ce,pe,K.current,(z,Ae,Be,gt)=>L.drawLiveFrame(z,Ae,Be,gt),z=>{if(d.current){Ce.current?.(d.current);return}const Ae=re.current.getTargetEmotion();Ce.current?.(z==="sil"||z==="blink"?`${Ae}${z==="blink"?" · blink":""}`:z)},null,b.current)}else if(!Oe&&w.current&&ve.current){const ce=ve.current,pe=ce.getVideo();if(pe.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA){ce.setActive(!0);const z=()=>!Y.isSpeaking()&&!C.current&&!T.current&&!I.current;L.usesPixi?(L.drawIdleVideo(pe,z),z()&&Ce.current?.("idle")):v.current||(v.current=!0,en(U,pe,null,void 0,dr.current,z).then(()=>Ce.current?.("idle")).finally(()=>{v.current=!1}))}else rn(U,null,"__sil__",K.current,(z,Ae,Be,gt)=>L.drawLiveFrame(z,Ae,Be,gt),z=>Ce.current?.(z))}else Oe||rn(U,null,"__sil__",K.current,(ce,pe,z,Ae)=>L.drawLiveFrame(ce,pe,z,Ae),ce=>Ce.current?.(ce));pt.enabled&&Hr(Y),Se.current=xe,m.current=requestAnimationFrame(A)};return m.current=requestAnimationFrame(A),()=>{cancelAnimationFrame(m.current),je(),Ue(),le.current.stop(),_e.current?.stop()}},[ge,Ge,St,je,Ue,Xt,Hr,Ze,pt.enabled,Q]),u.useImperativeHandle(ze,()=>({speakText:async(v,A)=>{const U=v.trim();if(!U)return;const L=$.current;if(!L||!ht.current&&!ge)throw new Error("AI twin is not ready");const{ttsEngineId:Y,voiceId:xe}=Gr(A);we(null),Ze(),k.current+=1,je(),Ue(),C.current=!1,J.current=!1,ye.current="sil",De.current=0,$e(K.current),st(Y),I.current=!1,b.current=null,d.current=null,re.current.reset(),Se.current=!1,Kr(),q.current=!1,L.finishIdleToSilCrossfade();try{const be=A?.fullBody??Q,Pe=Ve.current,Ie=!!(be&&Pe),Oe=Ie?Pe.waitForIdleCycleEnd():null,et=le.current.speak(U,{voiceId:xe,speakingRate:A?.speakingRate??l,ttsEngineId:Y,language:A?.language??h,fullBody:be,delayPlayback:Ie});if(Oe){try{await Promise.race([Oe.promise,et.then(()=>new Promise(()=>{}))])}catch(ce){throw Oe.cancel(),le.current.releasePlaybackHold(),Pe.resumeIdleLoop(),ce}le.current.releasePlaybackHold()}await et}catch(be){throw Qe(),q.current=!1,L.finishIdleToSilCrossfade(),St(),at(be instanceof Error?be.message:"TTS failed"),be}},speakWithReply:async(v,A)=>{const U=v.trim();if(!U)return{displayText:"",spokenText:""};const L=$.current;if(!L||!ht.current&&!ge)throw new Error("AI twin is not ready");const{ttsEngineId:Y,voiceId:xe}=Gr(A);we(null),Ze(),k.current+=1,je(),Ue(),C.current=!1,J.current=!1,ye.current="sil",De.current=0,$e(K.current),st(Y),I.current=!1,b.current=null,d.current=null,re.current.reset(),Se.current=!1,Kr(),q.current=!1,L.finishIdleToSilCrossfade();const be=A?.brainId?.trim()||Fe.current?.brainId?.trim()||void 0,Pe=A?.brainUrl?.trim()||Fe.current?.brainUrl?.trim()||void 0;try{const Ie=A?.fullBody??Q,Oe=Ve.current,et=!!(Ie&&Oe),ce=et?Oe.waitForIdleCycleEnd():null,pe=le.current.speakWithReply(U,{...A,voiceId:xe,speakingRate:A?.speakingRate??l,ttsEngineId:Y,language:A?.language??h,fullBody:Ie,delayPlayback:et,brainId:be,brainUrl:Pe,userName:A?.userName?.trim()||Re?.trim()||void 0,userEmail:A?.userEmail?.trim()||ke?.trim()||void 0,userContext:A?.userContext?.trim()||ne?.trim()||void 0,onDisplayText:z=>{A?.onDisplayText?.(z),zr.current?.(z)}});if(ce){try{await Promise.race([ce.promise,pe.then(()=>new Promise(()=>{}))])}catch(z){throw ce.cancel(),le.current.releasePlaybackHold(),Oe.resumeIdleLoop(),z}le.current.releasePlaybackHold()}return await pe}catch(Ie){throw Qe(),q.current=!1,L.finishIdleToSilCrossfade(),St(),at(Ie instanceof Error?Ie.message:"speakWithReply failed"),Ie}},stop:()=>{k.current+=1,je(),Ue(),C.current=!1,J.current=!1,q.current=!1,Qe(),$.current?.finishIdleToSilCrossfade(),le.current.stop(),_e.current?.stop(),$e(K.current),H.current?.reset(),he.current=0,Se.current=!1,Ze(),St()},setTtsEngineId:v=>{le.current.setTtsEngineId(v),_e.current?.setTtsEngineId(v),Fe.current&&(Fe.current.ttsEngineId=v),st(v)},renderViseme:async(v,A)=>{const U=$.current,L=S.current;if(!U||!L||!ht.current)throw new Error("AI twin is not ready");await U.renderViseme(L,v,{from:A?.from,transitionDurationMs:A?.transitionDurationMs,gapMs:A?.gapMs,onStatus:Y=>Ce.current?.(Y)})},setEmotion:v=>{if(!ht.current)throw new Error("AI twin is not ready");const A=$.current,U=S.current;if(!A||!U)throw new Error("AI twin is not ready");k.current+=1,je(),Ue(),C.current=!1,J.current=!1,T.current=!1,q.current=!1,Qe(),le.current.stop(),_e.current?.stop(),$e(K.current),H.current?.reset(),he.current=0,Se.current=!1,A.finishIdleToSilCrossfade(),ve.current?.setActive(!1);const L=ct(v);I.current=!0,b.current=null,d.current=null,re.current.snapToEmotion(L);const Y=re.current.getExpressionPath(),xe=re.current.getDrawKey(),be={mouthPath:null,expressionPath:Y},Pe=ir(be,xe);K.current.lastDrawnKey="",A.drawLiveFrame(U,be,Pe,Oe=>{Oe===Pe&&(K.current.lastDrawnKey=Pe)});const Ie=It(L);Ce.current?.(Y?`${L} · brow ${Ie>0?"+":""}${Ie}`:`${L} · brow 0 (sil base)`)},getEmotion:()=>I.current?re.current.getTargetEmotion():null,clearEmotionPreview:()=>{I.current=!1,b.current=null,d.current=null,re.current.reset(),$e(K.current),Ce.current?.("idle")},setViseme:v=>{if(!ht.current)throw new Error("AI twin is not ready");const A=$.current,U=S.current;if(!A||!U)throw new Error("AI twin is not ready");k.current+=1,je(),Ue(),C.current=!1,J.current=!1,T.current=!1,q.current=!1,Qe(),le.current.stop(),_e.current?.stop(),$e(K.current),H.current?.reset(),he.current=0,Se.current=!1,A.finishIdleToSilCrossfade(),ve.current?.setActive(!1);const L=Dr(v);I.current=!0,d.current=L,b.current=L==="sil"?null:Wt(L),re.current.snapToEmotion("neutral");const Y=re.current.getExpressionPath(),xe=re.current.getDrawKey(),Pe={mouthPath:b.current,expressionPath:Y},Ie=ir(Pe,xe);K.current.lastDrawnKey="",A.drawLiveFrame(U,Pe,Ie,Oe=>{Oe===Ie&&(K.current.lastDrawnKey=Ie)}),Ce.current?.(L)},getViseme:()=>I.current?d.current:null,isReady:()=>ht.current,getStatus:()=>D,getWordQueue:()=>le.current.getWordQueue(),connect:async(v={})=>{we(null);try{let A=v.authToken?.trim();A||(A=Je.current??s??await Tr(),Je.current=A);const U=lt(v.ttsEngineId??a,v.voiceId??f),L=U.voiceId??Fe.current?.voiceId,Y=v.brainId?.trim()||v.personaId?.trim()||Fe.current?.brainId,xe=v.brainUrl?.trim()||Fe.current?.brainUrl,be=U.ttsEngineId??Fe.current?.ttsEngineId??qe,Pe=qn();be&&Pe.setTtsEngineId(be),be&&st(be),await Pe.unlockAudio(),await Pe.connect({...v,apiBase:v.apiBase?.trim()||it,authToken:A,voiceId:L,brainId:Y,brainUrl:xe,ttsEngineId:be,speakingRate:v.speakingRate??l,language:v.language??h,fullBody:v.fullBody??Q,userName:v.userName?.trim()||Re?.trim()||void 0,userEmail:v.userEmail?.trim()||ke?.trim()||void 0,userContext:v.userContext?.trim()||ne?.trim()||void 0})}catch(A){throw rr(A)||at(A instanceof Error?A.message:"Voice connect failed"),A}},disconnect:async()=>{const v=_e.current;v&&(k.current+=1,je(),Ue(),C.current=!1,J.current=!1,q.current=!1,Qe(),$.current?.finishIdleToSilCrossfade(),$e(K.current),H.current?.reset(),he.current=0,Se.current=!1,await v.disconnect(),St())},isConnected:()=>_e.current?.isConnected()??!1,getVoiceStream:()=>_e.current?.getVoiceStream()??le.current?.getVoiceStream()??null,setMuted:v=>{hr.current=v,le.current?.setMuted(v),_e.current?.setMuted(v)},isMuted:()=>hr.current,getBrainId:()=>Fe.current?.brainId?.trim()||null,getPersonaId:()=>Fe.current?.brainId?.trim()||null,getBrainUrl:()=>Fe.current?.brainUrl?.trim()||null}),[ge,l,h,s,Re,ke,ne,qe,Ft,je,Ue,St,Kr,Qe,at,Gr,qn,st,D,it]),R.jsxs("div",{className:c,style:{...Ac,...p},children:[R.jsx("canvas",{ref:S,width:Mt.width,height:Mt.height,style:{...Rc,...y},"aria-label":t?`AI twin ${t}`:"AI twin face"}),Q&&ge&&ur&&(nt||Ye)?R.jsx(Aa,{ref:Ve,poseSynced:qt,gesturesBase:Xi(nt||Ye),keyHex:ur,status:D,activePose:Kt}):null,!Ke&&!fe?R.jsx(Jo,{thumbnailUrl:zs}):null,B&&fe?R.jsx("div",{style:Mc,children:fe}):null,pt.enabled&&Pt?R.jsx(qo,{text:Pt,style:pt.style},Pt):null]})});function Pc({muted:e}){return e?R.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[R.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),R.jsx("path",{d:"m16 9.5 5 5m0-5-5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}):R.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[R.jsx("path",{d:"M11 5 6.5 9H3v6h3.5L11 19V5Z",fill:"currentColor"}),R.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 Cc(){return R.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:R.jsx("path",{d:"M8 5.5v13l11-6.5L8 5.5Z"})})}function Fc(){return R.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:R.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}function Bc(){return R.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:R.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 Dc(){return R.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:R.jsx("path",{d:"M15 6 9 12l6 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Lc(){return R.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:R.jsx("path",{d:"M12 19V5m0 0-6 6m6-6 6 6",stroke:"currentColor",strokeWidth:"2.25",strokeLinecap:"round",strokeLinejoin:"round"})})}function Oc(){return R.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:R.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}function Ai({className:e}){return R.jsx("span",{className:e??"aitwin-widget__spinner","aria-hidden":!0,children:R.jsx("svg",{viewBox:"0 0 24 24",fill:"none",children:R.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeDasharray:"40 20"})})})}function Nc({muted:e,onToggle:t}){return R.jsx("button",{type:"button",className:"aitwin-widget__mute",onClick:t,"aria-label":e?"Unmute":"Mute","aria-pressed":e,children:R.jsx(Pc,{muted:e})})}function Uc(e){const t=e.status==="speaking",r=e.connecting||e.textSending||e.status==="loading"||t,n=e.connected?"End":"Talk",i=["aitwin-widget__action","aitwin-widget__action--primary",e.connecting?"aitwin-widget__action--connecting":""].filter(Boolean).join(" ");return R.jsxs("div",{className:e.textMode?"aitwin-widget__controls aitwin-widget__controls--text":"aitwin-widget__controls",children:[e.textMode?R.jsxs("form",{className:"aitwin-widget__composer",onSubmit:s=>{if(s.preventDefault(),t){e.onStopSpeech();return}e.onSendText()},children:[R.jsx("button",{type:"button",className:"aitwin-widget__composer-back",onClick:e.onTextMode,disabled:e.textSending&&!t,"aria-label":"Back",children:R.jsx(Dc,{})}),R.jsx("input",{type:"text",className:"aitwin-widget__composer-input",value:e.textDraft,onChange:s=>e.onTextDraftChange(s.target.value),placeholder:t?"Speaking…":e.textSending?"Getting reply...":"Type a message...",autoComplete:"off",disabled:!e.ready||r&&!t,autoFocus:!0}),t?R.jsx("button",{type:"button",className:"aitwin-widget__composer-send aitwin-widget__composer-send--stop",onClick:e.onStopSpeech,"aria-label":"Stop",children:R.jsx(Oc,{})}):R.jsx("button",{type:"submit",className:"aitwin-widget__composer-send",disabled:!e.ready||r||!e.textDraft.trim()&&!e.textSending,"aria-label":"Send","aria-busy":e.textSending,children:e.textSending?R.jsx(Ai,{className:"aitwin-widget__spinner aitwin-widget__spinner--on-accent"}):R.jsx(Lc,{})})]}):R.jsxs("div",{className:"aitwin-widget__actions",children:[R.jsxs("button",{type:"button",className:i,onClick:e.onTalk,disabled:!e.ready||e.connecting||e.textSending,"aria-busy":e.connecting,"aria-label":e.connecting?"Connecting":n,children:[e.connecting?R.jsx(Ai,{className:"aitwin-widget__spinner aitwin-widget__spinner--on-accent"}):e.connected?R.jsx(Fc,{}):R.jsx(Cc,{}),R.jsx("span",{children:n})]}),R.jsxs("button",{type:"button",className:"aitwin-widget__action",onClick:e.onTextMode,disabled:!e.ready||e.connecting||e.textSending,"aria-pressed":!1,children:[R.jsx(Bc,{}),R.jsx("span",{children:"Text"})]})]}),e.error?R.jsx("p",{className:"aitwin-widget__controls-error",role:"alert",children:e.error}):null]})}const Ri=97,Vc=3500;function Wc(e,t){const r=Math.max(0,e),n=1-Math.exp(-r/Vc);return Math.min(Ri,Math.round(n*Ri))}function jc(e){const[t,r]=u.useState(null),[n,i]=u.useState(()=>Date.now());return u.useEffect(()=>{if(!e){r(null);return}const s=Date.now();r(s),i(s);let o=0;const a=()=>{i(Date.now()),o=window.requestAnimationFrame(a)};return o=window.requestAnimationFrame(a),()=>{window.cancelAnimationFrame(o)}},[e]),e?t==null?0:Wc(n-t):100}const Hc="M259.01,593.87v-101.49c.33-6.31,4.94-11.26,10.21-11.88,6.42-.75,13.18,4.99,13.13,12.92-.42,45.09-.83,90.17-1.25,135.26.03,1.56.56,15.43,11.95,23.2,6.18,4.21,12.57,4.6,15.42,4.58-.42-112.77-.83-225.54-1.25-338.31-.08-2.55-1.03-46.36,21.17-55.34,2.05-.83,4.42-1.41,7.17-1.56v453.42c.07,12.06,1.98,37.84,19.03,62.73,7.01,10.23,14.79,17.71,21.4,22.99V222.42c-.01-3.72.48-11.67,5.35-19.87,7-11.77,18.13-15.82,21.4-16.95,10.42-3.61,19.49-2.06,23.48-1.11v684.96c.59,4.03,1.78,9.72,4.45,16.12,1.93,4.63,8.84,20.57,26.47,31.26,13.48,8.18,26.56,9.23,32.86,9.31-1.3-256.11-2.59-512.22-3.89-768.33.76-16.43,14.57-28.94,29.73-28.34,13.53.53,25.39,11.39,27.23,25.84-1.1,264.68-2.2,529.35-3.3,794.03,4.33.92,22.38,4.25,38.94-6.53,10.26-6.68,15.24-15.72,17.09-19.17,5.55-10.36,6.42-19.98,6.53-25.01-.72-246.99-1.43-493.97-2.15-740.96,2.27-.06,34.75-.44,48.29,22.68,3.41,5.83,4.87,11.86,5.34,17.19v674.68c5.92-2.16,39.19-14.94,50.16-47.79,3.12-9.34,3.68-18.03,3.33-25.01.03-193.22.06-386.43.09-579.65,4.12,1.18,28.28,8.48,36.17,30.08,1.64,4.49,2.32,8.88,2.43,12.92.02,146.42.05,292.84.07,439.25,3.82-1.71,19.51-9.22,25.56-26.47,2.15-6.12,2.48-11.73,2.29-15.89.01-114.91.03-229.81.04-344.72,2.36-.1,7.51.02,12.74,3.13,9.1,5.4,10.87,15.35,11.12,16.88.35,11.49.69,22.97,1.04,34.46.46,37.05.93,74.1,1.39,111.15v152.69c3.39-.72,9.77-2.67,14.31-8.34,3.62-4.52,4.51-9.46,5.56-15.28.91-5.04.95-9.31.83-12.23.02-38.81.03-77.62.05-116.43";function $c({className:e="aitwin-widget__logo",strokeWidth:t=15,durationMs:r=2600,delayMs:n=0,loop:i=!1}){return R.jsx("svg",{viewBox:"0 0 1080 1080",className:e,role:"img","aria-label":"AITWIN logo",children:R.jsx("path",{className:i?"aitwin-widget__logo-draw aitwin-widget__logo-draw--loop":"aitwin-widget__logo-draw",d:Hc,fill:"none",stroke:"currentColor",strokeWidth:t,strokeMiterlimit:10,pathLength:1,style:{animationDuration:`${r}ms`,animationDelay:`${n}ms`}})})}function zc({progress:e}){const t=Math.max(0,Math.min(100,Math.round(e)));return R.jsx("div",{className:"aitwin-widget__face-loading","aria-live":"polite","aria-label":`Loading ${t} percent`,children:R.jsxs("div",{className:"aitwin-widget__face-loading-content",children:[R.jsx($c,{className:"aitwin-widget__logo",loop:!0,durationMs:2600}),R.jsxs("div",{className:"aitwin-widget__face-loading-bar-wrap",children:[R.jsx("div",{role:"progressbar","aria-valuenow":t,"aria-valuemin":0,"aria-valuemax":100,className:"aitwin-widget__face-loading-track",children:R.jsx("div",{className:"aitwin-widget__face-loading-fill",style:{width:`${t}%`}})}),R.jsxs("p",{className:"aitwin-widget__face-loading-pct",children:[t,"%"]})]})]})})}function Mi(e){const t=e.id?.trim()||void 0,r=e.faceId?.trim()||e.avatarId?.trim()||void 0;return{id:r?void 0:t,faceId:r,authToken:e.authToken?.trim()||void 0,apiBase:e.apiBase?.trim()||void 0,voiceId:e.voiceId?.trim()||void 0,speakingRate:e.speakingRate,language:e.language}}function Gc(e){return[e.id??"",e.faceId??"",e.authToken?.slice(0,16)??"",e.voiceId??"",e.apiBase??"",String(e.speakingRate??"")].join("|")}const Pi={display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",lineHeight:0},Kc={display:"block",height:"100%",width:"100%",objectFit:"cover",objectPosition:"top"},qc=u.forwardRef(function({options:t},r){const n=u.useRef(null),i=u.useRef(t);i.current={...i.current,onReady:t.onReady,onStatusChange:t.onStatusChange,onError:t.onError,onUserTranscript:t.onUserTranscript,onBotOutput:t.onBotOutput};const[s,o]=u.useState(!!t.showControls),[a,f]=u.useState(()=>Mi(t)),[h,l]=u.useState(!1),[c,p]=u.useState(!1),[y,E]=u.useState(!1),[g,M]=u.useState(!1),[W,B]=u.useState("idle"),[_,x]=u.useState(null),[N,j]=u.useState(!1),[G,ie]=u.useState(!1),[P,V]=u.useState(""),[Z,Q]=u.useState(!1),[ue,ae]=u.useState([]),[Re,ke]=u.useState(t.brainId?.trim()||t.personaId?.trim()||void 0),[ne,ze]=u.useState(t.brainUrl?.trim()||void 0),S=u.useCallback(T=>{i.current={...i.current,...T},T.showControls!==void 0&&o(!!T.showControls),(T.brainId!==void 0||T.personaId!==void 0)&&ke((T.brainId??T.personaId)?.trim()||void 0),T.brainUrl!==void 0&&ze(T.brainUrl.trim()||void 0),f(q=>Mi({id:T.id??q.id,faceId:T.faceId??T.avatarId??q.faceId,authToken:T.authToken??q.authToken,apiBase:T.apiBase??q.apiBase,voiceId:T.voiceId??q.voiceId,speakingRate:T.speakingRate??q.speakingRate,language:T.language??q.language}))},[]);u.useImperativeHandle(r,()=>({getTwin:()=>n.current,applyOptions:S}),[S]),u.useEffect(()=>{S(t)},[S,t.id,t.faceId,t.avatarId,t.authToken,t.apiBase,t.voiceId,t.speakingRate,t.showControls,t.brainId,t.personaId,t.brainUrl]);const ee=u.useCallback(()=>{l(!0),x(null)},[]),$=u.useCallback(T=>{T==="idle"&&p(!0)},[]),H=u.useCallback(T=>{B(T),i.current.onStatusChange?.(T)},[]),de=u.useRef(!1);de.current=h&&c;const X=u.useCallback(T=>{if(M(!1),rr(T)){ie(!0),x(null);return}x(T),de.current||(l(!1),p(!1)),i.current.onError?.(T)},[]),se=u.useCallback((T,q)=>{i.current.onUserTranscript?.(T,q)},[]),me=u.useCallback(T=>{i.current.onBotOutput?.(T)},[]);u.useEffect(()=>{if(!s)return;const T=window.setInterval(()=>{E(!!n.current?.isConnected())},400);return()=>window.clearInterval(T)},[s,a]);const he=Gc(a),K=!!(a.id||a.faceId),re=h&&c,I=K&&!re&&!_,b=jc(I),d=u.useRef(he);u.useEffect(()=>{re&&i.current.onReady?.()},[re]),u.useEffect(()=>{re&&n.current?.setMuted(N)},[re,N,a]),u.useEffect(()=>{ae([])},[a.id,a.faceId]),u.useEffect(()=>{d.current!==he&&(d.current=he,l(!1),p(!1),x(null),M(!1),E(!1),B("idle"))},[he]);const m=u.useCallback(()=>{ie(!0),x(null),M(!1),E(!1)},[]),k=()=>{const T=n.current;if(!T?.isReady())return;if(x(null),T.isConnected()){M(!1),ie(!1),T.disconnect().finally(()=>{E(!1)});return}M(!0);const q={authToken:a.authToken,voiceId:a.voiceId,speakingRate:a.speakingRate,language:a.language,apiBase:a.apiBase,...Re?{brainId:Re}:{},...ne?{brainUrl:ne}:{}};(async()=>{if(await eo()){m();return}ie(!1);try{await T.connect(q),E(!!T.isConnected())}catch(Ee){if(rr(Ee)){m();return}const ye=Ee instanceof Error?Ee.message:"Failed to connect voice.";x(ye),i.current.onError?.(ye)}finally{M(!1)}})()},O=()=>{ie(T=>!T),x(null)},F=u.useRef(0),te=()=>{const T=P.trim(),q=n.current;if(!T||!q?.isReady()||Z)return;x(null),V(""),Q(!0);const Ee=++F.current;i.current.onUserTranscript?.(T,!0),(async()=>{try{const ye=Re||q.getBrainId()?.trim()||void 0,De=ne||q.getBrainUrl()?.trim()||void 0,Se=await q.speakWithReply(T,{brainId:ye,brainUrl:De,history:ue,voiceId:a.voiceId,speakingRate:a.speakingRate,language:a.language});if(Ee!==F.current)return;Se.displayText&&ae(ve=>[...ve,{role:"user",content:T},{role:"assistant",content:Se.displayText}])}catch(ye){if(Ee!==F.current)return;const De=ye instanceof Error?ye.message:"Failed to get reply.";x(De),i.current.onError?.(De)}finally{Ee===F.current&&Q(!1)}})()},C=()=>{F.current+=1,n.current?.stop(),Q(!1)},J=()=>{const T=!N;j(T),n.current?.setMuted(T)};return R.jsxs("div",{className:"aitwin-widget__layout",children:[R.jsxs("div",{className:"aitwin-widget__stage",children:[K?R.jsx("div",{style:Pi,children:R.jsx(Vs,{ref:n,id:a.id,faceId:a.faceId,authToken:a.authToken,apiBase:a.apiBase,voiceId:a.voiceId,speakingRate:a.speakingRate,language:a.language,fullBody:t.fullBody,style:Pi,canvasStyle:Kc,onReady:ee,onDisplayStatus:$,onStatusChange:H,onError:X,onUserTranscript:se,onBotOutput:me,loadingThumbnailUrl:t.loadingThumbnailUrl},he)}):R.jsx("p",{className:"aitwin-widget__hint",style:{padding:16},children:"Pass id or faceId to load a twin."}),I?R.jsx(zc,{progress:b}):null,s?R.jsx(Nc,{muted:N,onToggle:J}):null]}),s?R.jsx(Uc,{ready:re,connected:y,connecting:g,status:W,textMode:G,textDraft:P,textSending:Z,error:_,onTalk:k,onTextMode:O,onTextDraftChange:V,onSendText:te,onStopSpeech:C}):null]})}),Yc=".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-composer-width: calc(340px * var(--aitwin-size));--aitwin-composer-height: calc(40px * var(--aitwin-size));--aitwin-action-height: calc(32px * 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));--aitwin-float-inset: 20px;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{align-items:flex-end;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__controls--text{max-width:calc(100vw - (2 * var(--aitwin-float-inset)));width:var(--aitwin-composer-width)}.aitwin-widget__actions{align-items:center;display:flex;gap:var(--aitwin-action-gap);width:100%}.aitwin-widget__action{align-items:center;appearance:none;background:transparent;border:1.5px solid var(--aitwin-accent);border-radius:999px;box-sizing:border-box;color:var(--aitwin-accent);cursor:pointer;display:inline-flex;flex:1 1 0;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;line-height:1;margin:0;min-height:var(--aitwin-action-height);min-width:0;overflow:hidden;padding:0 calc(10px * var(--aitwin-size))}.aitwin-widget__action span{display:inline-flex;line-height:1}.aitwin-widget__action svg{display:block;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:var(--aitwin-accent);color:#fff}.aitwin-widget__action--primary:hover:not(:disabled){background:var(--aitwin-accent-hover);border-color:var(--aitwin-accent-hover)}.aitwin-widget__action--connecting:disabled{cursor:progress;opacity:1}.aitwin-widget__spinner{display:inline-flex;flex-shrink:0;height:calc(12px * var(--aitwin-size));width:calc(12px * var(--aitwin-size))}.aitwin-widget__spinner svg{animation:aitwin-widget-spin .8s linear infinite;display:block;height:100%;width:100%}.aitwin-widget__spinner--on-accent,.aitwin-widget__action .aitwin-widget__spinner{color:#fff}@keyframes aitwin-widget-spin{to{transform:rotate(360deg)}}.aitwin-widget__face-loading{background:transparent;inset:0;overflow:hidden;pointer-events:none;position:absolute;z-index:4}.aitwin-widget__face-loading-content{align-items:center;display:flex;flex-direction:column;gap:calc(12px * var(--aitwin-size));inset:0;justify-content:center;padding:calc(24px * var(--aitwin-size));position:absolute;z-index:1}.aitwin-widget__logo{color:#fff;display:block;flex-shrink:0;height:calc(64px * var(--aitwin-size));margin-bottom:calc(4px * var(--aitwin-size));width:calc(64px * var(--aitwin-size))}.aitwin-widget__logo-draw{stroke-dasharray:1;stroke-dashoffset:1;animation:aitwin-widget-logo-draw 2.6s ease-in-out forwards}.aitwin-widget__logo-draw--loop{animation:aitwin-widget-logo-draw-loop 2.6s ease-in-out infinite}@keyframes aitwin-widget-logo-draw{to{stroke-dashoffset:0}}@keyframes aitwin-widget-logo-draw-loop{0%{stroke-dashoffset:1}45%{stroke-dashoffset:0}55%{stroke-dashoffset:0}to{stroke-dashoffset:-1}}@media(prefers-reduced-motion:reduce){.aitwin-widget__logo-draw,.aitwin-widget__logo-draw--loop{animation:none;stroke-dashoffset:0}}.aitwin-widget__face-loading-bar-wrap{max-width:calc(220px * var(--aitwin-size));width:100%}.aitwin-widget__face-loading-track{background:#fff3;border-radius:999px;height:calc(4px * var(--aitwin-size));overflow:hidden;width:100%}.aitwin-widget__face-loading-fill{background:var(--aitwin-accent);border-radius:999px;height:100%;transition:width .3s ease-out}.aitwin-widget__face-loading-pct{color:#ffffffbf;font-size:calc(12px * var(--aitwin-size));margin:calc(8px * var(--aitwin-size)) 0 0;text-align:center}.aitwin-widget__composer{align-items:center;background:#fff;border:1.5px solid var(--aitwin-accent);border-radius:999px;display:flex;gap:calc(4px * var(--aitwin-size));height:var(--aitwin-composer-height);padding:calc(4px * var(--aitwin-size));width:100%}.aitwin-widget__composer-back{align-items:center;background:transparent;border:none;border-radius:999px;color:#9ca3af;cursor:pointer;display:inline-flex;flex-shrink:0;height:calc(30px * var(--aitwin-size));justify-content:center;padding:0;width:calc(30px * var(--aitwin-size))}.aitwin-widget__composer-back:hover:not(:disabled){color:#4b5563}.aitwin-widget__composer-back:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__composer-back svg{display:block;height:calc(16px * var(--aitwin-size));width:calc(16px * var(--aitwin-size))}.aitwin-widget__composer-input{background:transparent;border:none;color:#111827;flex:1;font-family:inherit;font-size:calc(14px * var(--aitwin-size));min-width:0;outline:none;padding:0 calc(4px * var(--aitwin-size))}.aitwin-widget__composer-input::placeholder{color:#9ca3af}.aitwin-widget__composer-input:disabled{opacity:.7}.aitwin-widget__composer-send{align-items:center;background:var(--aitwin-accent);border:none;border-radius:999px;color:#fff;cursor:pointer;display:inline-flex;flex-shrink:0;height:calc(30px * var(--aitwin-size));justify-content:center;padding:0;width:calc(30px * var(--aitwin-size))}.aitwin-widget__composer-send:hover:not(:disabled){background:var(--aitwin-accent-hover)}.aitwin-widget__composer-send:disabled{cursor:not-allowed;opacity:.45}.aitwin-widget__composer-send--stop{opacity:1}.aitwin-widget__composer-send svg{display:block;height:calc(14px * var(--aitwin-size));width:calc(14px * var(--aitwin-size))}.aitwin-widget__controls-error{color:#fecaca;font-size:calc(11px * var(--aitwin-size));margin:0}.aitwin-widget--float{bottom:var(--aitwin-float-inset);filter:drop-shadow(0 12px 32px rgba(0,0,0,.45));height:fit-content;margin:0;max-width:calc(100vw - (2 * var(--aitwin-float-inset)));position:fixed;right:var(--aitwin-float-inset);width:fit-content;z-index:2147483000}@media(max-width:640px){.aitwin-widget{--aitwin-composer-width: calc(100vw - (2 * var(--aitwin-float-inset)));--aitwin-composer-height: calc(44px * var(--aitwin-size))}.aitwin-widget__controls--text{width:var(--aitwin-composer-width)}.aitwin-widget__composer-input{font-size:calc(15px * var(--aitwin-size))}}",Ci="data-aitwin-widget-style";function Ws(){if(typeof document>"u")return;const e=Yc.trim();if(!e){console.warn("[AiTwinWidget] styles.css?inline resolved empty — chrome will be unstyled");return}const t=document.querySelector(`style[${Ci}]`);if(t){if((t.textContent??"").trim().length>0)return;t.textContent=e;return}const r=document.createElement("style");r.setAttribute(Ci,"1"),r.textContent=e,(document.head??document.documentElement).appendChild(r)}typeof document<"u"&&Ws();const Qc=u.forwardRef(function(t,r){Ws();const n=u.useRef(null);u.useImperativeHandle(r,()=>({speakText:async(s,o)=>{const a=n.current?.getTwin();if(!a)throw new Error("AiTwinWidget: twin is not mounted");return a.speakText(s,o)},speakWithReply:async(s,o)=>{const a=n.current?.getTwin();if(!a)throw new Error("AiTwinWidget: twin is not mounted");return a.speakWithReply(s,o)},connect:async s=>{const o=n.current?.getTwin();if(!o)throw new Error("AiTwinWidget: twin is not mounted");return o.connect(s)},disconnect:async()=>{const s=n.current?.getTwin();if(s)return s.disconnect()},stop:()=>{n.current?.getTwin()?.stop()},isReady:()=>!!n.current?.getTwin()?.isReady(),isConnected:()=>!!n.current?.getTwin()?.isConnected(),getTwin:()=>n.current?.getTwin()??null}),[]);const i=!!t.float;return R.jsx("div",{className:i?"aitwin-widget aitwin-widget--float":"aitwin-widget",children:R.jsx(qc,{ref:n,options:t})})}),Xc=new Set([".png",".jpg",".jpeg",".webp"]);function js(e=".png"){const t=e.toLowerCase();return Xc.has(t)?`source${t}`:"source.png"}function Jc(e,t=Pr,r=".png"){const n=e.trim();if(!n)throw new Error("faceId is required");return`${t.replace(/\/$/,"")}/${n}/${js(r)}`}function Hs(e,t){if(e&&typeof e=="object"&&"detail"in e){const r=e.detail;if(typeof r=="string"&&r.trim())return r}return t}async function Zc(e){const t=new FormData;t.append("image",e.image),e.name?.trim()&&t.append("name",e.name.trim()),e.fullBody&&t.append("fullBody","true");const r=(e.apiBase??ut).replace(/\/$/,""),n=await fetch(`${r}/createAiTwinFace`,{method:"POST",headers:{Authorization:`Bearer ${e.authToken}`},body:t}),i=await n.json().catch(()=>null);if(!n.ok)throw new Error(Hs(i,`createAiTwinFace failed (${n.status})`));return i}async function el(e,t){const r=(t.apiBase??ut).replace(/\/$/,""),n=new URL(`${r}/getAiTwinFaceStatus`);n.searchParams.set("avatarId",e.trim());const i=await fetch(n.toString(),{headers:{Authorization:`Bearer ${t.authToken}`}}),s=await i.json().catch(()=>null);if(!i.ok)throw new Error(Hs(s,`getAiTwinFaceStatus failed (${i.status})`));return s}async function tl(e=ut){const t=e.replace(/\/$/,"");try{const r=await fetch(`${t}/getAiTwinGestureCatalog`);if(r.ok)return await r.json()}catch{}return{success:!0,fullBody:!0,poses:[xr.idle,...sr.map(r=>xr[r])].filter(r=>!!r),encrypted:!0,pathTemplate:"custom-faces/{avatarId}/ges/{code}.bin",cropMetaPath:"custom-faces/{avatarId}/ges/m.json"}}async function rl(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 nl(e){const t=e.message.trim();if(!t)throw new Error("Message is required");const r=e.authToken.trim();if(!r)throw new Error("Auth token is required");const n=(e.apiBase?.trim()||ut).replace(/\/$/,""),i=await fetch(`${n}/avatarReply`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`,Accept:"text/event-stream"},body:JSON.stringify({message:t,history:e.history??[],brainId:e.brainId?.trim()||e.personaId?.trim()||"",tenant:"aiTwin"})});if(!i.ok)throw new Error(await rl(i));if(!i.body)throw new Error("avatarReply response body is empty");const s=i.body.getReader(),o=new TextDecoder;let a="",f="",h="",l="";for(;;){const{done:c,value:p}=await s.read();if(c)break;a+=o.decode(p,{stream:!0});const y=a.split(`
48
+ `);a=y.pop()||"";for(const E of y){if(E.startsWith("event: ")){l=E.slice(7).trim();continue}if(!E.startsWith("data: "))continue;const g=E.slice(6).trim();if(!g)continue;let M;try{M=JSON.parse(g)}catch{continue}if(l==="spokenText")f=M.text||"",e.onSpokenText?.(f);else if(l==="displayText")h=M.text||"";else if(l==="error")throw new Error(M.error||"avatarReply stream error")}}if(!f.trim()||!h.trim())throw new Error("avatarReply stream missing displayText or spokenText");return{displayText:h.trim(),spokenText:f.trim()}}exports.AI_TWIN_THUMBNAIL_FILENAME=Tn;exports.AiTwin=Vs;exports.AiTwinNotFoundError=kr;exports.AiTwinWidget=Qc;exports.CONSONANT_SKIP_GROUP=os;exports.DEFAULT_TTS_ENGINE_ID=Et;exports.DEFAULT_TTS_LANGUAGE=Ca;exports.EMOTION_TO_EYEBROW=Ps;exports.EXPRESSION_ATLAS_EMOTIONS=_o;exports.FULLBODY_GESTURE_POSES=sr;exports.MIC_SAMPLE_RATE=Mn;exports.OCULUS_VISEME_IDS=ns;exports.PLAYBACK_SAMPLE_RATE=Pn;exports.SPEAKING_RATE_MAX=Vr;exports.SPEAKING_RATE_MIN=Ur;exports.TTS_ENGINE_CARTESIA=dt;exports.TTS_ENGINE_GOOGLE=vn;exports.TTS_ENGINE_INWORLD=Cr;exports.TTS_ENGINE_VISEMETTS=ft;exports.TTS_LANGUAGE_CATALOG=xt;exports.TTS_LANGUAGE_CODES=es;exports.VISEME_IDS=oo;exports.VISEME_SKIP_GAP_MS=dn;exports.VISEME_TEST_CARTESIA_VOICE_ID=Rn;exports.VISEME_TEST_SPEAKING_RATE=or;exports.VISEME_TEST_VISEMETTS_VOICE_ID=Fr;exports.VISEME_TEST_VOICE_ID=An;exports.VISEME_VTIME_GRID_MS=kn;exports.VOWEL_SKIP_GROUP=as;exports.aiTwinSourceFilename=js;exports.buildPlaybackTransitions=hs;exports.buildPlaybackVisemeSeries=Or;exports.buildRawVisemeTransitions=ms;exports.buildVoiceWebSocketUrl=Ts;exports.compactSkippableVisemes=xn;exports.createAiTwinFace=Zc;exports.createAvatarTtsLipsyncController=fn;exports.createRealtimeVoiceLipsyncController=ks;exports.emotionToEyebrow=It;exports.faceAssetUrls=un;exports.fetchAiTwin=Ni;exports.fetchAvatarReply=nl;exports.fetchDevAuthToken=Tr;exports.gesturesBaseForFace=Xi;exports.getAiTwinFaceStatus=el;exports.getAiTwinGestureCatalog=tl;exports.getAiTwinSourceUrl=Jc;exports.getAiTwinThumbnailUrl=Ui;exports.getFullBodyCropMetaUrl=Ji;exports.getFullBodyGestureBinUrl=Zi;exports.isFullBodyGesturePose=Ea;exports.isTtsLanguageCode=ts;exports.isTtsLanguageSupported=Ba;exports.listSkippedVisemeEntries=Nr;exports.listSkippedVisemes=za;exports.normalizeFullBodyGesturePose=Nt;exports.normalizeOculusViseme=Dr;exports.normalizeStreamEmotion=ct;exports.normalizeTtsLanguage=Br;exports.parsePackedVoiceId=Bi;exports.parseTwinBrainUrl=aa;exports.resolveDirectFaceId=Vi;exports.resolveTwinBrainId=bn;exports.resolveTwinBrainUrl=Sn;exports.resolveVisemeAtTime=ar;exports.resolveVisemeFromPlaybackSeries=us;exports.resolveWordAtTime=Ss;exports.setActiveTwinAssets=Wi;exports.snapVisemeQueueToGrid=En;exports.snapVisemeVtimeToGrid=cs;exports.splitVoiceIdSpec=lt;exports.ttsLanguagesForEngine=Fa;