@avatarfactory/react 0.1.40 → 0.1.41
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/README.md +1 -1
- package/dist/{AvatarProvider-Cll_r1hx.d.ts → AvatarProvider-CItqTL0v.d.ts} +3 -0
- package/dist/{AvatarProvider-BXaeG3PZ.d.mts → AvatarProvider-DqD003D2.d.mts} +3 -0
- package/dist/chunk-3SRQGZJ5.js +4 -0
- package/dist/chunk-6Q2I7WKW.mjs +16 -0
- package/dist/{chunk-YOMHPKHO.js → chunk-FDZA3OHI.js} +3 -3
- package/dist/chunk-WOQBPJGB.mjs +4 -0
- package/dist/embed/embed.js +5 -5
- package/dist/embed/meeting.js +14 -14
- package/dist/embed/runtime.js +14 -14
- package/dist/framer/index.framer.mjs +42 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/page.js +1 -1
- package/dist/page.mjs +1 -1
- package/dist/unstable.d.mts +2 -2
- package/dist/unstable.d.ts +2 -2
- package/dist/unstable.js +1 -1
- package/dist/unstable.mjs +1 -1
- package/package.json +6 -4
- package/dist/chunk-E7HVSIHB.mjs +0 -4
- package/dist/chunk-HRSHBEAW.js +0 -4
- package/dist/chunk-OANDIUVQ.mjs +0 -16
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var dt=(n=>(n.Idle="idle",n.Connecting="connecting",n.Active="active",n))(dt||{}),ht=(r=>(r.None="none",r.Loading="loading",r.Painted="painted",r.Failed="failed",r))(ht||{}),pt=(s=>(s.Idle="idle",s.Greeting="greeting",s.Listening="listening",s.Thinking="thinking",s.Speaking="speaking",s))(pt||{});var re=class re{static setLogLevel(e){this.level=e;}static sanitize(e){return e.map(t=>{if(t&&typeof t=="object"){let n={...t};for(let r of re.SENSITIVE_FIELDS)r in n&&(n[r]="[REDACTED]");return n}return t})}static format(e,t,n){return `[${new Date().toISOString()}] [${e}] [${t}] ${n}`}static muted(e){return this.level>e&&!this.onLog}static debug(e,t,...n){if(this.muted(0))return;let r=this.sanitize(n);this.onLog?.(0,e,t,...r),this.level<=0&&console.debug(this.format("DEBUG",e,t),...r);}static info(e,t,...n){if(this.muted(1))return;let r=this.sanitize(n);this.onLog?.(1,e,t,...r),this.level<=1&&console.info(this.format("INFO",e,t),...r);}static warn(e,t,...n){if(this.muted(2))return;let r=this.sanitize(n);this.onLog?.(2,e,t,...r),this.level<=2&&console.warn(this.format("WARN",e,t),...r);}static error(e,t,...n){if(this.muted(3))return;let r=this.sanitize(n);this.onLog?.(3,e,t,...r),this.level<=3&&console.error(this.format("ERROR",e,t),...r);}static event(e,t,...n){this.info(`Event:${e}`,t,...n);}};re.level=4,re.SENSITIVE_FIELDS=["apiKey","sessionToken","getSessionToken","byok"];var u=re;var _n=5e3,jr=new Set(["read","retag","scroll","navigate","click","fill","submit"]),qr=i=>new Promise((e,t)=>{let n=setTimeout(()=>t(new Error("page surface did not answer")),_n);i.then(r=>{clearTimeout(n),e(r);},r=>{clearTimeout(n),t(r);});});function zr(i){let e=(t,n)=>qr(i({method:t,args:n}));return {read:async t=>{try{return await e("read",[t])}catch(n){return u.warn("Page","remote read reached no page",{error:String(n)}),null}},retag:t=>e("retag",[t]),scroll:(t,n)=>e("scroll",[t,n]),navigate:(t,n)=>e("navigate",[t,n]),click:(t,n)=>e("click",[t,n]),fill:(t,n)=>e("fill",[t,n]),submit:(t,n)=>e("submit",[t,n])}}function Yr(i,e){let{method:t,args:n}=e??{};if(typeof t!="string"||!jr.has(t))throw new Error(`not a page surface method: ${String(t)}`);if(!Array.isArray(n))throw new Error("page surface call has no args");return i[t].apply(i,n)}var L={position:"bottom-right",offset:{x:20,y:20},bubbleSize:64,panel:{w:384,h:560},panelBackground:"#F4F2EE",avatarScale:.6,draggable:false,launcher:"avatar",mobile:"sheet",zIndex:2147483e3,teaserDelayMs:8e3,mobileBreakpointPx:640,stripQuery:true,maxSessionMinutes:15},Jr=i=>({...i,position:i?.position??L.position,offset:i?.offset??L.offset,bubbleSize:i?.bubbleSize??L.bubbleSize,panel:i?.panel??L.panel,panelBackground:i?.panelBackground??L.panelBackground,avatarScale:i?.avatarScale??L.avatarScale,draggable:i?.draggable??L.draggable,launcher:i?.launcher??L.launcher,mobile:i?.mobile??L.mobile,zIndex:i?.zIndex??L.zIndex});var _e="33d964ca31c2dcf0c6ef3bfe4204c140829a7400bc73242e39b6b121fa174ce0";var Te="api.avatarfactory.in",mt=()=>`wss://${Te}`,ft=()=>`https://${Te}`,Tn=()=>`https://${Te}/v1/vad/weights-${_e}.bin`,Qr=(i,e)=>`https://${Te}/v1/assets/${i}.${e}`;var gt=new Map;function vt(i,e,t){let n=gt.get(i.sha256);if(n)return n;let r=Zr(i,e,t).catch(s=>{throw gt.delete(i.sha256),s});return gt.set(i.sha256,r),r}async function Zr(i,e,t){let n=await es(i.sha256,t);if(n&&await Mn(n,i))return n;let r=await fetch(e,{priority:"low"});if(!r.ok)throw new Error(`asset ${i.sha256} HTTP ${r.status}`);let s=new Uint8Array(await r.arrayBuffer());if(!await Mn(s,i))throw new Error(`asset ${i.sha256} failed integrity check (${s.byteLength}B)`);return t?.write(i.sha256,s)?.catch(o=>{u.warn("Assets","failed to cache asset",{sha256:i.sha256,cause:o});}),s}async function es(i,e){try{return await e?.read(i)??null}catch(t){return u.warn("Assets","asset cache read failed",{sha256:i,cause:t}),null}}async function Mn(i,e){if(i.byteLength!==e.byteLength)return false;let t=globalThis.crypto?.subtle;if(!t)return u.warn("Assets","no SubtleCrypto \u2014 asset checked by length only"),true;let n=await t.digest("SHA-256",i);return ts(new Uint8Array(n))===e.sha256}function ts(i){let e="";for(let t=0;t<i.length;t++)e+=i[t].toString(16).padStart(2,"0");return e}function wn(i,e){return vt({sha256:_e,byteLength:590012},i,e&&{read:t=>e.getCachedVadWeights?.(t),write:(t,n)=>e.setCachedVadWeights?.(t,n)})}var St={A:2,E:4,I:6,O:8,U:7,Y:6,P:21,B:21,M:21,F:18,V:18,T:19,D:19,N:19,S:15,Z:15,L:14,R:13,K:20,C:20,G:20,Q:20,H:12,W:7,J:16,X:15," ":0,".":0,",":0,"!":0,"?":0,":":0,";":0,"-":0,"(":0,")":0,'"':0,"'":0,DEFAULT:0},Me={TH:19,SH:16,CH:16,PH:18,GH:0,CK:20,NG:20,AI:4,AU:8,EA:6,EE:6,IE:6,OA:8,OO:7,OU:8,OW:8,UE:7,ER:5,IR:5,UR:5,AR:2,OR:8};var Et=400,Rn=4e3,At={loop:true,volume:.4,fadeOutMs:350},kn=15e3,bt=500,In=4010,Pn=4011,Cn=6e3,On=1500,Nn=[1e3,2e3,4e3,8e3,15e3],Ln={echoCancellation:false,noiseSuppression:false,autoGainControl:false,channelCount:1},yt=350,_t=-9999,is=9999,rs=Number.NEGATIVE_INFINITY,ss=.28,we=1,Tt=.15,Mt=2.5,Re=1,wt=.2,Rt=2,ke=1,kt=.25,It=1.6,Ie=60,Pt=.1,Ct=200,Pe=40,Ot=0,Nt=100,Lt=12e3,os=1e3,Ce=0,Oe=250,xn=3,Dn=10,xt=2500;var as=1e3,ls=.25,cs=.25,us=.01,Fn=200,Hn=250,Bn=12e4,Un=12e3;var Ne=i=>{if(!Array.isArray(i))return null;let e=[];for(let t of i){let{visemeId:n,start:r,end:s}=t??{};!Number.isInteger(n)||!Number.isFinite(r)||!Number.isFinite(s)||e.push({char:"",visemeId:n,start:r,end:s});}return e},Wn=(i,e)=>{let t=[],n=i[0];for(let s=1;s<i.length;s++){let o=i[s];o.start*1e3-n.start*1e3<=e&&o.char!==" "&&n.char!==" "?n={...n,end:o.end,char:n.char+o.char}:(Me?.[n.char]&&(n={...n,visemeId:Me?.[n.char]??0}),t.push(n),n=o);}t.push(n);let r=t.length-1;for(;r>=0&&t[r].visemeId===0;)r--;if(r<t.length-1){let s=t[t.length-1];t[r]={...t[r],end:s.start},t.splice(r+1,t.length-(r+1),{...s,start:t[r].end});}return t},ds=(i,e=40)=>{if(!i||!Array.isArray(i.character_start_times_seconds))return [];let t=i.characters.map((n,r)=>{let s=i.character_start_times_seconds[r]??0,o=i.character_end_times_seconds[r]??s+.05,a=(n||" ").toUpperCase();return {char:n,start:s,end:o,visemeId:St[a]??0}});return Wn(t,e)},Le=(i,{defaultDurationMs:e=50}={})=>{if(!i)return null;let t=Array.isArray(i.chars)?i.chars:[],n=Array.isArray(i.charStartTimesMs)?i.charStartTimesMs:[],r=Array.isArray(i.charDurationsMs)?i.charDurationsMs:[],s=t.length,o=new Array(s).fill(0),a=new Array(s).fill(e);for(let c=0;c<s;c++){let p=n[c],m=p==null?NaN:Number(p);o[c]=Number.isFinite(m)?m:0;let h=r[c],g=h==null?NaN:Number(h);a[c]=Number.isFinite(g)&&g>=0?g:NaN;}for(let c=0;c<s;c++)Number.isFinite(a[c])||(a[c]=c+1<s&&Number.isFinite(o[c+1])&&o[c+1]>o[c]?o[c+1]-o[c]:e);let l=new Array(s),d=new Array(s);for(let c=0;c<s;c++){let p=o[c]/1e3,m=(o[c]+Math.max(0,a[c]))/1e3;l[c]=Number.isFinite(p)?p:0,d[c]=Number.isFinite(m)?Math.max(l[c],m):l[c]+.001;}return {characters:t,character_start_times_seconds:l,character_end_times_seconds:d}};var Dt=["idle","listening","thinking","talking"];var Vn=i=>typeof i=="string"&&Dt.includes(i),j=i=>typeof i=="string"&&i.trim()&&i.length<=64?i:null,B=i=>{let e=Number(i);return Number.isFinite(e)&&e>0?Math.min(Math.round(e),6e5):0};function hs(i){if(!i||typeof i!="object")return null;let e=i,t=j(e.gate),n=j(e.act),r=n&&Array.isArray(e.acts)?e.acts.filter(s=>Number.isInteger(s)&&s>0&&s<=99):[];return !t&&!n?null:{gate:t,act:n,acts:r,...Vn(e.fallback)&&{fallback:e.fallback}}}var ps=["oneShot","loop","pingPong"],ms=/^[^\0\r\n]{1,120}$/;function fs(i){if(!i||typeof i!="object")return null;let e=i,t=j(e.gate),n=j(e.act),r=B(e.windowMaxMs);if(!t||!n||!r)return null;let s=Math.min(B(e.windowMinMs),r),o=[];for(let a of Array.isArray(e.acts)?e.acts:[]){let l=a??{},d=l.id,c=B(l.ms);if(!Number.isInteger(d)||d<1||d>99||!c||o.some(h=>h.id===d))continue;let p=ps.includes(l.loop)?l.loop:"loop",m=typeof l.timeline=="string"&&ms.test(l.timeline)?l.timeline:void 0;o.push({id:d,ms:c,loop:p,...m&&{timeline:m}});}return o.length?{gate:t,act:n,acts:o,windowMinMs:s,windowMaxMs:r}:null}var gs=12,vs=4;function Ss(i){let e=(Array.isArray(i)?i:[]).map(j).filter(t=>!!t);return [...new Set(e)].slice(0,vs)}function Es(i){if(!i||typeof i!="object")return null;let e=i,t=[];for(let n of Array.isArray(e.gestures)?e.gestures:[]){let r=n??{},s=j(r.trigger),o=B(r.ms);if(!(!s||!o||t.some(a=>a.trigger===s))&&(t.push({trigger:s,ms:o}),t.length===gs))break}return t.length?{gestures:t}:null}function Gn(i,e,t,n,r=Math.random){if(!i?.length||t<n)return null;let s=i.filter(a=>a.trigger!==e),o=s.length?s:i;return o[Math.floor(r()*o.length)]}function xe(i){if(!i||typeof i!="object")return null;let e=i,t=e.branches??{},n={};for(let a of Dt){let l=hs(t[a]);l&&(n[a]=l);}let r=fs(e.idleActs);if(r&&(n.idle={gate:r.gate,act:r.act,acts:r.acts.map(a=>a.id)}),!Object.keys(n).length)return null;let s=Es(e.playful),o=Ss(e.idleTriggers);return {version:Number(e.version)||1,branches:n,quietToIdleMs:B(e.quietToIdleMs),idleCycleMs:B(e.idleCycleMs),playfulAfterMs:B(e.playfulAfterMs),playfulRoles:Array.isArray(e.playfulRoles)?e.playfulRoles.filter(Vn):[],thinkingMaxMs:B(e.thinkingMaxMs),...r&&{idleActs:r},...s&&{playful:s},...o.length&&{idleTriggers:o}}}var Ft=i=>i.trim().replace(/\s+/g," ").slice(0,Et).trimEnd(),As=i=>{let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},Ht=(i,e,t)=>`${i}:${e}:${As(t)}`;var Bt=i=>i.environment!=="meeting"?i:{...i,autoStart:i.autoStart??true,controls:i.controls??{enabled:false},statusBanner:{enabled:false,...i.statusBanner},thinkingIndicator:{enabled:false,...i.thinkingIndicator},connectTone:i.connectTone??{enabled:false},turnTaking:{echoGate:false,clientBargeIn:false,...i.turnTaking}};var $n=()=>{if(typeof document>"u")return true;let i=document.permissionsPolicy??document.featurePolicy;return typeof i?.allowsFeature!="function"||i.allowsFeature("microphone")!==false};var F=1e3,q=(i,e,t,n)=>typeof i=="number"&&Number.isFinite(i)?Math.max(e,Math.min(t,i)):n,se=class{constructor(){this.speed=we;this.jawSpeed=Re;this.openness=ke;this.holdSec=Ie/F;this.rest=Pe;this.offsetSec=Ce/F;this.maxStepFrames=xn;}apply(e){e&&(this.speed=q(e.mouthSpeed,Tt,Mt,this.speed),this.jawSpeed=q(e.jawSpeed,wt,Rt,this.jawSpeed),this.openness=q(e.mouthOpenness,kt,It,this.openness),this.holdSec=q(e.mouthHold,Pt,Ct,this.holdSec*F)/F,this.rest=q(e.mouthRest,Ot,Nt,this.rest),this.offsetSec=q(e.offsetMs,-Oe,Oe,this.offsetSec*F)/F);}reset(e){this.speed=we,this.jawSpeed=Re,this.openness=ke,this.holdSec=Ie/F,this.rest=Pe,this.offsetSec=Ce/F,this.apply(e);}snapshot(){return {offsetMs:Math.round(this.offsetSec*F),mouthSpeed:this.speed,jawSpeed:this.jawSpeed,mouthOpenness:this.openness,mouthHold:Math.round(this.holdSec*F),mouthRest:this.rest}}};var De="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Ut(i){let e="",t=i.length;for(let n=0;n<t;n+=3){let r=i[n],s=n+1<t?i[n+1]:0,o=n+2<t?i[n+2]:0;e+=De[r>>2],e+=De[(r&3)<<4|s>>4],e+=n+1<t?De[(s&15)<<2|o>>6]:"=",e+=n+2<t?De[o&63]:"=";}return e}var oe=i=>i.characters.join("").replace(/\s+/g," ").trim(),ae=i=>{let{characters:e,character_start_times_seconds:t,character_end_times_seconds:n}=i,r=[],s="",o=0,a=0,l=()=>{s&&(r.push({text:s,start:o,end:a}),s="");};for(let d=0;d<e.length;d++){let c=e[d];if(/\s/.test(c)){l();continue}s||(o=t[d]??0),s+=c,a=n[d]??o;}return l(),r},Wt=i=>i.split(/\s+/).filter(Boolean).map(e=>({text:e,start:0,end:0})),Xn=(i,e)=>{let t=0;for(;t<i.words.length&&i.words[t].start<=e;)t++;return t},bs=(i,e)=>i.words.slice(0,Xn(i,e)).map(t=>t.text).join(" ").trim();var Vt=["hmm","hmmm","mhm","mhmm","mm","mmm","uh","um","umm","uh huh","yeah","yep","ok","okay","right","haan","han","achha","accha","theek hai","theek"];var Fe={mode:"healthy",commitPostPauseMs:680,settleMs:60,circuitBreakerEnabled:true},Gt={mode:"degraded",commitPostPauseMs:100,settleMs:100,circuitBreakerEnabled:false},Kn=1200,jn=600,qn=5,zn=3,Yn=6e4,Jn=400,Qn=6e3,Zn=.5,ei=80,ti=3,ni=100,ii=2,ri=.6,si=.8,oi=4,li=400,ci=40;function Kt(i){let e="idle",t=null,n=null,r=0,s=0,o=0,a=0,l="",d=null,c=0,p=0,m=0,h=0,g=0,S=0;function E(){return i.getPolicy?.()??Fe}function v(){return E().circuitBreakerEnabled?{pause:g,threshold:S}:{pause:0,threshold:0}}function b(){return Math.min(.95,(e==="soft_pause"?.3:.5)+v().threshold)}function R(){return l.trim().length>0&&!ui(l)}function P(I){return d===null||d.motion>=I}function C(){return d?{speechMotion:d.motion,speechMedianFlux:d.medianFlux,speechModulation:d.modulation}:{}}function O(){t=null,n=null,r=0,s=0,o=0,a=0,l="",d=null;}function K(){p=0,m=0;}function ye(){e="idle",O(),K(),h=0,g=0,S=0;}function D(I){i.onTelemetry?.({voiceOnsetToPauseMs:o-r,outcome:"commit",commitClause:I,totalVoicedMs:s,postPauseVoicedMs:a,transcript:l||void 0,wordlessResumeStreak:h,mode:E().mode,...C()}),i.commitInterrupt(),ye();}function at(I){l.trim().length===0&&a<60?h++:h=0,i.onTelemetry?.({voiceOnsetToPauseMs:o-r,outcome:"resume",totalVoicedMs:s,postPauseVoicedMs:a,transcript:l||void 0,wordlessResumeStreak:h,mode:E().mode,...C()}),i.resumePlayback(),E().circuitBreakerEnabled&&h>=3&&(g=150,S=.1),s>=100?(p=s,m=I+500):K(),e="speaking",O();}function te(I,M,G){if(G!==void 0&&(d=G),c=M,!i.isAvatarSpeaking()){e!=="idle"&&ne();return}if(e==="idle"&&(e="speaking",O()),I>=b()){if(t===null&&(t=M),n!==null){let w=M-n;w>0&&w<=150&&(s+=w,e==="soft_pause"&&M-o>E().settleMs&&(a+=Math.min(w,30)));}n=M;}else n!==null&&M-n>150&&(t=null);if(e==="speaking"){t!==null&&M-t>=70+v().pause&&(e="soft_pause",r=t,o=M,i.pausePlayback());return}if(a>=E().commitPostPauseMs&&!R()&&P(.02)){D("post_pause");return}let y=n!==null&&M-n<=150;if(y&&M-r>=1e3&&!R()&&P(.02)){D("sustained");return}if(!y&&n!==null&&M-n>=900){at(M);return}}function lt(I){if(e==="idle"||!I||i.getActiveScriptTail&&hi(I,i.getActiveScriptTail()))return;l=l?`${l} ${I}`:I;let M=m>0&&c<=m,G=s<100;(G&&M?p:s)<100||ui(I)&&(e==="speaking"&&(e="soft_pause",r=t??0,o=0,i.pausePlayback()),D(G?"words_late":"words"));}function ct(){e!=="idle"&&(e==="speaking"&&(e="soft_pause",o=0,i.pausePlayback()),D("manual"));}function ne(){e==="soft_pause"&&i.resumePlayback(),ye();}return {onVadProb:te,onPartialTranscript:lt,manualStop:ct,abort:ne,reset:ne}}function He(i){return i.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function di(i){return i.replace(/(.)\1+/g,"$1")}var Hs=new Set(Vt.filter(i=>!i.includes(" ")).map(di)),Bs=Vt.filter(i=>i.includes(" "));function ui(i){let e=He(i);if(!e)return false;for(let n of Bs)e=e.replace(new RegExp(`(^| )${n}( |$)`,"g")," ");return e.split(" ").filter(Boolean).some(n=>!Hs.has(di(n)))}function hi(i,e,t=ri){let n=He(i).split(" ").filter(Boolean);if(n.length===0)return false;let r=new Set(He(e).split(" ").filter(Boolean));if(r.size===0)return false;let s=0;for(let o of n)r.has(o)&&s++;return s/n.length>=t}function pi(i,e){return He(i).split(" ").filter(Boolean).length<oi?false:hi(i,e,si)}var mi=/^[a-z0-9][a-z0-9_.]{0,63}$/;var Be=class{constructor(){this.sentByName=new Map;this.windowStartedAt=0;this.windowCount=0;}validate(e){if(!mi.test(e.name))return {ok:false,reason:"invalid_name",message:`notify() name must be a slug matching ${mi} \u2014 got "${e.name}"`};if(e.say!==void 0&&e.say.length>1e3)return {ok:false,reason:"say_too_long",message:"notify() say is too long (max 1000 chars)"};if(e.data===void 0)return {ok:true};let t;if(typeof e.data=="string")t=e.data;else try{t=JSON.stringify(e.data);}catch{return {ok:false,reason:"data_invalid",message:"notify() data is not serializable"}}return t.length>512?{ok:false,reason:"data_too_long",message:"notify() data is too long (max 512 chars serialized)"}:{ok:true,data:t}}admit(e,t,n){let r=this.sentByName.get(e);return r&&n-r.sentAt<t?{ok:false,reason:"cooldown"}:(n-this.windowStartedAt>=1e4&&(this.windowStartedAt=n,this.windowCount=0),this.windowCount>=5?{ok:false,reason:"rate_limit"}:(this.windowCount+=1,this.sweepExpired(n),this.sentByName.set(e,{sentAt:n,cooldownMs:t}),{ok:true}))}sweepExpired(e){if(!(this.sentByName.size<64))for(let[t,n]of this.sentByName)e-n.sentAt>=n.cooldownMs&&this.sentByName.delete(t);}};var fi=/^[a-z][a-z0-9_]{0,63}$/,gi=/^[a-zA-Z][a-zA-Z0-9_]{0,39}$/,Us=new Set(["confirm_action","cancel_action"]),vi=16,Si=8,Ei=300,Ai=120,bi=20,Ws=1e3,Vs=250,$={unavailable:"that action is not available right now",invalidArgs:"the details did not match what that action needs",failed:"the action failed",timedOut:"it took too long"},Gs=new Set(["string","email","phone","date","datetime","number","boolean","enum"]),yi="[]",Ue=class{constructor(e){this.transport=e;this.actions=new Map;this.lastSent=yi;this.syncTimer=null;}get size(){return this.actions.size}get(e){return this.actions.get(e)}register(e){let t=Xs(e);if(t)return {ok:false,message:`registerAction(): ${t}`};if(!this.actions.has(e.name)&&this.actions.size>=vi)return {ok:false,message:`registerAction(): at most ${vi} actions at once \u2014 "${e.name}" was not added`};let n={declaration:$s(e),handler:e.handler,...e.check&&{check:e.check}};return this.actions.set(e.name,n),this.scheduleSync(),{ok:true,unregister:()=>{this.actions.get(e.name)===n&&(this.actions.delete(e.name),this.scheduleSync());}}}declarations(){return [...this.actions.values()].map(e=>e.declaration).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}syncNow(){if(this.clearSyncTimer(),!this.transport.canDeclare())return;let e=this.declarations(),t=JSON.stringify(e);t!==this.lastSent&&this.transport.send(e)&&(this.lastSent=t);}resetSession(){this.clearSyncTimer(),this.lastSent=yi;}scheduleSync(){this.clearSyncTimer(),this.syncTimer=setTimeout(()=>{this.syncTimer=null,this.syncNow();},Vs);}clearSyncTimer(){this.syncTimer!==null&&(clearTimeout(this.syncTimer),this.syncTimer=null);}},$s=i=>{let e={};for(let[n,r]of Object.entries(i.params??{}))e[n]={type:r.type,...r.description!==void 0&&{description:r.description},...r.required!==void 0&&{required:r.required},...r.type==="enum"&&{values:[...r.values??[]]},...r.check===true&&{check:true}};let t=i.ui&&{...i.ui.inputs!==void 0&&{inputs:i.ui.inputs==="*"?"*":[...i.ui.inputs]},...i.ui.review!==void 0&&{review:i.ui.review}};return {name:i.name,description:i.description.trim(),params:e,...i.kind==="lookup"&&{kind:"lookup"},...i.undoable===true&&{undoable:true},...t&&{ui:t}}},U=i=>!!i&&typeof i=="object"&&!Array.isArray(i),Xs=i=>{if(!U(i))return "the action must be an object";let{name:e,description:t,params:n,handler:r}=i;if(typeof e!="string"||!fi.test(e))return `name must match ${fi} \u2014 got "${String(e)}"`;if(Us.has(e))return `"${e}" is reserved`;if(typeof t!="string"||!t.trim())return `"${e}" needs a description`;if(t.length>Ei)return `"${e}" description is too long (max ${Ei} chars)`;if(typeof r!="function")return `"${e}" needs a handler`;let s=Ks(i);if(s)return `"${e}" ${s}`;if(n===void 0)return null;if(!U(n))return `"${e}" params must be an object`;let o=Object.entries(n);if(o.length>Si)return `"${e}" has too many params (max ${Si})`;for(let[a,l]of o){let d=js(a,l);if(d)return `"${e}" param "${a}": ${d}`}return null},Ks=i=>{let{kind:e,ui:t,check:n,undoable:r}=i,s=U(i.params)?i.params:{};if(e!==void 0&&e!=="action"&&e!=="lookup")return `kind must be "action" or "lookup" \u2014 got "${String(e)}"`;if(r!==void 0&&typeof r!="boolean")return "undoable must be a boolean";if(e==="lookup"&&r)return "is a lookup, which changes nothing to undo";let o=Object.values(s).some(d=>U(d)&&d.check===true);if(e==="lookup"&&(o||n!==void 0))return "is a lookup, which cannot check values";if(o&&typeof n!="function")return "marks a param check: true but has no check function";if(n!==void 0&&typeof n!="function")return "check must be a function";if(t===void 0)return null;if(!U(t))return "ui must be an object";if(t.review!==void 0&&typeof t.review!="boolean")return "ui.review must be a boolean";if(e==="lookup"&&t.review)return "is a lookup, which has no review";let{inputs:a}=t;if(a===void 0||a==="*")return null;if(!Array.isArray(a))return 'ui.inputs must be "*" or a list of params';let l=a.find(d=>!(String(d)in s));return l===void 0?null:`ui.inputs names "${String(l)}", which is not a param`},js=(i,e)=>{if(!gi.test(i))return `name must match ${gi}`;if(!U(e))return "must be an object";if(!Gs.has(e.type))return `unknown type "${String(e.type)}"`;if(e.description!==void 0&&(typeof e.description!="string"||e.description.length>Ai))return `description must be a string of at most ${Ai} chars`;if(e.required!==void 0&&typeof e.required!="boolean")return "required must be a boolean";if(e.check!==void 0&&typeof e.check!="boolean")return "check must be a boolean";if(e.type!=="enum")return null;let t=e.values;return Array.isArray(t)&&t.length>0&&t.length<=bi&&t.every(r=>typeof r=="string"&&r.trim())?null:`an enum needs 1\u2013${bi} non-empty string values`},qs=/^\d{4}-\d{2}-\d{2}$/,zs=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/,jt=(i,e)=>{switch(i.type){case "string":case "email":case "phone":return typeof e=="string";case "date":return typeof e=="string"&&qs.test(e);case "datetime":return typeof e=="string"&&zs.test(e);case "number":return typeof e=="number"&&Number.isFinite(e);case "boolean":return typeof e=="boolean";case "enum":return typeof e=="string"&&!!i.values?.includes(e)}},Ti=(i,e)=>{if(e!==void 0&&!U(e))return null;let t=e??{},n={};for(let[r,s]of Object.entries(i.params)){let o=t[r];if(o==null||o===""){if(s.required!==false)return null;continue}if(!jt(s,o))return null;n[r]=o;}return n},_i=i=>String(i).slice(0,Ws),Mi=i=>U(i)?i.ok===true?i.result===void 0||i.result===null?{ok:true}:{ok:true,result:_i(i.result)}:i.ok===false?{ok:false,error:(i.error===void 0||i.error===null?"":_i(i.error).trim())||$.failed}:null:null;var wi=2500,Ys=200,Js=5,le=i=>!!i&&typeof i=="object"&&!Array.isArray(i),Ri=i=>{if(!le(i))return null;let{actionId:e,revision:t,name:n,stage:r,args:s,missing:o,awaiting:a,outcome:l}=i;return typeof e!="string"||!e||typeof t!="number"||!Number.isFinite(t)||typeof n!="string"||typeof r!="string"?null:{actionId:e,revision:t,name:n,stage:r,args:le(s)?{...s}:{},missing:Array.isArray(o)?o.filter(d=>typeof d=="string"):[],awaiting:le(a)&&typeof a.kind=="string"?{...a}:null,...le(l)&&typeof l.ok=="boolean"&&{outcome:{ok:l.ok,message:typeof l.message=="string"?l.message:""}}}},Qs=new Set(["done","cancelled","expired"]),We=class{constructor(){this.current=null;}get flow(){return this.current}apply(e){let t=this.current;return t&&t.actionId===e.actionId&&e.revision<=t.revision?false:(this.current=e,true)}get isLive(){return !!this.current&&!Qs.has(this.current.stage)}clear(){this.current=null;}},ki=(i,e)=>{let t={};for(let[n,r]of Object.entries(e)){let s=i.params[n];if(!s)return {ok:false,message:`"${i.name}" has no param "${n}"`};if(!jt(s,r))return {ok:false,message:`"${i.name}" param "${n}" must be a ${s.type}`};t[n]=r;}return Object.keys(t).length?{ok:true,args:t}:{ok:false,message:"input needs at least one value"}},Ii=async(i,e,t,n)=>{if(!i)return {ok:true,unverified:true};let r,s=Promise.resolve().then(()=>i(e,t,n)).then(Zs,()=>null),o=new Promise(l=>{r=setTimeout(()=>l(null),wi);}),a=await Promise.race([s,o]);return clearTimeout(r),a??{ok:true,unverified:true}},Zs=i=>{if(!le(i)||typeof i.ok!="boolean")return null;if(i.ok)return i.value===void 0?{ok:true}:{ok:true,value:i.value};let e=typeof i.reason=="string"?i.reason.slice(0,Ys):void 0,t=Array.isArray(i.suggestions)?i.suggestions.slice(0,Js):void 0,n=typeof i.param=="string"&&i.param?i.param:void 0;return {ok:false,...e&&{reason:e},...t?.length&&{suggestions:t},...n&&{param:n}}};var Pi=i=>{let e=i.cause?.name;return typeof e=="string"&&e!==""&&e!=="Error"?e:null},eo="embed_unauthorized_domain",to=/unauthorized domain/i,qt=(i,e)=>i===eo||typeof e=="string"&&to.test(e),ce=class extends Error{constructor(e,t){let n=t??{},r=typeof n.error=="string"?n.error:void 0;super(`config route HTTP ${e}${r?`: ${r}`:""}`),this.name="ConfigRouteError",this.status=e,this.serverCode=typeof n.code=="string"?n.code:void 0,this.serverMessage=r;}},no=123,Ci=i=>`Initialization Failed: ${i.code} (${Pi(i)??i.message})`.slice(0,no);var io=50,ro=4e3,Ve=class{constructor(e,t=io){this.onChange=e;this.entries=[];this.activeUserEntryId=null;this.lastFinalText="";this.lastFinalAt=0;this.activeAvatarEntryId=null;this.activeAvatarJobId=null;this.entryCounter=0;this.consumedChunks=0;this.openChars=[];this.openStarts=[];this.openEnds=[];this.maxEntries=Math.max(1,t);}applyUserTranscript({text:e,isFinal:t,turnId:n}){let r=e?.trim()??"";if(!r)return;let s=this.findEntry(this.activeUserEntryId);if(s&&s.turnId!==n&&(this.upsert({...s,isFinal:true}),s=null),s&&s.text===r&&s.isFinal===t||!s&&r===this.lastFinalText&&Date.now()-this.lastFinalAt<ro)return;let o={id:s?.id??this.nextId("user"),speaker:"user",text:r,words:Wt(r),isFinal:t,turnId:n,createdAt:s?.createdAt??Date.now()};this.upsert(o),this.activeUserEntryId=t?null:o.id,t&&(this.lastFinalText=r,this.lastFinalAt=Date.now()),this.emit();}applyAvatarSpeech(e){let t=e.alignments??[],n=e.chunkOffset??0,r=n+t.length;if(this.activeAvatarJobId!==e.jobId&&(this.finalizeAvatar(),this.activeAvatarJobId=e.jobId,this.consumedChunks=0),r<=this.consumedChunks)return;this.activeAvatarEntryId||(this.activeAvatarEntryId=this.nextId("avatar"),this.openChars=[],this.openStarts=[],this.openEnds=[]);for(let l=Math.max(0,this.consumedChunks-n);l<t.length;l++){let d=e.displayAlignments?.[l]??t[l];d?.characters?.length&&(this.openChars.push(...d.characters),this.openStarts.push(...d.character_start_times_seconds),this.openEnds.push(...d.character_end_times_seconds));}if(this.consumedChunks=r,!this.openChars.length)return;let s={characters:this.openChars,character_start_times_seconds:this.openStarts,character_end_times_seconds:this.openEnds},o=oe(s);if(!o)return;let a=this.findEntry(this.activeAvatarEntryId);a?.text!==o&&(this.upsert({id:this.activeAvatarEntryId,speaker:"avatar",text:o,words:ae(s),isFinal:false,turnId:e.turnId,createdAt:a?.createdAt??Date.now()}),this.emit());}finalizeAvatar(){let e=this.findEntry(this.activeAvatarEntryId);this.activeAvatarEntryId=null,this.openChars=[],this.openStarts=[],this.openEnds=[],!(!e||e.isFinal)&&(this.upsert({...e,isFinal:true}),this.emit());}reset(){let e=this.entries.length>0;this.entries=[],this.activeUserEntryId=null,this.lastFinalText="",this.lastFinalAt=0,this.activeAvatarEntryId=null,this.activeAvatarJobId=null,this.consumedChunks=0,this.openChars=[],this.openStarts=[],this.openEnds=[],e&&this.emit();}getEntries(){return [...this.entries]}upsert(e){let t=this.entries.findIndex(n=>n.id===e.id);if(t>=0){this.entries[t]=e;return}this.entries.push(e),this.entries.length>this.maxEntries&&this.entries.splice(0,this.entries.length-this.maxEntries);}findEntry(e){return e?this.entries.find(t=>t.id===e)??null:null}nextId(e){return `${e}-${++this.entryCounter}`}emit(){this.onChange(this.getEntries());}};var Ge=class{constructor(e){this.deps=e;this.held=false;this.open=false;this.preRollToFlush=[];this.recentFrames=[];this.tailTimer=null;this.maxHoldTimer=null;this.silenceByteSize=new Map;}isHeld(){return this.held}isTurnOpen(){return this.open}press(){if(this.held)return false;this.held=true;let e=this.open;return this.clearTailTimer(),this.open=true,e||(this.preRollToFlush=this.recentFrames.map(t=>t.buffer),this.recentFrames=[]),this.maxHoldTimer=setTimeout(()=>{this.maxHoldTimer=null,u.warn("PushToTalk","hold hit its ceiling \u2014 releasing"),this.release();},Bn),u.event("ptt","press",{isContinuation:e,preRollFrames:this.preRollToFlush.length}),this.deps.onHeldChange(true),e||this.deps.onTurnStart(),!e}release(){this.held&&(this.held=false,this.clearMaxHoldTimer(),u.event("ptt","release"),this.deps.onHeldChange(false),this.tailTimer=setTimeout(()=>{this.tailTimer=null,this.closeTurn();},Hn));}gate(e){if(!this.open)return this.rememberFrame(e),[this.silenceOfSize(e.byteLength)];if(!this.preRollToFlush.length)return [e];let t=this.preRollToFlush;return this.preRollToFlush=[],t.push(e),t}reset(){this.held=false,this.open=false,this.preRollToFlush=[],this.recentFrames=[],this.clearTailTimer(),this.clearMaxHoldTimer();}closeTurn(){this.open&&(this.open=false,this.preRollToFlush=[],this.deps.onTurnEnd());}rememberFrame(e){let t=Date.now();for(this.recentFrames.push({capturedAt:t,buffer:e.slice(0)});this.recentFrames.length&&t-this.recentFrames[0].capturedAt>Fn;)this.recentFrames.shift();}silenceOfSize(e){let t=this.silenceByteSize.get(e);return t||(t=new ArrayBuffer(e),this.silenceByteSize.size>8&&this.silenceByteSize.clear(),this.silenceByteSize.set(e,t)),t}clearTailTimer(){this.tailTimer&&(clearTimeout(this.tailTimer),this.tailTimer=null);}clearMaxHoldTimer(){this.maxHoldTimer&&(clearTimeout(this.maxHoldTimer),this.maxHoldTimer=null);}};var Oi="server_tick";var $e=class{constructor(){this.wedge=[];}note(e,t){if(typeof e!="number"||!Number.isFinite(e))return null;let n=t-e;for(;this.wedge.length>0&&this.wedge[this.wedge.length-1].offset>=n;)this.wedge.pop();for(this.wedge.push({offset:n,at:t});this.wedge.length>0&&t-this.wedge[0].at>6e4;)this.wedge.shift();let r=n-this.wedge[0].offset;return r<25?0:r}minOffset(){return this.wedge.length>0?this.wedge[0].offset:null}hasSamples(){return this.wedge.length>0}reset(){this.wedge=[];}};var Xe=class{constructor(e){this.opts=e;this.timer=null;this.lastProbeAt=0;this.lastMessageAt=0;this.loopLagPeak=0;this.ticksSeen=false;this.suspended=false;this.degraded=false;this.degradedAt=0;this.cleanSince=null;this.lastSeq=null;this.seqAtGap=null;this.resumeAt=null;this.resumeSeqJump=null;this.resumeCount=0;}begin(e=Date.now()){this.lastProbeAt=e,this.lastMessageAt=e;}start(e=Date.now()){this.timer||(this.begin(e),this.timer=setInterval(()=>this.tick(Date.now()),100));}stop(){this.timer&&clearInterval(this.timer),this.timer=null;}noteMessage(e,t,n=false){let r=this.expired(t)||this.degraded;this.lastMessageAt=t,this.loopLagPeak=0,this.suspended=false,n&&(this.ticksSeen=true);let s=typeof e=="number"&&Number.isFinite(e)?e:null;r&&this.resumeAt===null&&(this.resumeAt=t,this.seqAtGap=this.lastSeq),this.resumeAt!==null&&t-this.resumeAt<=300&&(this.resumeCount++,s!==null&&this.seqAtGap!==null&&(this.resumeSeqJump=s-this.seqAtGap)),s!==null&&(this.lastSeq=s),this.degraded&&this.cleanSince===null&&(this.cleanSince=t);}reset(){this.stop(),this.lastMessageAt=0,this.loopLagPeak=0,this.ticksSeen=false,this.suspended=false,this.degraded=false,this.degradedAt=0,this.cleanSince=null,this.lastSeq=null,this.seqAtGap=null,this.resumeAt=null,this.resumeSeqJump=null,this.resumeCount=0;}tick(e){let t=Math.max(0,e-this.lastProbeAt-100);if(this.lastProbeAt=e,t>this.loopLagPeak&&(this.loopLagPeak=t),this.degraded){this.evaluateRecovery(e);return}let n=this.currentGap(e);n!==null&&(this.degraded=true,this.degradedAt=e,this.cleanSince=null,this.resumeAt=null,this.resumeSeqJump=null,this.resumeCount=0,this.opts.onVerdict({state:"degraded",scope:this.loopLagPeak>=this.opts.loopLagHighMs?"device":"network",gapMs:n,loopLagMs:this.loopLagPeak}));}currentGap(e,t=1e3){if(!this.ticksSeen||this.suspended)return null;let n=e-this.lastMessageAt;return n>=t?n:null}evaluateRecovery(e){if(e-this.degradedAt>6e4){this.suspended=true,this.clear(e);return}if(this.currentGap(e,700)!==null){this.cleanSince=null;return}this.cleanSince!==null&&e-this.cleanSince>=2500&&this.clear(e);}clear(e){this.degraded=false,this.cleanSince=null;let t=this.resumeCount>=4&&this.resumeSeqJump!==null?this.resumeSeqJump:void 0;this.opts.onVerdict({state:"ok",scope:"network",gapMs:e-this.degradedAt,...t!==void 0&&{seqJump:t}}),this.resumeAt=null,this.resumeSeqJump=null,this.resumeCount=0;}expired(e){return this.currentGap(e)!==null}};var ue=class{constructor(){this.listeners={};}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),()=>{this.listeners[e].delete(t);}}emit(e,...t){let n=this.listeners[e];if(n)for(let r of n)r(...t);}hasListeners(e){return (this.listeners[e]?.size??0)>0}removeAll(){for(let e in this.listeners)this.listeners[e]?.clear();}};var Li=i=>{let e=[];return i.fieldType&&e.push(i.fieldType),i.filled!==void 0&&e.push(i.filled?"filled":"empty"),i.checked!==void 0&&e.push(i.checked?"checked":"not checked"),i.shows&&e.push(`shows "${i.shows}"`),i.choiceOf&&e.push(`choice in ${i.choiceOf}`),i.options?.length&&e.push(`one of: ${i.options.join(" | ")}`),i.submits&&e.push("submits form"),i.count&&e.push(`${i.count} identical`),i.disabled&&e.push("disabled"),i.sensitive&&e.push("never fillable"),i.path&&e.push(i.path),i.site&&e.push(i.site),i.current&&e.push("this page"),i.children&&e.push(`contains ${i.children.join(" ")}`),e},xi=i=>i.length>0?` [${i.join(", ")}]`:"",mo=(i,e)=>{let t=e.filter(r=>r.item?.screenPosition).length,n=[`list${i.id} "${i.name}" \u2014 ${i.total} items, ${t} on screen`];for(let r of e){let s=r.item,o=Li(r);s.screenPosition&&o.unshift(`on screen #${s.screenPosition}`);let a=s.detail?` \u2014 ${s.detail}`:"";n.push(` ${s.position}. ${r.handle} ${r.kind} "${r.name}"${a}${xi(o)}`);}return n};function zt(i){let e=[`On the ${i.pageName} page \u2014 ${i.url} \u2014 "${i.title}"`],t=s=>`${s.handle} ${s.kind} "${s.name}"${xi(Li(s))}`,n=i.lists??[];if(n.length===0){for(let s of i.nodes)e.push(t(s));return e.join(`
|
|
2
|
+
`)}let r=i.nodes.filter(s=>!s.item);for(let s of r)s.kind!=="link"&&e.push(t(s));for(let s of n){let o=i.nodes.filter(a=>a.item?.list===s.id).sort((a,l)=>a.item.position-l.item.position);o.length>0&&e.push(...mo(s,o));}for(let s of r)s.kind==="link"&&e.push(t(s));return e.join(`
|
|
3
|
+
`)}function Di(i){return i.nodes.map(e=>({h:e.handle,n:e.name,...e.kind==="field"&&e.fieldType&&{t:e.fieldType},...e.sensitive&&{sensitive:true},...e.submits&&{submit:true},...e.item&&{card:{list:e.item.list,position:e.item.position,...e.item.screenPosition&&{screen:e.item.screenPosition},...e.item.detail&&{detail:e.item.detail}}}}))}var Fi=i=>{let e=i?.fields;if(!Array.isArray(e))return [];let t=new Map;for(let n of e){if(t.size>=12)break;let{h:r,v:s}=n??{};typeof r!="string"||typeof s!="string"||t.set(r,s.slice(0,2e3));}return [...t].map(([n,r])=>({handle:n,value:r}))},fo={stale:"the page changed since it was read",unknown_target:"it is not on this page",not_fillable:"it is not a box the avatar can type into",sensitive:"passwords and payment details are only theirs to type",disabled:"it is disabled right now",read_only:"it is read-only",no_such_option:"none of its choices matches",rejected:"the page would not take that value",invalid:"the site says that value is not valid"},Hi=i=>{let e=i.filter(r=>r.outcome!=="ok");if(e.length===0)return;let t=i.filter(r=>r.outcome==="ok").map(r=>`"${r.name}"`),n=e.map(r=>{let s=fo[r.outcome];return `"${r.name}" (${s}${r.detail?`: ${r.detail}`:""})`});return [t.length>0?`filled ${t.join(", ")}`:"",`could not fill ${n.join(", ")}`].filter(Boolean).join("; ")},Bi={stale:"the page has changed since it was read",unknown_target:"that button is not on this page",not_a_submit:"that button does not send a form",disabled:"that button is disabled right now",invalid:"the form is not complete yet",requires_reload:"sending this form would open a new page and end this call, so they need to press it themselves"};var W={camera:true,screen:false,micMute:true,endCall:true,actions:false,mood:false,page:{read:false,scroll:false,navigate:false,click:false,fill:false,submit:false}},x=(i,e)=>typeof i=="boolean"?i:e,Ui=i=>{if(!i||typeof i!="object")return W;let e=i,t=e.page&&typeof e.page=="object"?e.page:{},n=x(t.read,W.page.read),r=n&&x(t.click,false);return {camera:x(e.camera,W.camera),screen:x(e.screen,W.screen),micMute:x(e.micMute,W.micMute),endCall:x(e.endCall,W.endCall),actions:x(e.actions,W.actions),mood:x(e.mood,W.mood),page:{read:n,scroll:n&&x(t.scroll,false),navigate:n&&x(t.navigate,false),click:r,fill:n&&x(t.fill,false),submit:r}}};var go=/^([xy])=([+-]?)(\d{1,5})(%?)$/;var vo=i=>{let e=go.exec(i);if(!e)return null;let[,t,n,r,s]=e,o=Number(r);return !s&&o>2e4||s&&o>100?null:{axis:t,move:{value:n==="-"?-o:o,percent:s==="%",relative:n!==""}}},de=i=>{let e=i.split(",");if(e.length>2)return null;let t={};for(let n of e){let r=vo(n.trim());if(!r||t[r.axis])return null;t[r.axis]=r.move;}return t.x||t.y?t:null};var So=new Set(["top-left","top-center","top-right","middle-left","center","middle-right","bottom-left","bottom-center","bottom-right"]),Eo=/^bounce(?:=(.+))?$/,Ao=new Set(["forever","loop","infinite"]),bo=5,yo=i=>{if(i===void 0)return 1;if(Ao.has(i))return "forever";if(!/^\d{1,3}$/.test(i))return null;let e=Number(i);return e<1?null:Math.min(e,bo)},he=i=>{let e=i.trim().toLowerCase();if(!e)return null;if(So.has(e))return {kind:"spot",spot:e};if(e==="expand")return {kind:"stage",open:true};if(e==="collapse")return {kind:"stage",open:false};if(e==="stop"||e==="still")return {kind:"effect",effect:"stop"};let t=Eo.exec(e);if(t){let r=yo(t[1]);return r===null?null:{kind:"effect",effect:"bounce",times:r}}let n=de(e);return n?{kind:"move",...n}:null};var _o=new Set(["search","open","new_tab","switch","close","reload"]),To=new Set(["search","open","switch"]);function Wi(i){if(typeof i!="string")return null;let e=i.indexOf("="),t=(e<0?i:i.slice(0,e)).trim(),n=e<0?"":i.slice(e+1).trim();return !_o.has(t)||To.has(t)&&!n?null:n?{action:t,target:n}:{action:t}}var Io=new Set(["CONNECTION_FAILED","SERVER_ERROR","SESSION_TOKEN_FETCH_FAILED"]),Vi=1e3,Gi=1e3,Po=50,Co=600,Oo={ok:void 0,stale:"the page has changed since it was read",unknown_target:"that place is not on this page"},No={ok:void 0,stale:"the page has changed since it was read",unknown_target:"that link is not on this page",not_navigable:"that is not a link on this site",requires_reload:"opening that page would end this call",already_here:"they are already on that page",no_history:"there is nowhere in this call's history to go"},Lo={ok:void 0,stale:"the page has changed since it was read",unknown_target:"that is not on this page",not_clickable:"that is not a button or field the avatar can press",submits_form:"that button submits a form, which needs a confirmed action",requires_reload:"pressing that would open a new page and end this call",disabled:"that is disabled right now"},xo=400,Do=[300,1e3,2500],Fo=3e3,Ho="the page could not be reached",Bo={ok:void 0,not_found:"no open tab matches that",blocked:"that is not a web address it can open",failed:"the browser refused"},Uo=1e3,$i=12e3,Yt=()=>{},Wo=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||void 0}catch{return}},pe=i=>typeof i?.arg=="string"?i.arg:"",Vo=i=>i?.arg==="tab"||i?.arg==="window"||i?.arg==="screen"?i.arg:null,me=i=>typeof i?.generation=="number"?i.generation:void 0,fe=class extends Error{constructor(t){super("Failed to fetch session token");this.reason=t;this.name="SessionTokenError";}},Jt=class{constructor(e,t){this.sessionPhase="idle";this.paintPhase="none";this.turnPhase="idle";this.playful={last:null,busyUntilMs:0};this.sessionId=0;this.turnId=0;this.isConnected=false;this.lifecycle=0;this.userStoppedAt=null;this.speakReportedForStop=false;this.deliveryLagMs=null;this.firstAudioAt=null;this.firstAudioLagMs=null;this.transit=new $e;this.reconnectAttempt=0;this.hasBeenLive=false;this.reconnectTimer=null;this.intentionalClose=false;this.serverInitiatedReason=null;this.lastEmittedError=null;this.noticeReceived=false;this.noticeOnly=false;this.visualState="normal";this.micMuted=false;this.speakerMuted=false;this.pushToTalk=null;this.health={ingest:"ok",stt:"ok",llm:"ok",tts:"ok",downlink:"ok"};this.downlinkScope="network";this.downlinkVerdict=null;this.netStatusLastSentAt=0;this.netStatusTimer=null;this.moodDetectionOn=false;this.moodLatest=null;this.moodLastSentKey=null;this.moodLastSentAt=0;this.moodTimer=null;this.appEvents=new Be;this.actions=new Ue({canDeclare:()=>this.canDeclareActions(),send:e=>this.sendActionsSet(e)});this.actionCallsSeen=new Set;this.actionFlows=new We;this.actionsGrantWarned=false;this.actionRereadTimer=null;this.jobQueue=[];this.processing=false;this.turnOpen=false;this.scriptTail={jobId:-1,upto:0,text:""};this.activeStream=null;this.ws=null;this.micStream=null;this.micStartedAt=null;this.agcEnabled=true;this.agcRestoreTimer=null;this.events=new ue;this.transcript=null;this.greetingText="";this.greetingLanguage="en";this.greetingKey="";this.greetingEntry=null;this.greetingDecided=false;this.greetingDecisionTimer=null;this.greetingAwaitingPlayback=false;this.greetingDelayTimer=null;this.greetingAwaitingPaint=null;this.greetingPaintTimer=null;this.greetingAwaitingMic=null;this.greetingMicTimer=null;this.micPipelineSettled=false;this.talkingArmed=false;this.playerLeadInTimer=null;this.connectTonePlaying=false;this.connectToneTimer=null;this.connectToneStartedAt=null;this.tonePainted=false;this.toneSessionLive=false;this.greetingPlayed=false;this.skipGreetingOnce=false;this.greetedThisSession=false;this.jobCounter=0;this.riveReady=false;this.avatarConfig=null;this.serverReady=false;this.voiceSettings=null;this.watermark=false;this.lipSyncTuning=new se;this.rivSrc=null;this.pendingRivBytes=null;this.pendingSession=false;this.pendingContext=[];this.lastContextSnapshot=null;this.firstPage=null;this.pageGeneration=0;this.lastPageContext=null;this.pageReadThisUtterance=false;this.pageWork=Promise.resolve();this.pageSession=0;this.heardSpeech=null;this.pendingTours=new Map;this.tourRequestSeq=0;this.sessionCapabilities=null;this.initAckPromise=null;this.initAckResolve=null;this.initAckReject=null;this.loadInFlight=null;this.startInvoked=false;this.utteranceBuffer={audio:[],alignments:[],displayAlignments:[],visemes:[],flushTimer:null};this.firstChunkPending=true;this.responseSlow=false;this.heldResumeToken=null;this.stopCount=0;this.mountSurface="inline";this.load=()=>this.serverReady?Promise.resolve():this.loadInFlight?this.loadInFlight:(this.loadInFlight=this.runLoad().finally(()=>{this.loadInFlight=null;}),this.loadInFlight);this.runLoad=async()=>{let e=this.lifecycle;this.setPaintPhase("loading");try{if(this.mode==="player")await this.paintFromCache(e)?this.revalidatePaint(e):await this.fetchRenderConfig(e);else {let t=await this.paintFromCache(e);this.mode==="call"&&!this.startInvoked&&(t?await this.revalidatePaint(e):await this.fetchRenderConfig(e));}}catch(t){if(this.stale(e))return;if(u.error("Runtime","Avatar load failed",t),this.setPaintPhase("failed"),t instanceof ce&&qt(t.serverCode,t.serverMessage)){this.emitError("DOMAIN_NOT_ALLOWED","This page's domain is not in the deployment's authorised domains","server",{cause:t});return}let n=t instanceof fe;this.emitError(n?"SESSION_TOKEN_FETCH_FAILED":"AVATAR_LOAD_FAILED",n?"Failed to fetch session token":"Failed to load avatar","sdk",{cause:n?t.reason:t});return}this.stale(e)||this.mode!=="call"&&this.start();};this.start=async()=>{let e=this.lifecycle,t=this.stopCount;if(this.cancelReconnect(),this.startInvoked=true,this.lastEmittedError=null,this.startConnectTone(),this.mode!=="player"&&this.setSessionPhase("connecting"),await this.load(),!this.stale(e)){if(this.paintPhase==="failed"){this.setSessionPhase("idle");return}if(this.mode==="player"){this.setSessionPhase("active");return}try{(!this.ws||this.ws.readyState===WebSocket.CLOSED)&&await this.openWebSocket();let n=this.ws;if(this.staleSocket(e,n)||(this.initAckPromise&&(u.debug("Runtime","Waiting for server to acknowledge init..."),await this.initAckPromise),this.staleSocket(e,n))||this.noticeOnly)return;this.ws?.send(JSON.stringify({type:"start"}));}catch(n){if(this.stopCount!==t&&!this.lastEmittedError||(!this.stale(e)&&this.paintPhase!=="painted"&&this.setPaintPhase("failed"),this.lastEmittedError))return;if(n instanceof fe){this.emitError("SESSION_TOKEN_FETCH_FAILED","Failed to fetch session token","sdk",{cause:n.reason});return}this.emitError("UNKNOWN","Unexpected runtime error","sdk",{cause:n});}}};this.paintFromCache=async e=>{let[t,n]=await Promise.all([this.cache.getCachedRiv(this.avatarId),this.cache.getCachedAvatarConfig(this.avatarId)]);if(this.stale(e))return false;if(this.cachedConfigVersion=n?.configVersion,this.cachedRivVersion=t?.rivVersion,t&&n){let r=await this.urlResolver.bytesToSrc(t.bytes);return this.stale(e)?(this.urlResolver.revokeSrc(r),false):(this.rivSrc&&this.urlResolver.revokeSrc(this.rivSrc),this.rivSrc=r,this.avatarConfig={...n,rive:{...n.rive,src:r}},this.pendingRivBytes=t.bytes,this.serverReady=true,this.onRivReady(),true)}return t&&(this.pendingRivBytes=t.bytes),false};this.resolveSessionToken=async()=>{try{let e=await this.getSessionToken();if(!e)throw new Error("getSessionToken() returned an empty token");return e}catch(e){throw new fe(e)}};this.fetchRenderConfig=async e=>{let t={"Content-Type":"application/json"},n={avatarId:this.avatarId,...this.embedHostOrigin&&{hostOrigin:this.embedHostOrigin},needAvatarStream:!this.pendingRivBytes,...this.cachedConfigVersion!==void 0&&{cachedConfigVersion:this.cachedConfigVersion},...this.cachedRivVersion!==void 0&&{cachedRivVersion:this.cachedRivVersion}},r="";this.deployId?r=this.deployId:this.getSessionToken?r=await this.resolveSessionToken():this.apiKey&&(r=this.apiKey),t.Authorization=`Bearer ${r}`;let s=await fetch(`${this.httpUrl}/v1/avatar/config`,{method:"POST",headers:t,body:JSON.stringify(n)});if(!s.ok)throw new ce(s.status,await s.json().catch(()=>null));let o=await s.json();if(this.serverReady)return this.repaintFromPayload(o,e);let a=o.rivUrl?await this.fetchRivBytes(o.rivUrl):this.pendingRivBytes;if(!a)throw new Error("config response had no rivUrl and no cache");await this.applyRenderPayload(o,a,e);};this.paintForNotice=async()=>{let e=this.lifecycle;try{u.info("Runtime","notice with nothing painted \u2014 resolving config"),await this.fetchRenderConfig(e);}catch(t){if(this.stale(e))return;u.error("Runtime","Notice paint failed \u2014 notice will be silent",t),this.setPaintPhase("failed");}};this.revalidatePaint=async e=>{try{await this.fetchRenderConfig(e);}catch(t){u.warn("Runtime","Revalidation failed \u2014 keeping the cached paint",t);}};this.repaintFromPayload=async(e,t)=>{let n=e.rivUrl?await this.fetchRivBytes(e.rivUrl):null;if(e.rivUrl&&!n&&u.warn("Rive","New rig failed to download \u2014 keeping the painted one"),n)return this.applyRenderPayload(e,n,t);if(this.stale(t))return;let r=e.watermark===true!==this.watermark;this.watermark=e.watermark===true;let s=e.configVersion!==void 0&&e.configVersion!==this.avatarConfig?.configVersion,o=JSON.stringify(xe(e.performance)??null)!==JSON.stringify(this.avatarConfig?.performance??null);!s&&!r&&!o||(this.avatarConfig=this.paintedConfigFrom(e,this.rivSrc),this.cachedConfigVersion=e.configVersion,e.rivVersion!==void 0&&(this.cachedRivVersion=e.rivVersion),(s||o)&&e.cacheable!==false&&this.cache.setCachedAvatarConfig(this.avatarId,this.toCacheableConfig(this.avatarConfig)).catch(()=>{}),this.onRivReady());};this.applyRenderPayload=async(e,t,n)=>{let r=await this.urlResolver.bytesToSrc(t);if(this.stale(n))return this.urlResolver.revokeSrc(r);this.watermark=e.watermark===true,this.cachedConfigVersion=e.configVersion,this.cachedRivVersion=e.rivVersion,this.rivSrc&&this.urlResolver.revokeSrc(this.rivSrc),this.rivSrc=r,this.avatarConfig=this.paintedConfigFrom(e,this.rivSrc),this.serverReady=true,e.cacheable!==false&&(e.rivVersion!==void 0&&this.cache.setCachedRiv(this.avatarId,t,e.rivVersion).catch(()=>{}),this.cache.setCachedAvatarConfig(this.avatarId,this.toCacheableConfig(this.avatarConfig)).catch(()=>{})),this.pendingRivBytes=t,this.onRivReady();};this.setMountSurface=e=>{this.mountSurface=e;};this.getLipSyncTuning=()=>this.lipSyncTuning;this.speakAudio=async e=>{if(this.mode!=="audio"){this.emitError("INVALID_MODE","speakAudio can only be used in audio mode","sdk",{fatal:false});return}if(this.ws?.readyState!==WebSocket.OPEN){this.emitError("NOT_CONNECTED","speakAudio() needs a live session \u2014 call start() first","sdk",{fatal:false});return}try{let t;e instanceof Blob?t=await e.arrayBuffer():e instanceof Float32Array?t=e.buffer:t=e;let n=15*1024*1024;if(t.byteLength>n){this.emitError("INVALID_INPUT","Audio payload too large (max 15MB)","sdk",{fatal:!1});return}this.ws?.send(t);}catch(t){this.emitError("UNKNOWN","Failed to process audio payload","sdk",{cause:t,fatal:false});}};this.isPushToTalk=()=>this.turnTaking==="push-to-talk";this.isTalking=()=>this.pushToTalk?.isHeld()??false;this.startTalking=()=>{this.pushToTalk&&this.sessionPhase==="active"&&(this.noticeReceived||this.pushToTalk.press());};this.stopTalking=()=>{this.pushToTalk?.release();};this.setMicMuted=e=>{this.micMuted!==e&&(this.micMuted=e,this.queueClientNetStatus(),this.events.emit("mic-muted",e));};this.setSpeakerMuted=e=>{this.speakerMuted!==e&&(this.speakerMuted=e,this.events.emit("speaker-muted",e));};this.getMicMuted=()=>this.micMuted;this.getSpeakerMuted=()=>this.speakerMuted;this.commandHandlers={stop:e=>{this.cancelSpeech(),this.reportCommandStatus("stop",this.commandTurnId(e),"ok");},request_vision:e=>{this.events.emit("vision-request",this.commandTurnId(e));},flip_camera:e=>{let t=typeof e?.args=="string"?e.args:null,n=t==="front"?"front":t==="back"?"back":"toggle";this.events.emit("camera-flip",n,this.commandTurnId(e));},mute_mic:e=>{if(this.environment==="meeting"){this.reportCommandStatus("mute_mic",this.commandTurnId(e),"unsupported");return}this.setMicMuted(true),this.reportCommandStatus("mute_mic",this.commandTurnId(e),"ok");},unmute_mic:e=>{this.setMicMuted(false),this.reportCommandStatus("unmute_mic",this.commandTurnId(e),"ok");},close_camera:e=>{this.events.emit("camera-close",this.commandTurnId(e));},open_camera:e=>{this.events.emit("camera-open",this.commandTurnId(e));},request_screen:e=>{let t=this.commandTurnId(e);if(!this.capabilities?.screen){this.reportScreenStatus("unavailable",t,{reason:"not granted"});return}if(!this.perception?.screen||!this.events.hasListeners("screen-request")){this.reportScreenStatus("unavailable",t,{reason:"screen sharing is not enabled here"});return}this.events.emit("screen-request",Vo(e),t);},stop_screen:e=>{let t=this.commandTurnId(e);if(!this.events.hasListeners("screen-stop")){this.reportCommandStatus("stop_screen",t,"unsupported");return}this.events.emit("screen-stop",t);},scroll_to:e=>this.runPageCommand("scroll_to",e,t=>t.scroll,async(t,n)=>{let r=await t.scroll(pe(e),me(e));this.reportCommandStatus("scroll_to",n,r==="ok"?"ok":"failed",Oo[r]);}),navigate_to:e=>this.runPageCommand("navigate_to",e,t=>t.navigate,async(t,n)=>{let r=await t.navigate(pe(e),me(e));this.reportCommandStatus("navigate_to",n,r==="ok"?"ok":"failed",No[r]);}),click_element:e=>this.runPageCommand("click_element",e,t=>t.click,async(t,n)=>{let r=await t.click(pe(e),me(e));this.reportCommandStatus("click_element",n,r==="ok"?"ok":"failed",Lo[r]),r==="ok"&&this.scheduleReadAfterAction();}),fill_fields:e=>this.runPageCommand("fill_fields",e,t=>t.fill,async(t,n)=>{let r=Fi(e);if(r.length===0){this.reportCommandStatus("fill_fields",n,"failed","there was nothing to fill");return}let s=await t.fill(r,me(e)),o=Hi(s);u.event("page","Fields filled",{fields:s.map(a=>`${a.handle}:${a.outcome}`)}),this.reportCommandStatus("fill_fields",n,o?"failed":"ok",o),s.some(a=>a.outcome==="ok")&&this.scheduleReadAfterAction();}),submit_form:e=>this.runPageCommand("submit_form",e,t=>t.submit,async(t,n)=>{let{outcome:r,detail:s}=await t.submit(pe(e),me(e)),o=r==="ok"?void 0:`${Bi[r]}${s?`: ${s}`:""}`;this.reportCommandStatus("submit_form",n,r==="ok"?"ok":"failed",o),r==="ok"&&this.scheduleReadAfterAction();}),widget_control:e=>{let t=this.commandTurnId(e);if(this.mountSurface!=="widget"){this.reportCommandStatus("widget_control",t,"unsupported","the avatar is not in a widget here");return}let n=he(pe(e));if(!n){this.reportCommandStatus("widget_control",t,"failed","that is not somewhere the avatar can put itself");return}this.events.emit("widget-command",n,t);},browser:e=>{let t=this.commandTurnId(e),n=this.browser;if(!n){this.reportCommandStatus("browser",t,"unsupported","this client cannot drive the browser");return}let r=Wi(e?.arg);if(!r){this.reportCommandStatus("browser",t,"failed","that is not a browser command");return}Promise.resolve().then(()=>n.run(r)).catch(s=>(u.warn("Runtime","browser command threw",{error:String(s)}),"failed")).then(s=>this.reportCommandStatus("browser",t,s==="ok"?"ok":"failed",Bo[s]));},close_call:e=>{this.reportCommandStatus("close_call",this.commandTurnId(e),"ok"),this.stop({intentionalClose:true,code:4001,reason:"Closed by server command"});}};this.loadCachedGreeting=async()=>{if(!(!this.greeting?.enabled||this.greetingEntry))try{let e=await this.cache.getCachedGreeting(this.greetingKey);if(!e)return;this.greetingEntry=e,this.sentGreetingId=e.greetingId,u.debug("Greeting","Loaded greeting from cache",{greetingId:e.greetingId});}catch{}};this.openWebSocket=async()=>{if(!this.wsUrl)throw new Error("WebSocket URL not resolved");if(this.ws&&this.ws.readyState===WebSocket.OPEN)return;if(!this.pendingRivBytes){let t=await this.cache.getCachedRiv(this.avatarId);this.pendingRivBytes=t?.bytes??null,this.cachedRivVersion=t?.rivVersion;}await this.loadCachedGreeting();let e=this.getSessionToken?await this.resolveSessionToken():void 0;return this.initAckPromise=new Promise((t,n)=>{this.initAckResolve=t,this.initAckReject=n;}),new Promise((t,n)=>{try{let r=new WebSocket(this.wsUrl);this.ws=r,r.binaryType="arraybuffer",r.onopen=()=>{if(this.ws!==r)return;u.event("WebSocket","Connection opened"),this.intentionalClose=!1,this.serverInitiatedReason=null;let s=Wo();r.send(JSON.stringify({type:"init",...this.deployId?{deployId:this.deployId,...this.embedHostOrigin&&{hostOrigin:this.embedHostOrigin}}:{avatarId:this.avatarId,...e?{sessionToken:e}:{apiKey:this.apiKey}},...this.onResumeState&&{resumable:!0},...this.resumeKept&&{resume:this.resumeKept},...this.voiceSettings&&{voiceSettings:this.voiceSettings},...this.brain&&{brain:this.brain},...this.languages!==void 0&&{languages:this.languages},...this.perception&&{perception:{...this.perception,...this.readsMood&&{mood:!0}}},...this.greeting?.enabled&&{greeting:{enabled:!0,...this.greetingText&&{message:this.greetingText},language:this.greetingLanguage,...this.sentGreetingId&&{cachedGreetingId:this.sentGreetingId}}},...this.useOwnVoice!==void 0&&{useOwnVoice:this.useOwnVoice},...this.useOwnBrain!==void 0&&{useOwnBrain:this.useOwnBrain},mode:this.mode,turnTaking:this.turnTaking,systemPrompt:this.systemPrompt,needAvatarStream:!this.pendingRivBytes,...this.cachedConfigVersion!==void 0&&{cachedConfigVersion:this.cachedConfigVersion},...this.cachedRivVersion!==void 0&&{cachedRivVersion:this.cachedRivVersion},...this.platform&&{platform:this.platform},...this.browser&&{browser:!0},surface:this.mountSurface,...this.framed!==void 0&&{framed:this.framed},...this.micBlocked()&&{micBlocked:!0},...s&&{timeZone:s}})),t();},r.onmessage=s=>{this.ws===r&&this.handleServerMessage(s);},r.onclose=s=>{if(this.ws!==r){u.debug("WebSocket","Ignoring onclose \u2014 already handled");return}let o=this.intentionalClose,a=this.serverInitiatedReason;if(this.isConnected=!1,this.events.emit("connection-status",!1),a)u.info("WebSocket","Closed following server message",{...a});else if(s.code===In)u.info("WebSocket","Meeting ended; closed by the server");else if(s.code===Pn)u.info("WebSocket","A newer session took over this meeting");else if(o)u.info("WebSocket","Connection closed gracefully");else {let{code:l,message:d}=this.classifyClose(s);this.emitError(l,d,"network",{cause:s?.reason});}this.ws=null,this.intentionalClose=!1,this.serverReady=!1,this.rejectInitAck("WebSocket closed before init acknowledged"),this.stop();},r.onerror=s=>{if(this.ws!==r)return;let o=this.intentionalClose,a=this.serverInitiatedReason;a?u.info("WebSocket","Transport error after server message",{...a}):o?u.info("WebSocket","Transport error during intentional close"):this.emitError("CONNECTION_FAILED","Transport error on the connection to the avatar service","network",{cause:s}),this.ws=null,this.isConnected=!1,this.events.emit("connection-status",!1),this.intentionalClose=!1,this.serverReady=!1,this.rejectInitAck("WebSocket error before init acknowledged"),this.stop(),n(s);};}catch(r){this.emitError("CONNECTION_FAILED","Could not open a connection to the avatar service","network",{cause:r}),n(r);}})};this.onRivReady=async()=>{if(!this.avatarConfig)return;this.setPaintPhase("painted");let e=this.avatarConfig.rive,t=this.voiceSettings?.visimeMs;this.lipSyncTuning.reset(this.avatarConfig.lipSync),this.lipSyncTuning.apply(this.voiceSettings?.lipSync),u.event("Runtime","lip-sync tuning seeded",{configVersion:this.avatarConfig.configVersion,fromConfig:!!this.avatarConfig.lipSync,overridden:!!this.voiceSettings?.lipSync,...this.lipSyncTuning.snapshot()}),this.events.emit("avatar-config",{...this.avatarConfig,rive:{...e,src:this.rivSrc,watermark:this.watermark},lipSync:{...this.avatarConfig.lipSync,...t!==void 0?{visemeMs:t}:{}}}),this.pendingSession&&(this.pendingSession=false,u.info("Runtime","Riv ready \u2014 starting deferred session"),this.startSession());};this.micBlocked=()=>this.mode==="call"&&this.usesDefaultMic&&!$n();this.startMic=async()=>{let e=this.ws;if(this.micBlocked())return this.emitError("MIC_PERMISSION_DENIED","This page does not allow the microphone","sdk"),false;let t;try{t=await this.getMicStreamFn();}catch(n){return this.emitError("MIC_PERMISSION_DENIED","Microphone permission denied","sdk",{cause:n}),false}return this.ws!==e||e?.readyState!==WebSocket.OPEN?(u.warn("Runtime","session closed while awaiting mic \u2014 releasing it"),t.getTracks().forEach(n=>n.stop()),false):(this.micStream=t,this.micPipelineSettled=false,this.micStartedAt=Date.now(),this.agcEnabled=true,this.events.emit("mic-start",this.micStream),true)};this.setAgcForAvatarSpeech=e=>{if(!(!this.micStream||this.environment==="meeting")){if(this.agcRestoreTimer!==null&&(clearTimeout(this.agcRestoreTimer),this.agcRestoreTimer=null),e){this.applyAgc(false);return}this.agcRestoreTimer=setTimeout(()=>{this.agcRestoreTimer=null,this.applyAgc(true);},Co);}};this.fetchRivBytes=async(e,t=false)=>{try{let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status}`);return await n.arrayBuffer()}catch(n){return t?(u.error("Rive","Riv fetch failed after retry",{cause:n}),null):(u.warn("Rive","Riv fetch failed \u2014 retrying once",{cause:n}),this.fetchRivBytes(e,true))}};let n=Bt(e);if(this.environment=n.environment,this.environment==="meeting"&&(this.lipSyncTuning.maxStepFrames=Dn),n.debug&&u.setLogLevel(0),u.debug("Runtime","Initializing with config",n),this.mode=n.mode||"call",this.turnTaking=this.mode==="call"&&n.turnTaking?.mode==="push-to-talk"?"push-to-talk":"auto",this.turnTaking==="push-to-talk"&&(this.pushToTalk=new Ge({onTurnStart:()=>this.openUserTurn(),onTurnEnd:()=>this.closeUserTurn(),onHeldChange:r=>this.events.emit("ptt-held",r)})),this.greeting=t.embedResume?.kept?void 0:n.avatar?.greeting,this.connectTone=t.embedResume?.kept?void 0:n.connectTone,this.avatarId=n.avatar?.avatarId||"default",this.systemPrompt=n.avatar?.systemPrompt,this.apiKey=n.apiKey,this.getSessionToken=n.getSessionToken,this.deployId=n.deployId,this.voiceSettings=n.avatar?.voiceSettings||null,!this.apiKey&&!this.getSessionToken&&!this.deployId)throw new Error("AvatarConfig requires apiKey, getSessionToken, or deployId");this.useOwnVoice=n.avatar?.voiceSettings?.useOwnVoice,this.useOwnBrain=n.avatar?.brain?.useOwnBrain,this.brain=n.avatar?.brain,this.languages=n.avatar?.languages,this.perception=n.perception,this.readsMood=this.mode==="call"&&!!n.perception?.camera&&!!t.readsMood,this.wsUrl=mt(),this.httpUrl=ft(),this.greeting?.enabled&&(this.greetingLanguage=this.greeting.language??"en",this.greetingText=this.greeting.message?Ft(this.greeting.message):"",this.greetingKey=Ht(this.avatarId,this.greetingLanguage,this.greetingText)),n.transcript?.enabled&&(this.transcript=new Ve(r=>this.events.emit("transcript",r),n.transcript.maxEntries)),this.cache=t.cache,this.urlResolver=t.urlResolver,this.pageSurface=t.pageSurface,this.browser=t.browser,this.pageBeforeLive=t.pageBeforeLive??false,this.reportsMicPipeline=t.reportsMicPipeline??false,this.usesDefaultMic=!t.getMicStream,this.getMicStreamFn=t.getMicStream??(async()=>{let r=await navigator.mediaDevices.getUserMedia({audio:this.environment==="meeting"?Ln:{echoCancellation:true,noiseSuppression:true,autoGainControl:false,channelCount:1}});return u.event("mic","settings",{...r.getAudioTracks()[0]?.getSettings()}),r}),this.platform=t.platform,this.framed=t.framed,this.embedHostOrigin=t.embedHostOrigin,this.onResumeState=t.embedResume?.onState,this.resumeKept=t.embedResume?.kept,this.downlinkWatchdog=new Xe({loopLagHighMs:this.platform?500:250,onVerdict:r=>this.applyDownlinkVerdict(r)});}paintedConfigFrom(e,t){return {avatarId:e.avatarId,configVersion:e.configVersion,pipelineMode:e.pipelineMode,rive:{...e.rive??{artboard:"",stateMachine:"",layout:{}},src:t},lipSync:e.lipSync,performance:xe(e.performance)??void 0}}toCacheableConfig(e){return {...e,rive:{...e.rive,src:"",watermark:void 0}}}async startSession(){if(this.isConnected||(this.resetHealth(),this.mode==="call"&&!this.noticeOnly&&!await this.startMic()))return;if(this.pageBeforeLive&&this.firstPage){let t=this.pageSession;if(await Promise.race([this.firstPage,new Promise(n=>setTimeout(n,Fo))]),t!==this.pageSession)return}if(this.isConnected=true,this.downlinkWatchdog.start(),this.mode==="call"&&!this.noticeOnly&&this.queueClientNetStatus(),this.pushToTalk&&this.sendClientVadStatus(true,"push_to_talk"),this.events.emit("connection-status",true),this.heldResumeToken&&this.onResumeState?.(this.heldResumeToken),this.heldResumeToken=null,this.setSessionPhase("active"),this.reconnectAttempt=0,this.hasBeenLive=true,this.markToneSessionLive(),this.noticeOnly)return;this.actions.syncNow(),this.greetingPlayed=false;let e=this.skipGreetingOnce;if(this.skipGreetingOnce=false,this.greetedThisSession=!!this.greeting?.enabled&&!e,!this.greeting?.enabled||e){this.greetingPlayed=e,this.enterListening();return}if(!this.playGreeting()){if(!this.greetingDecided){this.greetingAwaitingPlayback=true,this.setTurnPhase("greeting"),this.armGreetingBackstop();return}this.enterListening();}}stop(e={intentionalClose:false}){this.stopCount++,e.intentionalClose&&(this.intentionalClose=true,this.cancelReconnect()),this.teardownSession(e.code,e.reason,true),this.setSessionPhase("idle");}scheduleReconnect(e){if(this.environment!=="meeting"||this.reconnectTimer||!Io.has(e.code))return;let t=Nn[this.reconnectAttempt];if(t===void 0){u.warn("Runtime","Meeting reconnect attempts exhausted",{attempts:this.reconnectAttempt});return}this.reconnectAttempt++,u.event("session","reconnect_scheduled",{attempt:this.reconnectAttempt,delayMs:t,code:e.code}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.hasBeenLive&&this.skipNextGreeting(),this.start();},t);}cancelReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}setLipSyncTuning(e){this.lipSyncTuning.apply(e);}speakText(e){try{if(this.mode!=="tts"){this.emitError("INVALID_MODE","speakText() is only available in text mode","sdk",{fatal:!1});return}if(!e.trim()){this.emitError("INVALID_INPUT","speakText() needs non-empty text","sdk",{fatal:!1});return}if(e.length>5e3){this.emitError("INVALID_INPUT","Text too long (max 5000 chars)","sdk",{fatal:!1});return}if(this.ws?.readyState!==WebSocket.OPEN){this.emitError("NOT_CONNECTED","speakText() needs a live session \u2014 call start() first","sdk",{fatal:!1});return}this.ws?.send(JSON.stringify({type:"input",payload:{text:e}}));}catch(t){this.emitError("UNKNOWN","Unexpected error in speakText()","sdk",{cause:t,fatal:false});}}addLiveContext({context:e,update:t}){if(!e||e.trim().length===0){this.emitError("INVALID_INPUT","Context cannot be empty","sdk",{fatal:false});return}if(e.length>2e3){this.emitError("INVALID_INPUT","Context too long (max 2000 chars)","sdk",{fatal:false});return}let n=e.trim();if(!(!t&&n===this.lastContextSnapshot)){if(t||(this.lastContextSnapshot=n),this.ws?.readyState!==WebSocket.OPEN||!this.sessionCapabilities){t||(this.pendingContext=[]),this.pendingContext.push({context:n,update:t}),this.pendingContext.length>16&&this.pendingContext.shift();return}this.sendLiveContext(n,t);}}get capabilities(){return this.sessionCapabilities}pageSendSkipReason(e){return this.mode!=="call"?"wrong_mode":this.ws?.readyState!==WebSocket.OPEN?"no_session":this.capabilities?.page.read?e===this.lastPageContext?"unchanged":null:"not_granted"}skipNextGreeting(){this.skipGreetingOnce=true;}async requestTour(){if(!this.isConnected||!this.ws)return null;let e=await this.readPage();if(!e||e.reason==="not_granted"||e.reason==="wrong_mode"||e.reason==="no_session")return u.warn("Runtime","requestTour(): the page cannot be sent",{reason:e?.reason??"no_page_surface"}),null;let t=`t${++this.tourRequestSeq}`;return new Promise(n=>{let r=o=>{clearTimeout(s),this.pendingTours.delete(t),n(o);},s=setTimeout(()=>r(null),Un);this.pendingTours.set(t,r),this.ws?.send(JSON.stringify({type:"tour_request",requestId:t,greeted:this.greetedThisSession}));})}async sendFirstPage(){if(!this.pageSurface||!this.capabilities?.page.read)return;let e=this.pageSession;for(let t of [...Do,null]){let n=await this.readPage();if(n?.sent||this.pageGeneration>0||e!==this.pageSession||n)return;if(t===null){u.warn("Runtime","The page never answered at call start; waiting for a change");return}if(u.warn("Runtime","First page read reached no page \u2014 retrying",{delayMs:t}),await new Promise(r=>setTimeout(r,t)),e!==this.pageSession)return}}readPage(){let e=this.pageSurface;return e?this.queuePageWork(()=>this.readPageNow(e)):(u.debug("Runtime","readPage(): no page surface on this platform"),Promise.resolve(null))}async readPageNow(e){let t=this.pageSession;try{let n=this.pageGeneration+1,r=await e.read(n);if(!r)return null;let s=zt(r),o=r.unreadable?`${s} (${r.unreadable})`:s,a=t===this.pageSession?this.pageSendSkipReason(o):"no_session";return a?(await e.retag(this.pageGeneration),r.generation=this.pageGeneration):(this.pageGeneration=n,this.lastPageContext=o,this.ws?.send(JSON.stringify({type:"page_context",context:s,url:r.url,generation:r.generation,handles:Di(r),...r.covered&&{covered:r.covered},...r.unreadable&&{unreadable:r.unreadable}}))),u.event("page","Page read",{generation:r.generation,page:r.pageName,pageNamedBy:r.pageNamedBy,nodes:r.nodes.length,unnamed:Object.values(r.unnamed).reduce((l,d)=>l+d,0),characters:s.length,sent:!a,...a&&{reason:a}}),{index:r,context:s,sent:!a,...a&&{reason:a}}}catch(n){return this.emitError("UNKNOWN","Failed to read the host page","sdk",{cause:n,fatal:false}),null}}queuePageWork(e){let t=this.pageWork.then(e,e);return this.pageWork=t.catch(()=>{}),t}sendLiveContext(e,t){try{this.ws?.send(JSON.stringify({type:"live_context",context:e,update:t}));}catch(n){this.emitError("UNKNOWN","Failed to send live context","sdk",{cause:n,fatal:false});}}flushPendingContext(){if(this.pendingContext.length===0)return;let e=this.pendingContext;this.pendingContext=[];for(let t of e)this.sendLiveContext(t.context,t.update);}notify(e){try{if(this.mode==="player"){this.emitError("INVALID_MODE","notify() needs a session \u2014 player mode never opens a socket","sdk",{fatal:!1});return}let t=this.appEvents.validate(e);if(!t.ok){this.emitError("INVALID_INPUT",t.message,"sdk",{fatal:!1});return}let n=e.policy??"idle_only";if(!(this.ws?.readyState===WebSocket.OPEN)&&n!=="context_only"){u.event("app","Event dropped",{name:e.name,reason:"no_session"});return}let s=e.cooldownMs??5e3,o=this.appEvents.admit(e.name,s,Date.now());if(!o.ok){u.event("app","Event dropped",{name:e.name,reason:o.reason});return}if(n==="context_only"){this.addLiveContext({context:t.data?`${e.name}: ${t.data}`:e.name,update:!0});return}this.ws?.send(JSON.stringify({type:"app_event",name:e.name,data:t.data,policy:n,say:e.say})),u.event("app","Event sent",{name:e.name,policy:n});}catch(t){this.emitError("UNKNOWN","Unexpected error in notify()","sdk",{cause:t,fatal:false});}}registerAction(e){try{if(this.mode!=="call")return this.emitError("INVALID_MODE","registerAction() needs call mode \u2014 only a call can confirm an action","sdk",{fatal:!1}),Yt;let t=this.actions.register(e);return t.ok?t.unregister:(this.emitError("INVALID_INPUT",t.message,"sdk",{fatal:!1}),Yt)}catch(t){return this.emitError("UNKNOWN","Unexpected error in registerAction()","sdk",{cause:t,fatal:false}),Yt}}canDeclareActions(){if(this.ws?.readyState!==WebSocket.OPEN)return false;let e=this.capabilities;return e?e.actions?true:(this.actions.size>0&&!this.actionsGrantWarned&&(this.actionsGrantWarned=true,u.warn("Runtime","actions not granted for this avatar",{registered:this.actions.size})),false):false}sendActionsSet(e){try{return this.ws?.send(JSON.stringify({type:"actions_set",actions:e})),u.event("action","Actions declared",{names:e.map(t=>t.name)}),!0}catch(t){return u.warn("Runtime","failed to send actions_set",{err:t}),false}}async handleActionRun(e){let t=typeof e?.callId=="string"?e.callId:"",n=typeof e?.name=="string"?e.name:"";if(!t){u.warn("Runtime","action_run without a callId cannot be answered",{name:n});return}if(this.actionCallsSeen.has(t)){u.warn("Runtime","duplicate action_run ignored",{callId:t,name:n});return}this.actionCallsSeen.add(t);let r=this.ws,s=Date.now();u.event("action","Action run",{callId:t,name:n});let o=await this.runAction(t,n,e.args);if(u.event("action","Action result",{callId:t,name:n,ok:o.ok,ms:Date.now()-s}),r===null||r!==this.ws||r.readyState!==WebSocket.OPEN){u.warn("Runtime","action_result not sent: the session ended mid-run",{callId:t,name:n,ok:o.ok});return}try{r.send(JSON.stringify({type:"action_result",callId:t,...o}));}catch(a){u.warn("Runtime","failed to send action_result",{callId:t,err:a});}}async runAction(e,t,n){let r=this.actions.get(t);if(!r)return u.warn("Runtime","action_run for an unregistered action",{name:t}),{ok:false,error:$.unavailable};let s=Ti(r.declaration,n);if(!s)return u.warn("Runtime","action_run args do not match the declaration",{name:t,params:Object.keys(r.declaration.params)}),{ok:false,error:$.invalidArgs};let o=new AbortController,a=Promise.resolve().then(()=>r.handler(s,{callId:e,signal:o.signal})).then(d=>{let c=Mi(d);return c||(u.warn("Runtime","action handler returned no { ok } result",{name:t}),{ok:false,error:$.failed})},d=>(u.error("Runtime","action handler threw",{name:t,err:d}),{ok:false,error:$.failed})),l=new Promise(d=>{let c=setTimeout(()=>{o.abort(),u.warn("Runtime","action handler timed out",{name:t,timeoutMs:$i}),d({ok:false,error:$.timedOut});},$i);a.then(()=>clearTimeout(c));});return Promise.race([a,l])}getActionFlow(){return this.actionFlows.flow}sendActionUi(e,t,n){let r=this.ws;if(!r||r.readyState!==WebSocket.OPEN)return this.emitError("NOT_CONNECTED","sendActionUi() needs a live session","sdk",{fatal:false}),false;let s=this.actionFlows.isLive?this.actionFlows.flow:null,o;if(e==="input"){let a=s?.name??n??"",l=this.actions.get(a),d=l?ki(l.declaration,t??{}):{ok:false,message:`no registered action "${a}"`};if(!d.ok)return this.emitError("INVALID_INPUT",`sendActionUi(): ${d.message}`,"sdk",{fatal:false}),false;o={type:"action_ui",op:e,...s?{actionId:s.actionId}:{name:a},args:d.args};}else {if(!s)return this.emitError("INVALID_INPUT",`sendActionUi("${e}") needs an action in progress`,"sdk",{fatal:false}),false;o={type:"action_ui",op:e,actionId:s.actionId,revision:s.revision};}try{return r.send(JSON.stringify(o)),u.event("action","Action UI sent",{op:e,actionId:s?.actionId,params:t?Object.keys(t):[]}),!0}catch(a){return u.warn("Runtime","failed to send action_ui",{op:e,err:a}),false}}handleActionState(e){let t=Ri(e);if(!t){u.warn("Runtime","action_state ignored: not a flow");return}this.actionFlows.apply(t)&&(u.event("action","Action flow",{actionId:t.actionId,name:t.name,stage:t.stage,revision:t.revision,awaiting:t.awaiting?.kind??null}),this.events.emit("action-flow",t));}async handleActionCheck(e){let t=typeof e?.checkId=="string"?e.checkId:"",n=typeof e?.name=="string"?e.name:"",r=typeof e?.param=="string"?e.param:"";if(!t){u.warn("Runtime","action_check without a checkId cannot be answered",{name:n});return}let s=this.ws,o=e?.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},a=await Ii(this.actions.get(n)?.check,r,e?.value,o);if(u.event("action","Action check answered",{checkId:t,name:n,param:r,ok:a.ok,unverified:a.unverified===true}),s===null||s!==this.ws||s.readyState!==WebSocket.OPEN){u.warn("Runtime","action_check_result not sent: the session ended",{checkId:t});return}try{s.send(JSON.stringify({type:"action_check_result",checkId:t,...a}));}catch(l){u.warn("Runtime","failed to send action_check_result",{checkId:t,err:l});}}reportPerceptionOutcome(e,t,n){if(this.ws?.readyState!==WebSocket.OPEN){this.emitError("NOT_CONNECTED","reportPerceptionOutcome() needs a live session","sdk",{fatal:false});return}try{this.ws.send(JSON.stringify({type:"perception_status",turnId:t,outcome:e,...e==="granted"&&{hasHistory:!!n?.hasHistory,feed:n?.feed??"off"}}));}catch(r){this.emitError("UNKNOWN","Failed to send perception status","sdk",{cause:r,fatal:false});}}sendCameraState(e){if(this.ws?.readyState===WebSocket.OPEN&&!(e.access===void 0&&e.feed===void 0&&e.facing===void 0&&e.canFlip===void 0&&e.availableCameras===void 0)){try{this.ws.send(JSON.stringify({type:"camera_state",...e.access!==void 0&&{access:e.access},...e.feed!==void 0&&{feed:e.feed},...e.facing!==void 0&&{facing:e.facing},...e.canFlip!==void 0&&{canFlip:e.canFlip},...e.availableCameras!==void 0&&{availableCameras:e.availableCameras}}));}catch(t){u.warn("Runtime","failed to send camera_state",{err:t});}(e.feed==="off"||e.access&&e.access!=="granted")&&this.clearMood();}}get canReadMood(){return this.readsMood&&!!this.capabilities?.mood}get isMoodDetectionOn(){return this.moodDetectionOn}setMoodDetection(e){e!==this.moodDetectionOn&&(this.moodDetectionOn=e,this.moodLatest=null,this.events.emit("mood-detection",e),this.queueMoodState());}reportMood(e){!this.canReadMood||!this.moodDetectionOn||(this.moodLatest=e,this.queueMoodState());}resyncMoodSwitch(){this.moodLastSentKey="off",this.queueMoodState();}moodStateKey(){return this.moodDetectionOn?this.moodLatest?.state??"on":"off"}queueMoodState(){if(!this.canReadMood||this.moodTimer||this.moodStateKey()===this.moodLastSentKey)return;let e=Date.now()-this.moodLastSentAt;if(e>=Gi){this.sendMoodState();return}this.moodTimer=setTimeout(()=>{this.moodTimer=null,this.sendMoodState();},Gi-e);}sendMoodState(){let e=this.moodStateKey();if(e===this.moodLastSentKey||this.ws?.readyState!==WebSocket.OPEN)return;let t=this.moodDetectionOn?this.moodLatest:null;try{this.ws.send(JSON.stringify({type:"mood_state",enabled:this.moodDetectionOn,...t&&{label:t.state,confidence:t.confidence}})),this.moodLastSentKey=e,this.moodLastSentAt=Date.now(),u.debug("Runtime","mood_state sent",{key:e});}catch(n){u.warn("Runtime","failed to send mood_state",{err:n});}}clearMood(){this.moodLatest=null,this.moodLastSentKey!=="off"&&this.moodLastSentKey!==null&&(this.moodLastSentKey="on");}reportScreenStatus(e,t,n){if(u.event("screen","Share status",{outcome:e,turnId:t,surface:n?.surface??null,browser:n?.browser??null,reason:n?.reason??null}),this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"screen_status",turnId:t,outcome:e,...n?.surface&&{surface:n.surface},...n?.browser&&{browser:n.browser},...n?.reason&&{reason:n.reason}}));}catch(r){u.warn("Runtime","failed to send screen_status",{err:r});}}sendScreenState(e){if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"screen_state",feed:e.feed,...e.surface&&{surface:e.surface}}));}catch(t){u.warn("Runtime","failed to send screen_state",{err:t});}}sendScreenFrame(e){if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"screen_frame",format:"jpeg",width:e.width,height:e.height,frame:Ut(e.bytes)}));}catch(t){u.warn("Runtime","failed to send screen_frame",{err:t});}}reportCommandStatus(e,t,n,r){if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"command_status",command:e,turnId:t,outcome:n,...r&&{reason:r}}));}catch(s){u.warn("Runtime","failed to send command_status",{err:s});}}loadVadWeights(){return wn(Tn(),this.cache)}noteUserVoice(){this.events.emit("user-voice");}sendClientVadStatus(e,t){if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"client_vad_status",active:e,...t&&{reason:t}}));}catch(n){u.warn("Runtime","failed to send client_vad_status",{err:n});}}sendClientNetStatus(){if(this.ws?.readyState===WebSocket.OPEN){try{this.ws.send(JSON.stringify({type:"client_net_status",micMuted:this.micMuted,...this.downlinkVerdict&&{downlink:this.downlinkVerdict}})),this.downlinkVerdict?.state==="ok"&&(this.downlinkVerdict=null);}catch(e){u.warn("Runtime","failed to send client_net_status",{err:e});}this.netStatusLastSentAt=Date.now();}}queueClientNetStatus(){if(this.netStatusTimer)return;let e=Date.now()-this.netStatusLastSentAt;if(e>=Vi){this.sendClientNetStatus();return}this.netStatusTimer=setTimeout(()=>{this.netStatusTimer=null,this.sendClientNetStatus();},Vi-e);}sendVisionFrames(e,t){if(this.ws?.readyState!==WebSocket.OPEN){this.emitError("NOT_CONNECTED","sendVisionFrames() needs a live session","sdk",{fatal:false});return}if(!e.length){u.warn("Runtime","vision frames requested but buffer is empty",{turnId:t});return}try{let n=e.map(r=>Ut(r));this.ws.send(JSON.stringify({type:"vision_query",turnId:t,format:"jpeg",frames:n}));}catch(n){this.emitError("UNKNOWN","Failed to send vision frames","sdk",{cause:n,fatal:false});}}play(e){if(this.mode!=="player"){this.emitError("INVALID_MODE","play() can only be used in player mode","sdk",{fatal:false});return}this.jobQueue.push({...e,sessionId:this.sessionId,turnId:this.turnId,jobId:++this.jobCounter,chunkOffset:0}),!(this.processing||this.playerLeadInTimer)&&(this.setTalkingArmed(true),this.playerLeadInTimer=setTimeout(()=>{this.playerLeadInTimer=null,this.setTalkingArmed(false),this.processQueue();},yt));}setTalkingArmed(e){this.talkingArmed!==e&&(this.talkingArmed=e,this.events.emit("talking-armed",e));}clearPlayerLeadIn(){this.playerLeadInTimer&&(clearTimeout(this.playerLeadInTimer),this.playerLeadInTimer=null),this.setTalkingArmed(false);}sendPcmChunk(e){if(!this.micMuted&&!this.noticeReceived&&!(this.ws?.readyState!==WebSocket.OPEN||!this.isConnected)){if(!this.pushToTalk){this.ws.send(e);return}for(let t of this.pushToTalk.gate(e))this.ws.send(t);}}openUserTurn(){(this.turnPhase==="speaking"||this.turnPhase==="greeting")&&this.interrupt({notifyServer:true,reason:"push_to_talk"}),this.sendClientTurnSignal("client_turn_start");}closeUserTurn(){this.sendClientTurnSignal("client_turn_end");}sendClientTurnSignal(e){if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:e,turnId:this.turnId}));}catch(t){u.warn("Runtime",`failed to send ${e}`,{err:t});}}interrupt(e){u.event("bargein","interrupt",{reason:e?.reason??"api",turnId:this.turnId,turnPhase:this.turnPhase});let t=this.turnId;this.sessionId++,this.turnId++,e?.notifyServer&&this.sendClientInterruptToServer(t,e.reason),this.resetSpeechPipeline(),this.setResponseSlow(false),this.events.emit("interrupt"),this.sessionPhase==="active"&&this.setTurnPhase("listening");}setHeardSpeechProvider(e){this.heardSpeech=e;}readHeardSpeech(){try{let e=this.heardSpeech?.()?.trim();return e?e.slice(0,Uo):void 0}catch{return}}sendClientInterruptToServer(e,t){if(this.ws&&this.ws.readyState===WebSocket.OPEN){let n=this.readHeardSpeech();try{this.ws.send(JSON.stringify({type:"client_interrupt",turnId:e,...t&&{reason:t},...n&&{heard:n}}));}catch{}}}stopSpeaking(){this.sessionPhase==="active"&&(u.event("Runtime","User stopped the avatar"),this.interrupt({notifyServer:true,reason:"user_cancel"}));}cancelSpeech(){u.event("bargein","server_cancel_speech",{turnId:this.turnId,turnPhase:this.turnPhase}),this.resetSpeechPipeline(),this.events.emit("speech-cancelled"),this.sessionPhase==="active"&&this.setTurnPhase("listening");}setResponseSlow(e){this.responseSlow!==e&&(this.responseSlow=e,this.events.emit("avatar_slow_response",e));}armFirstChunk(){this.firstChunkPending=true;}resetSpeechPipeline(){this.utteranceBuffer.flushTimer&&clearTimeout(this.utteranceBuffer.flushTimer),this.utteranceBuffer={audio:[],alignments:[],displayAlignments:[],visemes:[],flushTimer:null},this.jobQueue=[],this.processing=false,this.turnOpen=false,this.activeStream=null,this.clearPlayerLeadIn(),this.armFirstChunk(),this.sendAvatarSpeakingSignalToServer(false),this.transcript?.finalizeAvatar();}grantedPageSurface(e,t,n){let r=this.capabilities?.page;return !r||!n(r)?(this.reportCommandStatus(e,this.commandTurnId(t),"unsupported","this avatar is not allowed to do that to the page"),null):this.pageSurface?this.pageSurface:(this.reportCommandStatus(e,this.commandTurnId(t),"unsupported","no page surface on this platform"),null)}runPageCommand(e,t,n,r){let s=this.grantedPageSurface(e,t,n);if(!s)return;let o=this.commandTurnId(t);this.queuePageWork(()=>r(s,o)).catch(a=>{u.warn("Runtime","page command failed",{command:e,error:String(a)}),this.reportCommandStatus(e,o,"failed",Ho);});}scheduleReadAfterAction(){this.actionRereadTimer&&clearTimeout(this.actionRereadTimer),this.actionRereadTimer=setTimeout(()=>{this.actionRereadTimer=null,this.readPage();},xo);}commandTurnId(e){return typeof e?.turnId=="number"&&Number.isFinite(e.turnId)?e.turnId:this.turnId}handleCommand(e){let t=typeof e?.intent=="string"?e.intent:null;if(!t){u.warn("Runtime","command message missing intent",{msg:e});return}this.setResponseSlow(false);let n=this.commandHandlers[t];if(!n){u.warn("Runtime","unknown command intent",{intent:t}),this.reportCommandStatus(t,this.commandTurnId(e),"unsupported","unknown command");return}n(e);}dispose(e="SDK Disposed"){this.lifecycle++,this.cancelReconnect(),this.loadInFlight=null,this.teardownSession(4003,e,false),this.setSessionPhase("idle"),this.setPaintPhase("none");}setAvatarId(e){let t=e||"default";return t===this.avatarId?false:(u.event("Runtime","Avatar changed",{from:this.avatarId,to:t}),this.dispose("Avatar changed"),this.avatarId=t,this.startInvoked=false,this.load(),true)}stale(e){return e!==this.lifecycle}staleSocket(e,t){return this.stale(e)?(this.ws===t&&(this.ws=null),t?.close(4003,"SDK Disposed"),true):false}destroy(){this.dispose(),this.events.removeAll();}getPaintPhase(){return this.paintPhase}getSessionPhase(){return this.sessionPhase}getMode(){return this.mode}getTurnPhase(){return this.turnPhase}getTalkingArmed(){return this.talkingArmed}getSessionId(){return this.sessionId}on(e,t){return this.events.on(e,t)}markRiveReady(){this.riveReady||(this.riveReady=true,this.events.emit("avatar-ready"),this.releaseGreetingForPaint("rive-ready"),this.utteranceBuffer.audio.length&&(this.utteranceBuffer.flushTimer&&(clearTimeout(this.utteranceBuffer.flushTimer),this.utteranceBuffer.flushTimer=null),this.flushUtterance()));}notifyPlaybackEnded(){this.processing&&(this.processing=false,this.activeStream=null,this.armFirstChunk(),this.processQueue());}notifyAvatarLoadError(e){this.setPaintPhase("failed"),this.emitError("AVATAR_LOAD_FAILED","Failed to load avatar","sdk",{cause:e});}getAvatarConfig(){return this.serverReady?this.avatarConfig:null}getAvailableActions(){return Object.keys(this.avatarConfig?.rive?.gestures??{})}triggerAction(e){e&&this.events.emit("gesture",e);}avatarClicked(){if(this.turnPhase==="speaking"||this.turnPhase==="greeting")return;if(this.sessionPhase==="active"){try{this.ws?.send(JSON.stringify({type:"avatar_click"}));}catch{}return}let e=Date.now(),t=Gn(this.avatarConfig?.performance?.playful?.gestures,this.playful.last,e,this.playful.busyUntilMs);t&&(this.playful={last:t.trigger,busyUntilMs:e+t.ms},this.events.emit("gesture",t.trigger));}setSessionPhase(e){this.sessionPhase!==e&&(this.sessionPhase=e,u.debug("Runtime","Session phase",{next:e}),this.events.emit("session-phase",e),e!=="active"&&this.turnPhase!=="idle"&&this.setTurnPhase("idle"));}setPaintPhase(e){this.paintPhase!==e&&(this.paintPhase=e,u.debug("Runtime","Paint phase",{next:e}),this.events.emit("paint-phase",e),e==="painted"&&this.markTonePainted(),e==="failed"&&this.stopConnectTone("paint-failed"),e==="failed"&&this.releaseGreetingForPaint("paint-failed"));}setTurnPhase(e){this.turnPhase!==e&&(this.turnPhase=e,u.debug("Runtime","Turn phase",{next:e}),this.events.emit("turn-phase",e));}startConnectTone(){!this.connectTone?.enabled||this.connectTonePlaying||this.mode!=="player"&&(this.tonePainted=this.paintPhase==="painted",this.toneSessionLive=this.sessionPhase==="active",!(this.tonePainted&&this.toneSessionLive)&&(this.connectTonePlaying=true,this.connectToneStartedAt=Date.now(),u.event("ConnectTone","Ringback start",{paintedOnEntry:this.tonePainted,liveOnEntry:this.toneSessionLive}),this.events.emit("connect-tone","start",this.resolvedConnectTone()),this.connectToneTimer=setTimeout(()=>{u.warn("ConnectTone","Ringback hit its ceiling \u2014 stopping"),this.stopConnectTone("ceiling");},kn)));}stopConnectTone(e){this.connectToneTimer&&(clearTimeout(this.connectToneTimer),this.connectToneTimer=null),this.connectTonePlaying&&(this.connectTonePlaying=false,u.event("ConnectTone","Ringback stop",{reason:e,audibleMs:this.connectToneStartedAt?Date.now()-this.connectToneStartedAt:null}),this.connectToneStartedAt=null,this.events.emit("connect-tone","stop"));}resolvedConnectTone(){return {...At,...this.connectTone}}getPendingConnectTone(){return this.connectTonePlaying?this.resolvedConnectTone():null}markTonePainted(){this.tonePainted=true,this.toneSessionLive&&this.stopConnectTone("painted+live");}markToneSessionLive(){this.toneSessionLive=true,this.tonePainted&&this.stopConnectTone("painted+live");}settleGreeting(e){this.greetingDecided||(this.greetingDecided=true,this.greetingDecisionTimer&&(clearTimeout(this.greetingDecisionTimer),this.greetingDecisionTimer=null),u.event("Greeting","Decision settled",{outcome:e}));}armGreetingBackstop(){this.greetingDecided||this.greetingDecisionTimer||(this.greetingDecisionTimer=setTimeout(()=>{this.greetingDecisionTimer=null,u.warn("Greeting","No greeting decision from server \u2014 listening"),this.settleGreeting("timeout"),this.greetingAwaitingPlayback=false,this.sessionPhase==="active"&&this.enterListening();},Rn));}handleGreetingPayload(e,t){if(!t?.audio_base64){this.settleGreeting("empty-payload"),this.resolveGreetingPlayback();return}let n={greetingId:e,audioChunks:[t.audio_base64],alignments:[t.normalized_alignment??t.alignment??null],...t.visemes&&{visemes:[Ne(t.visemes)]},cachedAt:Date.now()};this.greetingEntry=n,this.sentGreetingId=e,this.cache.setCachedGreeting(this.greetingKey,n).catch(()=>{}),this.settleGreeting("synthesized"),this.resolveGreetingPlayback();}resolveGreetingPlayback(){this.greetingAwaitingPlayback&&(this.greetingAwaitingPlayback=false,this.sessionPhase==="active"&&(this.playGreeting()||this.enterListening()));}playGreeting(){if(this.greetingPlayed)return false;let e=this.greetingEntry;if(!e?.audioChunks.length)return false;this.greetingPlayed=true,u.event("Greeting","Playing greeting",{greetingId:e.greetingId}),this.setTurnPhase("greeting");let t={audioChunks:e.audioChunks,alignments:e.alignments,...e.visemes&&{visemes:e.visemes},sessionId:this.sessionId,turnId:this.turnId,isGreeting:true,jobId:++this.jobCounter,chunkOffset:0},n=()=>{this.greetingDelayTimer=setTimeout(()=>{this.greetingDelayTimer=null,t.sessionId===this.sessionId&&this.sessionPhase==="active"&&this.enqueueJob(t);},bt);},r=()=>{this.greetingWaitsForPaint()?this.holdGreetingForPaint(n):n();};return this.greetingWaitsForMic()?this.holdGreetingForMic(r):r(),true}reportMicPipelineSettled(){this.micPipelineSettled=true,this.releaseGreetingForMic("settled");}greetingWaitsForMic(){return this.reportsMicPipeline&&!!this.micStream&&!this.micPipelineSettled}holdGreetingForMic(e){this.greetingAwaitingMic=e,this.greetingMicTimer=setTimeout(()=>this.releaseGreetingForMic("timeout"),On),u.event("Greeting","Held for mic pipeline");}releaseGreetingForMic(e){let t=this.greetingAwaitingMic;this.clearGreetingMicHold(),t&&(u.event("Greeting","Released after mic hold",{reason:e}),t());}clearGreetingMicHold(){this.greetingAwaitingMic=null,this.greetingMicTimer&&(clearTimeout(this.greetingMicTimer),this.greetingMicTimer=null);}greetingWaitsForPaint(){return this.environment==="meeting"&&!this.riveReady&&this.paintPhase!=="failed"}holdGreetingForPaint(e){this.greetingAwaitingPaint=e,this.greetingPaintTimer=setTimeout(()=>this.releaseGreetingForPaint("timeout"),Cn),u.event("Greeting","Held for first paint");}releaseGreetingForPaint(e){let t=this.greetingAwaitingPaint;this.clearGreetingPaintHold(),t&&(u.event("Greeting","Released after paint hold",{reason:e}),t());}clearGreetingPaintHold(){this.greetingAwaitingPaint=null,this.greetingPaintTimer&&(clearTimeout(this.greetingPaintTimer),this.greetingPaintTimer=null);}enterListening(){this.setTurnPhase("listening");}enterThinking(){this.setTurnPhase("thinking"),this.events.emit("avatar_thinking");}holdsSpeech(){return this.processing||this.jobQueue.length>0||this.utteranceBuffer.audio.length>0}enqueueJob(e){this.jobQueue.push(e),this.processQueue();}processQueue(){if(this.processing)return;let e=this.jobQueue.shift();if(!e){this.transcript?.finalizeAvatar(),this.turnOpen?this.enterThinking():this.enterListening(),this.sendAvatarSpeakingSignalToServer(false);return}if(e.sessionId!==this.sessionId){this.processQueue();return}this.processing=true,this.setTurnPhase("speaking"),this.emitSpeak(e),this.sendAvatarSpeakingSignalToServer(true);}emitSpeak(e){this.setResponseSlow(false),this.rollScriptTail(e),this.transcript?.applyAvatarSpeech(e),this.events.emit("speak",e);}rollScriptTail(e){let t=this.scriptTail;t.jobId!==e.jobId&&(t.jobId=e.jobId,t.upto=0,t.text="");let n=e.alignments??[],r=e.chunkOffset+n.length;if(r<=t.upto)return;let s=[];for(let o=Math.max(0,t.upto-e.chunkOffset);o<n.length;o++){let a=n[o];if(!a)continue;let l=oe(a);l&&s.push(l);}t.upto=r,t.text=[t.text,...s].join(" ").slice(-200);}getScriptTail(){return this.scriptTail.text}applyAgc(e){if(this.agcEnabled===e||typeof this.micStream?.getAudioTracks!="function")return;let t=this.micStream.getAudioTracks()[0];t&&(this.agcEnabled=e,u.event("mic","agc",{enabled:e}),t.applyConstraints({autoGainControl:e}).catch(n=>u.warn("Runtime","AGC toggle rejected",{enabled:e,error:n})));}async handleServerMessage(e){if(typeof e.data!="string")return;let t=Date.now(),n;try{n=JSON.parse(e.data);}catch{return}let r=this.transit.note(n.sentAt,t);switch(this.downlinkWatchdog.noteMessage(n.seq,t,n.type===Oi),n.type){case "avatar_config":{let s=n.config;if(!s?.rive&&!this.serverReady){this.emitError("AVATAR_LOAD_FAILED","Server config had no rive configuration","server"),this.rejectInitAck("Server config missing rive configuration");return}if(this.serverReady)await this.repaintFromPayload(s,this.lifecycle);else {let o=s.rivUrl?await this.fetchRivBytes(s.rivUrl):this.pendingRivBytes;if(!o){this.emitError("AVATAR_LOAD_FAILED","No rivUrl in avatar_config and no cache","server"),this.rejectInitAck("no riv bytes");return}await this.applyRenderPayload(s,o,this.lifecycle);}this.resolveInitAck();break}case "greeting_current":{u.event("Greeting","Server confirmed cached greeting",{greetingId:n.greetingId}),this.settleGreeting("cache-hit"),this.resolveGreetingPlayback();break}case "greeting":{u.event("Greeting","Received greeting audio",{greetingId:n.greetingId}),this.handleGreetingPayload(n.greetingId,n.job);break}case "greeting_unavailable":{u.info("Greeting","Server sent no greeting",{reason:n.reason??null}),this.settleGreeting(`unavailable:${n.reason??"unspecified"}`),this.resolveGreetingPlayback();break}case "notice_only":{this.noticeOnly=true,u.info("Runtime","notice_only \u2014 suppressing mic/greeting",{kind:n.kind}),this.serverReady||await this.paintForNotice(),this.setSessionPhase("idle"),this.resolveInitAck();break}case "resume_state":{if(typeof n.token!="string")break;this.isConnected?this.onResumeState?.(n.token):this.heldResumeToken=n.token;break}case "session_started":{this.resumeKept=void 0,this.heldResumeToken=null,this.sessionCapabilities=Ui(n.capabilities);let{camera:s,screen:o,micMute:a,endCall:l,actions:d,page:c}=this.sessionCapabilities;u.event("session","Capabilities resolved",{camera:s,screen:o,micMute:a,endCall:l,actions:d,pageRead:c.read,pageScroll:c.scroll,pageNavigate:c.navigate,pageClick:c.click}),this.resyncMoodSwitch(),this.flushPendingContext(),this.noticeOnly||(this.firstPage=this.sendFirstPage()),this.serverReady?this.startSession():(u.info("Runtime","session_started before riv ready \u2014 deferring"),this.pendingSession=true);break}case "error":case "closed":{let s=n.type==="error",o=s?"SERVER_ERROR":"SERVER_CLOSE_REQUESTED",a=n.message||(s?"Server error":"Server requested closure");this.serverInitiatedReason={code:o,message:a},this.emitError(o,a,"server"),this.rejectInitAck(a);return}case "usage_limit_reached":case "avatar_not_allowed":{let s=n.type==="usage_limit_reached",o=n.message||(s?"Usage limit reached":"This avatar is not in your active slots, and your active slots are full");this.serverInitiatedReason={code:n.type,message:o},this.handleNotice({kind:n.kind??"plan",action:n.action,message:o});return}case "brain_error":{let s=n.message||"The assistant failed to respond";this.emitError("BRAIN_ERROR",s,"server",{fatal:false}),this.turnOpen=false,this.turnPhase==="thinking"&&this.enterListening();return}case "stream_health":{let s=n.service,o=n.state;if(!this.isHealthService(s)||!this.isHealthState(o)){u.warn("Runtime","stream_health: unknown service/state",{service:n.service,state:n.state});return}u.event("Runtime","stream_health",{service:s,state:o,code:n.code??null,detail:n.detail??null}),this.health[s]=o,this.emitHealth(s,n.code);return}case "tts_alignment":{if(n.turnId!==this.turnId)return;let s=n.audio_base64??n.audio_base64_string??"";if(!s)return;this.firstAudioAt===null&&(this.firstAudioAt=t,this.firstAudioLagMs=r);let o=this.mode==="call"&&!this.noticeOnly?Le(n.normalized_alignment??n.alignment):n.normalized_alignment??null;u.debug("TTS","Processed alignment",o);let a=n.display_alignment?Le(n.display_alignment):null;if(this.utteranceBuffer.audio.push(s),this.utteranceBuffer.alignments.push(o),this.utteranceBuffer.displayAlignments.push(a),this.utteranceBuffer.visemes.push(Ne(n.visemes)),!this.utteranceBuffer.flushTimer){let l=this.firstChunkPending?0:Po;this.firstChunkPending=false,this.utteranceBuffer.flushTimer=setTimeout(()=>{this.flushUtterance();},l);}return}case "user_transcript":{u.debug("Transcript","user_transcript received",{text:n.text??"",isFinal:!!n.isFinal,turnId:n.turnId??null,event:n.event??null,msSinceMicStart:this.micStartedAt===null?null:Date.now()-this.micStartedAt,micMuted:this.micMuted,turnPhase:this.turnPhase});let s=this.turnPhase==="speaking"&&pi(n.text??"",this.getScriptTail());s||this.transcript?.applyUserTranscript({text:n.text??"",isFinal:!!n.isFinal,turnId:n.turnId??this.turnId}),n.text&&this.events.emit("user-partial",n.text,!!n.isFinal),n.text&&!s&&!this.pageReadThisUtterance&&this.capabilities?.page.read&&(this.pageReadThisUtterance=true,this.readPage());return}case "user_speaking":{this.events.emit("user-speaking");return}case "user_stopped_speaking":{this.deliveryLagMs=r,this.pageReadThisUtterance=false,this.userStoppedAt=t-(r??0),this.speakReportedForStop=false,this.firstAudioAt=null,this.firstAudioLagMs=null;return}case "avatar_thinking":{if(n.settles===true&&(this.turnOpen=true,this.holdsSpeech()))return;this.enterThinking();return}case "turn_settled":{this.turnOpen=false,this.turnPhase==="thinking"&&n.audioPending!==true&&!this.holdsSpeech()&&this.enterListening();return}case "avatar_slow_response":{this.setResponseSlow(true);return}case "avatar_speech_starting":{this.utteranceBuffer.audio.length&&(this.utteranceBuffer.flushTimer&&(clearTimeout(this.utteranceBuffer.flushTimer),this.utteranceBuffer.flushTimer=null),this.flushUtterance()),this.transcript?.finalizeAvatar(),this.armFirstChunk(),this.events.emit("avatar_speech_starting");return}case "interrupt":{u.event("bargein","server_interrupt",{turnId:this.turnId,turnPhase:this.turnPhase}),this.interrupt({reason:"server"});return}case "command":{this.handleCommand(n);return}case "tour":{let s=Array.isArray(n.steps)?n.steps:null;this.pendingTours.get(n.requestId)?.(s);return}case "tour_unavailable":{u.warn("Runtime","Server could not write a tour",{reason:n.reason}),this.pendingTours.get(n.requestId)?.(null);return}case "action_run":{this.handleActionRun(n);return}case "action_state":{this.handleActionState(n);return}case "action_check":{this.handleActionCheck(n);return}case "gesture":{if(typeof n.name=="string"){let s=typeof n.atMs=="number"&&Number.isFinite(n.atMs)?n.atMs:void 0,o=typeof n.speechless=="boolean"?n.speechless:void 0;this.events.emit("gesture",n.name,s,o);}return}case "beep":{this.events.emit("beep",typeof n.atMs=="number"&&Number.isFinite(n.atMs)?n.atMs:void 0,typeof n.speechless=="boolean"?n.speechless:void 0);return}}}teardownSession(e,t,n=true){this.utteranceBuffer.flushTimer&&clearTimeout(this.utteranceBuffer.flushTimer),this.utteranceBuffer={audio:[],alignments:[],displayAlignments:[],visemes:[],flushTimer:null},this.turnOpen=false,this.stopConnectTone("session-teardown"),this.toneSessionLive=false,this.greetingDelayTimer&&(clearTimeout(this.greetingDelayTimer),this.greetingDelayTimer=null),this.clearGreetingPaintHold(),this.clearGreetingMicHold(),this.clearPlayerLeadIn(),this.greetingDecisionTimer&&(clearTimeout(this.greetingDecisionTimer),this.greetingDecisionTimer=null),this.greetingDecided=false,this.greetingAwaitingPlayback=false,this.greetingPlayed=false,this.sessionCapabilities=null,this.pageGeneration=0,this.lastPageContext=null,this.firstPage=null,this.pageSession++;for(let s of [...this.pendingTours.values()])s(null);this.actionRereadTimer&&(clearTimeout(this.actionRereadTimer),this.actionRereadTimer=null),this.actions.resetSession(),this.actionCallsSeen.clear(),this.actionFlows.flow&&(this.actionFlows.clear(),this.events.emit("action-flow",null)),this.actionsGrantWarned=false,this.armFirstChunk(),this.setResponseSlow(false),this.micMuted&&(this.micMuted=false,this.events.emit("mic-muted",false)),this.speakerMuted&&(this.speakerMuted=false,this.events.emit("speaker-muted",false)),this.sendAvatarSpeakingSignalToServer(false),this.isConnected&&(this.isConnected=false,this.events.emit("connection-status",false)),this.downlinkWatchdog.reset(),this.resetHealth(),this.heldResumeToken=null,this.lastContextSnapshot&&(this.pendingContext=[{context:this.lastContextSnapshot}]),this.netStatusTimer&&(clearTimeout(this.netStatusTimer),this.netStatusTimer=null),this.netStatusLastSentAt=0,this.moodTimer&&(clearTimeout(this.moodTimer),this.moodTimer=null),this.moodLatest=null,this.moodLastSentKey=null,this.moodLastSentAt=0,this.intentionalClose=false,this.serverInitiatedReason=null;let r=this.ws;this.ws=null,r?.close(e,t),this.agcRestoreTimer!==null&&(clearTimeout(this.agcRestoreTimer),this.agcRestoreTimer=null),this.micStream&&(this.micStream.getTracks().forEach(s=>s.stop()),this.micStream=null,this.micStartedAt=null,this.events.emit("mic-stop")),this.pushToTalk?.reset(),this.jobQueue=[],this.processing=false,this.activeStream=null,this.turnId=0,this.sessionId=0,this.userStoppedAt=null,this.speakReportedForStop=false,this.deliveryLagMs=null,this.firstAudioAt=null,this.firstAudioLagMs=null,this.transit.reset(),this.pendingSession=false,this.rejectInitAck("Runtime stopped"),this.transcript?.reset(),this.scriptTail={jobId:-1,upto:0,text:""},this.noticeReceived=false,this.noticeOnly=false,this.visualState="normal",n||(this.serverReady=false,this.rivSrc&&(this.urlResolver.revokeSrc(this.rivSrc),this.rivSrc=null),this.pendingRivBytes=null,this.riveReady=false,this.avatarConfig=null,this.cachedConfigVersion=void 0,this.watermark=false);}sendAvatarSpeakingSignalToServer(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"avatar_speaking",value:e}));}catch{}}resolveInitAck(){this.initAckResolve?.(),this.initAckResolve=null,this.initAckReject=null,this.initAckPromise=null;}rejectInitAck(e){this.initAckReject?.(new Error(e)),this.initAckResolve=null,this.initAckReject=null,this.initAckPromise=null;}emitError(e,t,n,r){let s=r?.fatal??true,o={code:e,message:t,source:n,cause:r?.cause,fatal:s,retryable:s&&e!=="MIC_PERMISSION_DENIED"&&e!=="DOMAIN_NOT_ALLOWED"};if(this.lastEmittedError=o,u.error("Runtime",`${n.toUpperCase()} ERROR: ${t}`,{code:e,fatal:s}),this.events.emit("error",o),!s)return;let a=n==="server"&&this.initAckReject!==null;this.failSession(o),a||this.scheduleReconnect(o);}reportAudioBlocked(e){this.emitError("UNKNOWN",`Audio ${e} is blocked: the page has not had a user gesture`,"sdk",{fatal:false});}classifyClose(e){let t=e?.reason?.trim();switch(e?.code){case 4008:return {code:"SESSION_IDLE_TIMEOUT",message:t||"Session disconnected due to inactivity"};case 1008:return qt(void 0,t)?{code:"DOMAIN_NOT_ALLOWED",message:"This page's domain is not in the deployment's authorised domains"}:{code:"SERVER_CLOSE_REQUESTED",message:t||"The service ended the session"};case 1009:return {code:"SERVER_CLOSE_REQUESTED",message:t||"Message too big"};case 1011:return {code:"SERVER_ERROR",message:"The service ended the session after a component failure"};default:return {code:"CONNECTION_FAILED",message:t?`Connection to the avatar service closed: ${t}`:"Connection to the avatar service was lost unexpectedly"}}}failSession(e){if(e.code==="SESSION_IDLE_TIMEOUT"){this.stop({intentionalClose:true,code:4002,reason:"Idle timeout reached"});return}if(e.code==="AVATAR_LOAD_FAILED"||e.code==="DOMAIN_NOT_ALLOWED"||e.code==="MIC_PERMISSION_DENIED"||e.source==="sdk"){this.stop({intentionalClose:true,code:4004,reason:Ci(e)});return}this.stop({intentionalClose:false,code:4e3,reason:e.message});}setVisualState(e){this.visualState!==e&&(this.visualState=e,u.event("Runtime","Visual state",{state:e}),this.events.emit("visual",e));}applyDownlinkVerdict(e){if(this.noticeReceived)return;let t=e.state==="degraded"?"degraded":"ok";this.downlinkVerdict=e,this.downlinkScope=e.scope,u.event("Runtime","downlink_health",{...e}),this.health.downlink!==t&&(this.health.downlink=t,this.emitHealth("downlink","DOWNLINK_SLOW")),this.queueClientNetStatus();}transcriptPathDegraded(){return this.health.downlink!=="ok"&&this.downlinkScope!=="device"||this.health.ingest!=="ok"||this.health.stt!=="ok"}isHealthService(e){return e==="ingest"||e==="stt"||e==="llm"||e==="tts"}isHealthState(e){return e==="ok"||e==="degraded"||e==="failed"}resolveHealthConcern(e,t){let n=o=>o===e?t:void 0;if(this.health.ingest!=="ok")return {scope:"network",service:"ingest",state:this.health.ingest,code:n("ingest")};if(this.health.downlink!=="ok")return {scope:this.downlinkScope,service:"downlink",state:this.health.downlink,code:n("downlink")};let r=["stt","llm","tts"],s=null;for(let o of r){let a=this.health[o];if(a==="failed"){s=o;break}a==="degraded"&&s===null&&(s=o);}return s===null?null:{scope:"service",service:s,state:this.health[s],code:n(s)}}emitHealth(e,t){let n={services:{...this.health},concern:this.resolveHealthConcern(e,t)};this.events.emit("health",n);}resetHealth(){let e=Object.values(this.health).some(t=>t!=="ok");this.health={ingest:"ok",stt:"ok",llm:"ok",tts:"ok",downlink:"ok"},this.downlinkScope="network",this.downlinkVerdict=null,e&&this.emitHealth();}handleNotice(e){this.noticeReceived=true,this.downlinkWatchdog.stop(),this.downlinkVerdict=null,this.health.downlink!=="ok"&&(this.health.downlink="ok",this.emitHealth()),u.event("Runtime","Session notice",{...e}),this.stopConnectTone("notice"),this.events.emit("notice",e),this.setVisualState("expired");}flushUtterance(){let e=this.utteranceBuffer;if(e.flushTimer=null,!e.audio.length)return;if(!this.riveReady){u.debug("Runtime","Holding speech \u2014 renderer not ready",{chunks:e.audio.length});return}(!this.activeStream||this.activeStream.turnId!==this.turnId)&&(this.activeStream={sessionId:this.sessionId,turnId:this.turnId,jobId:++this.jobCounter,emittedChunks:0});let t={audioChunks:e.audio,alignments:e.alignments,displayAlignments:e.displayAlignments,visemes:e.visemes,sessionId:this.activeStream.sessionId,turnId:this.activeStream.turnId,jobId:this.activeStream.jobId,chunkOffset:this.activeStream.emittedChunks};this.activeStream.emittedChunks+=e.audio.length,e.audio=[],e.alignments=[],e.displayAlignments=[],e.visemes=[],this.processing=true,this.setTurnPhase("speaking"),this.emitSpeak(t),this.sendAvatarSpeakingSignalToServer(true),this.reportAvatarStartedSpeaking();}reportAvatarStartedSpeaking(){if(this.speakReportedForStop)return;this.speakReportedForStop=true;let e=Date.now(),t=this.userStoppedAt!==null?e-this.userStoppedAt:null,n=this.firstAudioAt!==null?e-this.firstAudioAt:null;if(this.ws?.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify({type:"avatar_started_speaking",turnId:this.turnId,clientLatencyMs:t,deliveryLagMs:this.firstAudioLagMs,stopNoticeLagMs:this.deliveryLagMs,clientRenderMs:n}));}catch{}}};var $o=1e3,ji="I'm right here, so let me know if you have any questions.",Xo=80,Qt=i=>{if(typeof i!="string")return;let e=i.trim();return e&&e.length<=Xo?e:void 0},Ko=["above","below","left","right"],Xi=(i,e)=>{let t=typeof e=="string"?{target:e}:e,n=Qt(t?.target);if(!n)return;let r=Ko.find(s=>s===t?.from);return r?{kind:i,target:n,from:r}:{kind:i,target:n}},jo=i=>{let e=Xi("point",i.point);if(e)return e;let t=Xi("go",i.go);if(t)return t;if(typeof i.spot!="string")return;let n=he(i.spot);return n?.kind==="spot"?{kind:"spot",spot:n.spot}:void 0},qo=i=>{let e=typeof i=="string"?{target:i}:i,t=Qt(e?.target);if(t)return {target:t,strong:e?.strong===true}},Ki=i=>i.split(/\s+/).filter(Boolean),zo=(i,e=ji)=>{let t=[],n=[];for(let s of i??[]){let o=Ki(typeof s?.say=="string"?s.say:"");if(!o.length)continue;let a=typeof s.gesture=="string"&&s.gesture.trim()?s.gesture.trim():void 0;n.push({wordIndex:t.length,move:jo(s),highlight:qo(s.highlight),scroll:Qt(s.scroll),gesture:a}),t.push(...o);}if(!n.length)return {text:"",words:[],steps:[]};n[0].move||(n[0].move={kind:"spot",spot:"center"});let r=e===false?[]:Ki(e);return r.length&&(n.push({wordIndex:t.length,move:{kind:"home"},scrollTop:true}),t.push(...r)),{text:t.join(" "),words:t,steps:n}},Yo=i=>{let e=JSON.stringify(i.steps)+i.text,t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return (t>>>0).toString(36)};var qi=i=>i.toLowerCase().normalize("NFKC").replace(/[^\p{L}\p{N}]+/gu,""),Jo=(i,e,t)=>{let n="";for(let r=1;r<=3&&t-r>=0;r++){if(n=e[t-r]+n,n===i)return r;if(!i.endsWith(n))return 0}return 0},Qo=(i,e)=>{let t=i.map(qi),n=e.map(h=>qi(h.text)),r=t.length+1,s=n.length+1,o=new Int32Array(r*s),a=(h,g)=>t[h-1]?Jo(t[h-1],n,g):0;for(let h=1;h<r;h++)for(let g=1;g<s;g++){let S=Math.max(o[(h-1)*s+g],o[h*s+g-1]),E=a(h,g);E&&(S=Math.max(S,o[(h-1)*s+g-E]+1)),o[h*s+g]=S;}let l=t.map(()=>null),d=r-1,c=s-1;for(;d>0&&c>0;){let h=o[d*s+c];if(h===o[(d-1)*s+c])d--;else if(h===o[d*s+c-1])c--;else {let g=a(d,c);l[d-1]={from:c-g,to:c},d--,c-=g;}}let p=t.map((h,g)=>{let S=l[g];return !S||h.length<=3&&!(l[g-1]?.to===S.from||l[g+1]?.from===S.to)?null:e[S.from].start}),m=null;for(let h=t.length-1;h>=0;h--)p[h]!==null?m=p[h]:m!==null&&(p[h]=m);return p};var Zt=class{constructor(){this.jobId=null;this.consumed=0;this.chars=[];this.starts=[];this.ends=[];this.cachedWords=[];}add(e){let t=e.alignments??[],n=e.chunkOffset??0;this.jobId!==e.jobId&&(this.reset(),this.jobId=e.jobId);let r=n+t.length;if(!(r<=this.consumed)){for(let s=Math.max(0,this.consumed-n);s<t.length;s++){let o=e.displayAlignments?.[s]??t[s];o?.characters?.length&&(this.chars.push(...o.characters),this.starts.push(...o.character_start_times_seconds),this.ends.push(...o.character_end_times_seconds));}this.consumed=r,this.cachedWords=null;}}get words(){return this.cachedWords??(this.cachedWords=ae({characters:this.chars,character_start_times_seconds:this.starts,character_end_times_seconds:this.ends})),this.cachedWords}reset(){this.jobId=null,this.consumed=0,this.chars=[],this.starts=[],this.ends=[],this.cachedWords=[];}};var zi=["right","left","below","above"],Ke=(i,e,t)=>Math.min(Math.max(i,e),Math.max(e,t)),Yi=(i,e,t,n,r)=>i>=r&&e>=r&&i+t.w<=n.w-r&&e+t.h<=n.h-r,Zo=(i,e)=>{let t=i/2+e/2,n=[0];for(let r=24;r<=t;r+=24)n.push(-r,r);return n},ea=(i,e,t,{margin:n,gap:r=16,prefer:s,blocked:o})=>{let a=typeof r=="number"?r:r.x,l=typeof r=="number"?r:r.y,d=i.top+i.height/2-e.h/2,c=i.left+i.width/2-e.w/2,p={right:{left:i.left+i.width+a,top:d},left:{left:i.left-a-e.w,top:d},below:{left:c,top:i.top+i.height+l},above:{left:c,top:i.top-l-e.h}},m=s?[s,...zi.filter(h=>h!==s)]:zi;for(let h of m){let{left:g,top:S}=p[h];if(h==="right"||h==="left"){let v={left:g,top:Ke(S,n,t.h-e.h-n),side:h};if(Yi(v.left,v.top,e,t,n))return v;continue}let E=null;for(let v of Zo(i.width,e.w)){let b={left:Ke(g+v,n,t.w-e.w-n),top:S,side:h};if(Yi(b.left,b.top,e,t,n)&&(E??(E=b),!o?.({left:b.left,top:b.top,width:e.w,height:e.h})))return b}if(E)return E}return {left:Ke(p.right.left,n,t.w-e.w-n),top:Ke(d,n,t.h-e.h-n),side:"right"}};var ta=i=>{let e=new Uint8Array(i.length/4);for(let t=0;t<e.length;t+=1){let n=t*4;e[t]=(i[n]+i[n+1]+i[n+2])/3;}return e},na=(i,e)=>{let t=0,n=0;for(let r=0;r<e.length;r+=1){let s=Math.abs(i[r]-e[r]);t+=s,s>n&&(n=s);}return {mean:e.length?t/e.length:0,max:n}},ia=(i,e,t)=>{if(!i||i.length!==e.length)return true;let{mean:n,max:r}=na(i,e);return n>=4?true:r>=8&&t>=4e3};var tr={happy:[{shape:"mouthSmile",weight:.8},{shape:"cheekSquint",weight:.2}],surprised:[{shape:"browInnerUp",weight:.25},{shape:"browOuterUp",weight:.25},{shape:"eyeWide",weight:.1},{shape:"jawOpen",weight:.4,mouth:true}],angry:[{shape:"browDown",weight:.85},{shape:"noseSneer",weight:.15}],sad:[{shape:"mouthFrown",weight:.55,mouth:true},{shape:"browInnerUp",weight:.45}]},ra={happy:.45,surprised:.3,angry:.2,sad:.35},Ji=.3,Qi=.2,sa={neutral:1,happy:1,surprised:1,angry:.7,sad:.7},oa=1500,aa=.6,la=1e3,ca=2e3,ua=.03,da=.2,ha=new Set(["browInnerUp","browOuterUp","eyeWide"]),Zi=.1,er=.3,je=i=>Math.round(i*100)/100,ge=[...new Set([...Object.values(tr).flatMap(i=>i.map(e=>e.shape)),"eyeBlink"])],ve=(i,e)=>{let t=i[e];if(typeof t=="number")return t;let n=i[`${e}Left`]??0,r=i[`${e}Right`]??0;return (n+r)/2},en=class{constructor(){this.baseline=new Map;this.window=[];this.current=null;this.candidate=null;this.faceLostAtMs=null;this.last=null;}update(e,t,n){if(!e)return this.noteNoFace(t);if(this.faceLostAtMs=null,this.baseline.size===0)for(let l of ge)this.baseline.set(l,Math.min(ve(e,l),er));let r=new Map;for(let l of ge){let d=this.baseline.get(l)??0,c=ve(e,l);r.set(l,d<1?Math.max(0,(c-d)/(1-d)):0);}let{label:s,scores:o}=this.frameLabel(r,n),a=["browInnerUp","browOuterUp"].reduce((l,d)=>l+Math.max(0,(this.baseline.get(d)??0)-ve(e,d)),0)/2;if(this.last={raw:Object.fromEntries(ge.map(l=>[l,je(ve(e,l))])),baseline:Object.fromEntries(ge.map(l=>[l,je(this.baseline.get(l)??0)])),browDrop:je(a),scores:o,label:s},s==="neutral"&&!n&&this.learnBaseline(e),s==="neutral"&&n)return this.candidate=null,this.current;for(this.window.push({atMs:t,label:s});this.window.length&&t-this.window[0].atMs>oa;)this.window.shift();return this.vote(t)}inspect(){return this.last}reset(){this.last=null,this.baseline.clear(),this.window=[],this.current=null,this.candidate=null,this.faceLostAtMs=null;}frameLabel(e,t){let n={},r="neutral",s=0;for(let[o,a]of Object.entries(tr)){let l=0;for(let c of a)c.mouth&&t||(l+=c.weight*(e.get(c.shape)??0));if(o==="angry"||o==="sad"){let c=e.get("mouthSmile")??0;l*=1-Math.max(0,c-Qi)/(1-Qi);}if(o==="surprised"){let c=e.get("eyeBlink")??0;l*=1-Math.max(0,c-Ji)/(1-Ji);}n[o]=je(l);let d=l-ra[o];d>s&&(r=o,s=d);}return {label:r,scores:n}}learnBaseline(e){for(let t of ge){let n=ve(e,t),r=this.baseline.get(t)??0;if(n-r>Zi)continue;let s=ha.has(t);if(s&&r-n>Zi)continue;let o=n<r&&!s?da:ua;this.baseline.set(t,Math.min(r+o*(n-r),er));}}vote(e){let t=new Map;for(let o of this.window)t.set(o.label,(t.get(o.label)??0)+1);let n=null,r=0;for(let[o,a]of t){let l=a/this.window.length;l>r&&(n=o,r=l);}if(!n||r<aa)return this.candidate=null,this.current;let s=Math.round(r*sa[n]*100)/100;return this.current?.state===n?(this.candidate=null,this.current={state:n,confidence:s},this.current):(this.candidate?.label!==n&&(this.candidate={label:n,sinceMs:e}),e-this.candidate.sinceMs>=la&&(this.current={state:n,confidence:s},this.candidate=null),this.current)}noteNoFace(e){return this.faceLostAtMs??(this.faceLostAtMs=e),e-this.faceLostAtMs<ca?this.current:(this.window=[],this.candidate=null,this.baseline.clear(),this.current={state:"no_face",confidence:1},this.current)}};var pa={top:"top",middle:"middle",center:"middle",centre:"middle",bottom:"bottom"},ma=new Set(["up","down"]),tn=i=>{let e=i.trim().toLowerCase();if(!e)return null;let t=pa[e];if(t)return {kind:"edge",edge:t};if(ma.has(e))return {kind:"step",direction:e};let n=de(e);return n?{kind:"axis",...n}:null};function fa(i){let e=i,t=new Set;return {subscribe(n){return t.add(n),()=>t.delete(n)},getSnapshot:()=>e,getServerSnapshot:()=>i,set(n){if(!Object.is(e,n)){e=n;for(let r of t)r();}}}}var Se=class{constructor(e,t=Math.random){this.idleActs=e;this.random=t;this.pass=[];this.round=[];this.lastId=null;}next(){this.round.length||(this.round=this.planRound());let e=this.round.shift();return this.lastId=e.id,e}planRound(){let{windowMinMs:e,windowMaxMs:t}=this.idleActs;this.pass.length||(this.pass=this.shuffled());let n=[],r=0;for(let o of [...this.pass])n.length&&r+o.ms>t||(n.push({act:o,holdMs:o.ms}),r+=o.ms,this.pass.splice(this.pass.indexOf(o),1));let s=o=>o.holdMs/o.act.ms;for(;r<e;){let o=t-r,a=n.filter(({act:d})=>d.loop!=="oneShot"&&d.ms<=o);if(!a.length)break;let l=a.reduce((d,c)=>s(c)<s(d)||s(c)===s(d)&&c.act.ms>d.act.ms?c:d);l.holdMs+=l.act.ms,r+=l.act.ms;}return n.map(({act:o,holdMs:a})=>({id:o.id,holdMs:a,cycleMs:o.ms,...o.timeline&&{timeline:o.timeline}}))}shuffled(){let e=[...this.idleActs.acts];for(let t=e.length-1;t>0;t--){let n=Math.floor(this.random()*(t+1));[e[t],e[n]]=[e[n],e[t]];}return e.length>1&&e[0].id===this.lastId&&e.push(e.shift()),e}};var nr={quietToIdleMs:Lt,idleCycleMs:0,playfulAfterMs:0,playfulRoles:[],idleTriggers:[],thinkingMaxMs:0},ga={has:()=>false,fire:()=>{}},qe="trigger:",va=.5,nn=class{constructor(e,t={},n=()=>{},r=()=>true,s=ga){this.writeMode=e;this.cycle=n;this.rigHas=r;this.rigTriggers=s;this.phase="off";this.timer=null;this.cycleTimer=null;this.attending=false;this.idleSince=0;this.idleRole="idle";this.idleStep="idle";this.planner=null;this.hold=null;this.holdStartMs=0;this.holdEntered=false;this.followsRig=false;this.rigPose=null;this.timings={...nr,...typeof t=="number"?{quietToIdleMs:t}:t},this.planner=this.timings.idleActs?new Se(this.timings.idleActs):null,this.followsRig=this.namesActs();}setMode(e,t){e!=="idle"&&(this.rigPose=null),this.writeMode(e,t);}namesActs(){return !!this.timings.idleActs?.acts.some(e=>e.timeline)}configure(e){this.timings={...nr,...e},this.planner=this.timings.idleActs?new Se(this.timings.idleActs):null,this.hold=null,this.followsRig=this.namesActs(),this.phase==="listening"?this.listen(false):this.phase==="idle"?this.settle():this.phase==="thinking"&&this.armThinkingLimit();}rest(e){if(this.clear(),!e){this.phase="off",this.setMode("idle");return}this.listen(true);}connect(){this.clear(),this.phase="off",this.idleSince=Date.now(),this.settle();}resume(e){switch(this.phase){case "busy":return;case "off":e?this.connect():this.setMode("idle");return;case "listening":this.setMode("listening");return;case "idle":this.setMode(this.idleRole,this.idleRole==="idle"?this.hold?.id:void 0);return;case "thinking":this.setMode("thinking");return}}think(){if(!(this.phase==="busy"||this.phase==="off")){if(this.phase==="thinking"){this.armThinkingLimit();return}this.startThinking();}}restThinking(){this.startThinking();}startThinking(){this.clear(),this.phase="thinking",this.setMode("thinking"),this.armThinkingLimit();}stopThinking(){this.phase==="thinking"&&this.listen(true);}userActivity(){this.phase==="busy"||this.phase==="off"||this.listen(false);}setAttending(e){e!==this.attending&&(this.attending=e,this.userActivity());}busy(){this.clear(),this.phase="busy",this.rigPose=null;}dispose(){this.clear();}rigEntered(e){this.timings.idleActs?.acts.some(t=>t.timeline===e)&&(this.rigPose={timeline:e,sinceMs:Date.now()},!(this.phase!=="idle"||this.idleRole!=="idle"||this.holdEntered||e!==this.hold?.timeline)&&(this.holdEntered=true,this.holdStartMs=Date.now(),this.cycleTimer!==null&&clearTimeout(this.cycleTimer),this.cycleTimer=null,this.armCycle()));}get current(){return this.phase}listen(e){this.clear(),(e||this.phase!=="listening")&&this.setMode("listening"),this.phase="listening",this.timings.quietToIdleMs>0&&!this.attending&&(this.timer=setTimeout(()=>{this.timer=null,!(this.phase!=="listening"||this.attending)&&(this.idleSince=Date.now(),this.settle());},this.timings.quietToIdleMs));}settle(){this.clear(),this.phase!=="idle"?(this.phase="idle",this.idleRole="idle",this.idleStep="idle",this.setMode("idle",this.nextHold(Date.now()))):this.idleRole==="idle"&&this.planner&&!this.hold&&this.cycle(this.nextHold(Date.now())),this.armCycle();}nextHold(e){if(this.hold=this.planner?.next()??null,this.holdStartMs=e,this.holdEntered=false,this.hold?.timeline&&this.rigPose&&this.rigPose.timeline===this.hold.timeline){let t=Math.floor((e-this.rigPose.sinceMs)/this.hold.cycleMs);this.holdStartMs=this.rigPose.sinceMs+Math.max(0,t)*this.hold.cycleMs,this.holdEntered=true;}return this.hold?.id}armCycle(){let e=this.idleRole==="idle"?this.hold:null;if(!e){this.timings.idleCycleMs>0&&this.armTimer(this.timings.idleCycleMs,()=>this.onCycle());return}if(this.followsRig&&!this.holdEntered){let n=Math.max(...this.timings.idleActs?.acts.map(r=>r.ms)??[0]);this.armTimer(this.holdStartMs+n+e.cycleMs-Date.now(),()=>{this.followsRig=false,this.holdEntered=true,this.holdStartMs=Date.now(),this.armCycle();});return}let t=this.holdStartMs+e.holdMs-e.cycleMs*(1-va);this.armTimer(t-Date.now(),()=>this.onCycle());}armTimer(e,t){this.cycleTimer=setTimeout(()=>{this.cycleTimer=null,t();},Math.max(0,e));}onCycle(){if(this.phase!=="idle")return;let{playfulAfterMs:e,playfulRoles:t,idleTriggers:n=[]}=this.timings,r=t.length>0||n.length>0,o=e>0&&r&&Date.now()-this.idleSince>=e?this.nextIdleStep(t,n):"idle";if(o.startsWith(qe)){this.idleRole!=="idle"&&(this.idleRole="idle",this.setMode("idle",this.nextHold(Date.now()))),this.idleStep=o,this.rigTriggers.fire(o.slice(qe.length)),this.armCycle();return}let a=o;this.idleStep=a;let l=this.idleRole==="idle"&&this.hold?this.holdStartMs+this.hold.holdMs:Date.now(),d=a==="idle"?this.nextHold(l):void 0;a===this.idleRole?this.cycle(d):(this.idleRole=a,this.setMode(a,d)),this.armCycle();}nextIdleStep(e,t){let n=[...e.filter(r=>r!==this.idleStep&&(r===this.idleRole||this.rigHas(r))),...t.map(r=>qe+r).filter(r=>r!==this.idleStep&&this.rigTriggers.has(r.slice(qe.length)))];return n.length?n[Math.floor(Math.random()*n.length)]:this.idleRole}armThinkingLimit(){this.timer!==null&&clearTimeout(this.timer),this.timer=null,!(this.timings.thinkingMaxMs<=0)&&(this.timer=setTimeout(()=>{this.timer=null,this.phase==="thinking"&&this.listen(true);},this.timings.thinkingMaxMs));}clear(){this.timer!==null&&clearTimeout(this.timer),this.cycleTimer!==null&&clearTimeout(this.cycleTimer),this.timer=null,this.cycleTimer=null;}};var Sa=2,rn=class{constructor(e){this.writeControl=e;this.policy=null;this.role=null;this.lastAct={};}setPolicy(e){e!==this.policy&&(this.policy=e,this.role=null,this.lastAct={});}get hasPolicy(){return this.policy!==null}get mode(){return this.role}get act(){return this.role?this.lastAct[this.role]??null:null}setMode(e,t){return e===this.role&&(t===void 0||t===this.lastAct[e])?true:this.enter(e,t)}cycle(e){return this.role?this.enter(this.role,e):false}reapply(){let e=this.role;return e?this.write(e,this.lastAct[e]??0):false}has(e){if(e==="idle"||e===this.role)return true;let t=this.policy?.branches[e]?.gate;return !!t&&this.writeControl(t,false)}stop(){this.role=null;}enter(e,t){if(!this.policy)return u.debug("BranchToggler","no performance policy \u2014 branch not written",{role:e}),false;let n=t??this.pickAct(e);return this.write(e,n)?(this.lastAct[e]=n,this.role=e,true):(u.debug("BranchToggler","branch write did not land \u2014 staying put",{wanted:e,role:this.role}),false)}pickAct(e){let t=this.policy?.branches[e]?.acts??[];if(!t.length)return 0;let n=t.length>1?t.filter(r=>r!==this.lastAct[e]):t;return n[Math.floor(Math.random()*n.length)]}resolve(e){let t=e;for(let n=0;n<=Sa;n++){let r=this.policy?.branches[t];if(!r)return null;if(!r.gate||!r.fallback||this.writeControl(r.gate,false))return r;t=r.fallback;}return null}write(e,t){let n=this.resolve(e);if(!n&&e!=="idle")return false;let r=Object.values(this.policy?.branches??{}).filter(l=>l!==n),s=new Set(r.map(l=>l.gate).filter(l=>!!l&&l!==n?.gate)),o=new Set(r.map(l=>l.act).filter(l=>!!l&&l!==n?.act)),a=[];n?.act&&t&&a.push(this.writeControl(n.act,t));for(let l of s)a.push(this.writeControl(l,false));n?.gate&&a.push(this.writeControl(n.gate,true));for(let l of o)a.push(this.writeControl(l,0));return a.some(Boolean)}};var Ea=(i,e,t)=>{let n=e?.[i];return {input:n?.input??i,type:n?.type??"trigger",value:n?.value??1,binding:n?.binding??(t?"data-binding":"input"),resetMs:n?.resetMs,returnMs:n?.returnMs??xt}};var sn=class{constructor(){this.segments=[];this.playable=0;}schedule(e,t,n){let r=this.segments[this.segments.length-1],s=n??(r?r.start+r.duration:0);return this.segments.push({at:e,start:s,duration:t}),r&&e<r.at&&this.segments.sort((o,a)=>o.at-a.at),this.playable=Math.max(this.playable,s+t),s}isAnchored(){return this.segments.length>0}timeAt(e){let t=this.segments;if(t.length===0)return _t;for(;t.length>1&&t[1].at<=e;)t.shift();let n=t[0];return n.start+(e-n.at)}playableTime(){return this.playable}reanchor(){this.segments.length=0;}reset(){this.segments.length=0,this.playable=0;}};var ze="viseme",Ye={plain:i=>`${i}`,prefix:i=>`${ze}${i}`,"prefix-space":i=>`${ze} ${i}`,suffix:i=>`${i}${ze}`},ir=["plain","prefix","prefix-space","suffix"],ba=/^(?:viseme\s*(\d+)|(\d+)\s*viseme|(\d+))$/i,ya=i=>{let e=i.trim().match(ba);if(!e)return null;let t=e[1]??e[2]??e[3];if(t===void 0)return null;let n=Number(t);return Number.isNaN(n)?null:n};function _a(i){let e=[0,1,2,6,21];for(let t of ir){let n=Ye[t];for(let r of e){let s=false;try{s=i(n(r));}catch{s=false;}if(s)return {format:n,shape:t,matched:true}}}return {format:Ye.plain,shape:"plain",matched:false}}var Ta="Watermark_opacity";var Ma=4e3,wa=6,Ra=.2,sr=-90,ka=25,Ia=200,Je=-50,Pa=18,or=10,Ca=10,Oa=500,Na=1e3,La=3,xa=10,Da=500,Fa=30,Ha=30,Ba=-50,Ua=-30,J=80,Wa=400,H=i=>i<=1e-7?-140:20*Math.log10(i),Y=i=>i.length?H(i.reduce((e,t)=>e+t,0)/i.length):-140;function ar(i,e){let t=0,n=0,r=0;for(let s=0;s<i.length;s++){for(n+=i[s].mic*i[s].mic;r<s&&i[s].t-i[r].t>e;)n-=i[r].mic*i[r].mic,r++;i[s].t-i[r].t<e*.9||(t=Math.max(t,n/(s-r+1)));}return H(Math.sqrt(t))}var Qe=class{constructor(){this.buf=[];this.pausedAt=null;this.floorDb=null;this.floorComputedAt=0;this.erlSamples=[];this.erlSampledAt=0;this.micDb=-140;this.gateOpen=false;this.gateHoldUntil=0;this.gateLevelDb=-140;this.renderAudibleSince=null;}push(e,t){let n=Date.now();this.buf.push({t:n,mic:e,render:t});let r=n-Ma,s=0;for(;s<this.buf.length&&this.buf[s].t<r;)s++;s&&this.buf.splice(0,s),H(t)>=Je?this.renderAudibleSince===null&&(this.renderAudibleSince=n):this.renderAudibleSince=null,this.micDb=H(e),this.updateFloor(),this.updateErl(),this.updateGate();}updateErl(){let e=Date.now();if(e-this.erlSampledAt<Oa)return;let t=this.recent(Na);!t||t.renderDb<Je||this.floorDb!==null&&this.pausedAt===null&&(t.micDb<=sr||t.micDb<this.floorDb+xa&&(this.renderAudibleSince===null||e-this.renderAudibleSince<Da)||(this.erlSampledAt=e,this.erlSamples.push(t.erlDb),this.erlSamples.length>Ca&&this.erlSamples.shift()));}erlEstimateDb(){if(this.erlSamples.length<La)return Pa;let e=[...this.erlSamples].sort((t,n)=>t-n);return Math.min(e[Math.floor(e.length/2)],Fa)}updateFloor(){let e=Date.now();if(this.floorDb!==null&&e-this.floorComputedAt<Ia)return;let t=[];for(let n of this.buf){let r=H(n.mic);r>sr&&t.push(r);}t.length<ka||(t.sort((n,r)=>n-r),this.floorDb=t[Math.floor((t.length-1)*Ra)],this.floorComputedAt=e);}updateGate(){this.gateLevelDb=H(this.meanMicRms(J));let e=this.gateThresholdDb();if(this.gateLevelDb>=e){this.gateHoldUntil=Date.now()+Wa,this.gateOpen=true;return}this.gateOpen=Date.now()<this.gateHoldUntil;}gateThresholdDb(){let e=this.floorDb===null?-1/0:this.floorDb+Ha,t=H(this.meanRenderRms(J)),n=t>=Je?t-this.erlEstimateDb()+or:-1/0;return Math.min(Math.max(Ba,e,n),Ua)}meanMicRms(e){let t=Date.now()-e,n=0,r=0;for(let s=this.buf.length-1;s>=0&&!(this.buf[s].t<t);s--)n+=this.buf[s].mic,r++;return r?n/r:0}meanRenderRms(e){let t=Date.now()-e,n=0,r=0;for(let s=this.buf.length-1;s>=0&&!(this.buf[s].t<t);s--)n+=this.buf[s].render,r++;return r?n/r:0}isLive(){return this.gateOpen}levels(){return {micNowDb:+this.micDb.toFixed(1),gateLevelDb:+this.gateLevelDb.toFixed(1),gateAtDb:+this.gateThresholdDb().toFixed(1),floorDb:+(this.floorDb??-140).toFixed(1),erlEstDb:+this.erlEstimateDb().toFixed(1)}}markPaused(){this.pausedAt=Date.now();}clearPaused(){this.pausedAt=null;}report(){if(this.buf.length<10)return null;let e=Date.now(),t=this.pausedAt??e,n=this.buf.filter(p=>p.t>=t-500&&p.t<=t),r=this.buf.filter(p=>p.t>t),s=Y(n.map(p=>p.mic)),o=Y(n.map(p=>p.render)),a=this.floorDb??-140,l=a+wa,d=-1;for(let p of r)if(H(p.mic)<=l){d=p.t-t;break}let c=n.length?Math.max(...n.map(p=>H(p.mic))):-140;return {micPreDb:+s.toFixed(1),renderPreDb:+o.toFixed(1),erlDb:+(o-s).toFixed(1),micPostDb:+Y(r.map(p=>p.mic)).toFixed(1),micFloorDb:+a.toFixed(1),micPeakDb:+c.toFixed(1),micPostSustainedDb:+ar(this.buf.filter(p=>p.t>t+60),J).toFixed(1),gateAtDb:+this.gateThresholdDb().toFixed(1),micDecayMs:d}}provablyNotEcho(e,t){if(this.pausedAt===null)return false;let n=this.pausedAt,r=this.buf.filter(l=>l.t>=n-500&&l.t<=n),s=this.buf.filter(l=>l.t>n+t);if(r.length===0||s.length===0)return false;let o=Y(r.map(l=>l.render));if(o<Je)return false;let a=o-this.erlEstimateDb()+or;return ar(s,J)>=a+e}recent(e){let t=Date.now()-e,n=this.buf.filter(o=>o.t>=t);if(n.length<5)return null;let r=Y(n.map(o=>o.mic)),s=Y(n.map(o=>o.render));return {micDb:+r.toFixed(1),renderDb:+s.toFixed(1),erlDb:+(s-r).toFixed(1)}}reset(){this.buf=[],this.pausedAt=null,this.floorDb=null,this.floorComputedAt=0,this.erlSamples=[],this.erlSampledAt=0,this.micDb=-140,this.gateOpen=false,this.gateHoldUntil=0,this.gateLevelDb=-140,this.renderAudibleSince=null;}};function lr(i){let e=0;for(let t=0;t<i.length;t++)e+=i[t]*i[t];return Math.sqrt(e/Math.max(1,i.length))}var Ze=class{constructor(e){this.onModeChange=e;this.pending=null;this.samples=[];this.blackoutStreak=0;this.lastEpisodeAt=0;this.mode="healthy";this.episodesInMode=0;}noteVoiceFrame(e,t){this.expirePending(t);let n=this.pending;if(e<Zn){n&&n.endedAt===null&&t-n.lastVoicedAt>150&&(n.endedAt=t);return}if(!n){this.pending={onsetAt:t,voicedMs:0,lastVoicedAt:t,endedAt:null};return}n.endedAt=null;let r=t-n.lastVoicedAt;r>0&&r<=150&&(n.voicedMs+=r),n.lastVoicedAt=t;}noteTranscript(e){let t=this.pending;t&&(this.pending=null,this.blackoutStreak=0,this.samples.push(e-t.onsetAt),this.samples.length>qn&&this.samples.shift(),this.closeEpisode(e));}policy(e,t=false){return this.isStale(e)&&this.setMode("healthy","stale"),t?Gt:this.mode==="degraded"?Gt:Fe}currentMode(){return this.mode}lagMs(){return this.median()}getBlackoutStreak(){return this.blackoutStreak}clearPending(){this.pending=null;}reset(){this.pending=null,this.samples=[],this.blackoutStreak=0,this.lastEpisodeAt=0,this.mode="healthy",this.episodesInMode=0;}expirePending(e){let t=this.pending;!t||t.endedAt===null||e-t.endedAt<Qn||(this.pending=null,!(t.voicedMs<Jn)&&(this.blackoutStreak++,this.closeEpisode(e)));}closeEpisode(e){this.lastEpisodeAt=e,this.episodesInMode++,!(this.episodesInMode<zn)&&this.setMode(this.verdict(e),"lag");}setMode(e,t){if(e===this.mode)return;let n=this.mode;this.mode=e,this.episodesInMode=0,this.onModeChange?.({from:n,to:e,reason:t,lagMs:this.median(),blackoutStreak:this.blackoutStreak,samples:this.samples.length});}isStale(e){return this.lastEpisodeAt===0||e-this.lastEpisodeAt>Yn}median(){if(this.samples.length===0)return null;let e=[...this.samples].sort((t,n)=>t-n);return e[Math.floor(e.length/2)]}verdict(e){let t=this.median();return t===null||this.isStale(e)?"healthy":t>Kn?"degraded":t<jn?"healthy":this.mode}};var an=class{constructor(e,t,n){this.runtime=e;this.sensorProvider=t;this.vad=null;this.controller=null;this.initPromise=null;this.playback=null;this.speaking=false;this.micMuted=false;this.handedBack=false;this.framesPushed=0;this.voicedFramesSeen=0;this.userVoicedAtMs=0;this.voiceRunStartedAt=0;this.voiceWakeSent=false;this.partialsWhileBlind=0;this.trace=new Qe;this.asrLag=new Ze(e=>u.event("bargein","policy",e));this.lastEchoLogAt=0;this.vadCost={at:0,calls:0,totalMs:0,maxMs:0,audioMs:0};this.dutyBreaches=0;this.sessionStartedAt=Date.now();this.gatedFrames=0;this.farEndMs=0;this.softPaused=false;this.uplinkDelay=[];this.echoGate=n?.echoGate??true;}setPlaybackControls(e){this.playback=e;}setSpeaking(e){let t=this.speaking!==e;this.speaking=e,t&&this.runtime.setAgcForAvatarSpeech(e),e||(this.softPaused=false),t&&e&&this.resetBlindWatch();}isUserVoiced(){return Date.now()-this.userVoicedAtMs<li}isAvatarAudible(){return this.speaking||(this.playback?.hasPendingAudio?.()??false)}setMicMuted(e){this.micMuted!==e&&(this.micMuted=e,e&&(this.controller?.abort(),this.vad?.reset(),this.trace.reset(),this.uplinkDelay=[],this.asrLag.clearPending()));}effectivePolicy(){return this.asrLag.policy(Date.now(),this.runtime.transcriptPathDegraded())}prefetch(){this.runtime.loadVadWeights().catch(()=>{});}async ensureInit(){if(this.sessionStartedAt=Date.now(),this.controller){this.runtime.sendClientVadStatus(true);return}return this.initPromise||(this.initPromise=this.init()),this.initPromise}async init(){try{let e=await this.sensorProvider.create(await this.runtime.loadVadWeights()),t=Kt({isAvatarSpeaking:()=>this.isAvatarAudible(),pausePlayback:()=>{u.event("bargein","soft_pause",{mode:this.effectivePolicy().mode,...this.trace.levels()}),this.softPaused=!0,this.trace.markPaused(),this.playback?.pause();},resumePlayback:()=>{this.softPaused=!1,this.trace.clearPaused(),this.playback?.resume();},commitInterrupt:()=>this.runtime.interrupt({notifyServer:!0,reason:"barge_in"}),getActiveScriptTail:()=>this.runtime.getScriptTail(),isProvablyNotEcho:()=>this.trace.provablyNotEcho(10,60),getPolicy:()=>this.effectivePolicy(),onTelemetry:n=>u.event("bargein",n.outcome,{mode:n.mode,policySource:n.mode==="degraded"&&this.asrLag.currentMode()!=="degraded"?"health":"measured",pathFault:this.runtime.transcriptPathDegraded(),blackoutStreak:this.asrLag.getBlackoutStreak(),asrLagMs:this.asrLag.lagMs(),clause:n.commitClause,onsetToPauseMs:n.voiceOnsetToPauseMs,voicedMs:n.totalVoicedMs,postPauseMs:n.postPauseVoicedMs,wordlessStreak:n.wordlessResumeStreak,transcript:n.transcript,motion:n.speechMotion,medianFlux:n.speechMedianFlux,modulation:n.speechModulation,...this.trace.report()??{}})});e.onProb((n,r,s)=>{if(this.isAvatarAudible()?this.voiceRunStartedAt=0:(this.asrLag.noteVoiceFrame(n,Date.now()),n>=.5&&(this.userVoicedAtMs=Date.now()),this.noteVoiceForWake(n)),n>=.5&&this.voicedFramesSeen++,!this.echoGate||this.trace.isLive()&&!this.isWarming()){t.onVadProb(n,r,s);return}n>=.5&&this.gatedFrames++,t.onVadProb(0,r,null);}),this.vad=e,this.controller=t,this.handedBack=!1,this.resetBlindWatch(),u.debug("BargeIn","client VAD initialized"),this.runtime.sendClientVadStatus(!0);}catch(e){u.error("BargeIn","failed to init client VAD",e),this.initPromise=null,this.handedBack=true,this.runtime.sendClientVadStatus(false,"asset_load_failed");}}disable(e){this.vad?.destroy?.(),this.vad=null,this.controller=null,this.initPromise=null,this.dutyBreaches=0,this.handedBack=true,u.warn("BargeIn","client VAD disabled",{reason:e}),this.runtime.sendClientVadStatus(false,e);}pushLevel(e,t){this.micMuted||(this.isAvatarAudible()&&this.farEndMs<1500&&(this.farEndMs+=t/16e3*1e3),this.trace.push(e,this.playback?.getOutputLevel?.()??0),this.logEchoHealth());}pushPcm(e){if(this.micMuted)return;this.isAvatarAudible()&&this.farEndMs<1500&&(this.farEndMs+=e.length/16e3*1e3),this.trace.push(lr(e),this.playback?.getOutputLevel?.()??0),this.logEchoHealth();let t=e.length,n=Date.now();this.vad&&(this.vad.pushPcm(e),this.framesPushed++),this.noteVadCost(Date.now()-n,t);}noteVadCost(e,t){let n=this.vadCost;n.calls++,n.totalMs+=e,n.audioMs+=t/16e3*1e3,e>n.maxMs&&(n.maxMs=e);let r=Date.now();if(n.at===0){n.at=r;return}let s=r-n.at;if(s<1e3)return;let o=Math.round(n.totalMs/s*100);this.vadCost={at:r,calls:0,totalMs:0,maxMs:0,audioMs:0},this.noteSensorHealth(o);}noteSensorHealth(e){if(this.vad){if(e<ei){this.dutyBreaches=0;return}++this.dutyBreaches<ti||(u.warn("BargeIn","client VAD cannot keep up",{dutyPct:e}),this.disable("sensor_too_slow"));}}isWarming(){return this.isAvatarAudible()&&this.farEndMs<1500}logEchoHealth(){}onPartialTranscript(e){e&&this.asrLag.noteTranscript(Date.now()),e&&this.noteBlindSensor(),this.controller?.onPartialTranscript(e);}noteBlindSensor(){!this.controller||this.micMuted||this.isAvatarAudible()&&(this.farEndMs<1500||this.framesPushed<ni||this.voicedFramesSeen>0||++this.partialsWhileBlind<ii||(u.warn("BargeIn","client VAD scored nothing while ASR returned words",{framesPushed:this.framesPushed}),this.disable("sensor_blind")));}resetBlindWatch(){this.framesPushed=0,this.voicedFramesSeen=0,this.partialsWhileBlind=0;}shouldUplink(){return this.handedBack||!this.isAvatarAudible()||this.softPaused?true:this.isWarming()?false:this.trace.isLive()}noteVoiceForWake(e){if(e<.5||!this.trace.isLive()){this.voiceRunStartedAt=0,this.voiceWakeSent=false;return}let t=Date.now();this.voiceRunStartedAt||(this.voiceRunStartedAt=t),!(this.voiceWakeSent||t-this.voiceRunStartedAt<ci)&&(this.voiceWakeSent=true,this.runtime.noteUserVoice());}releaseUplinkFrames(e){if(!this.echoGate)return [e];if(!this.isAvatarAudible()){let s=this.uplinkDelay.map(o=>o.frame);return this.uplinkDelay=[],[...s,e]}let t=Date.now();this.uplinkDelay.push({t,frame:e});let n=this.shouldUplink(),r=[];for(;this.uplinkDelay.length>0&&t-this.uplinkDelay[0].t>=J;){let s=this.uplinkDelay.shift();n||s.frame.fill(0),r.push(s.frame);}return r}reset(){this.vad?.reset(),this.controller?.reset(),this.trace.reset(),this.sessionStartedAt=Date.now(),this.softPaused=false,this.uplinkDelay=[],this.farEndMs=0,this.asrLag.reset(),this.dutyBreaches=0,this.vadCost={at:0,calls:0,totalMs:0,maxMs:0,audioMs:0},this.userVoicedAtMs=0,this.voiceRunStartedAt=0,this.voiceWakeSent=false,this.resetBlindWatch();}dispose(){this.vad?.destroy?.(),this.vad=null,this.controller=null,this.initPromise=null;}};var Ga=/^(cc-|new-password|current-password|one-time-code)/,$a=/\b(?:card (?:number|no|num)|cc (?:number|num|no)|cvv|cvc|csc|security code|iban|ssn|social security|otp)\b/,Xa=i=>i.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_\-.:]+/g," ").toLowerCase(),tt=(i,e="")=>{if(i.getAttribute("type")==="password"||Ga.test(i.getAttribute("autocomplete")||""))return true;let t=["name","id","aria-label","placeholder"].map(n=>i.getAttribute(n)||"").concat(e).join(" ");return $a.test(Xa(t))},Ee=i=>(i instanceof HTMLButtonElement||i instanceof HTMLInputElement)&&(i.type==="submit"||i.type==="image")&&i.form!==null;var Ka=/\bsponsored\b/i,ja="nav, aside, [role=navigation], [role=banner], [role=contentinfo], [role=complementary]",ln=i=>{if(i.closest(ja))return true;let e=i.closest("header, footer");return !!e&&!e.parentElement?.closest("article, section, main, [role=main]")},qa=i=>{let e=i.getAttribute("role"),t=Array.from(i.classList).sort().slice(0,3).join(".");return `${i.tagName}${e?`[${e}]`:""}${t?`.${t}`:""}`},za=i=>[i,i.parentElement,i.parentElement?.parentElement].map(e=>e?qa(e):"").join("<"),Ya=i=>{let e=0;for(let t=i.parentElement;t;t=t.parentElement)e+=1;return e},cr=(i,e)=>i.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1,Ja=i=>{let e=i.ownerDocument.defaultView;if(!e)return false;let t=i.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;return n>=0&&r>=0&&n<=e.innerWidth&&r<=e.innerHeight},nt=(i,e)=>{if(i.length<=e)return i;let t=i.slice(0,e),n=t.lastIndexOf(" ");return `${n>0?t.slice(0,n):t}\u2026`},Qa=i=>{let e=new Map,t=new Map;for(let r of i){let s=r.el;for(let o=0;s&&o<=8&&s!==s.ownerDocument.body;o+=1){let a=za(s),l=e.get(a);l||e.set(a,l=new Set),l.add(s);let d=t.get(s);d||t.set(s,d=[]),d.push(r),s=s.parentElement;}}let n=[];for(let r of e.values()){if(r.size<3)continue;let s=Array.from(r).sort(cr);s.some((o,a)=>a>0&&s[a-1].contains(o))||n.push({cards:s,depth:s.reduce((o,a)=>o+Ya(a),0)/s.length});}return {groups:n,controlsIn:t}},Za=i=>{let e=new Set;for(let t of i){let n=new Set(t.cards);for(let r of i){let s=r.depth-t.depth;if(r===t||s<=0||s>8)continue;let o=new Map;for(let l of r.cards){let d=l.parentElement;for(let c=0;d&&c<8;c+=1,d=d.parentElement)if(n.has(d)){o.set(d,(o.get(d)??0)+1);break}}if(o.size<3)continue;Array.from(o.values()).reduce((l,d)=>l+d,0)/o.size>=1.5?e.add(t):e.add(r);}}return i.filter(t=>!e.has(t))};function ur(i,e){let t=new Map,n=m=>{let h=t.get(m);return h===void 0&&t.set(m,h=e.textOf(m)),h},{groups:r,controlsIn:s}=Qa(i),o=m=>{if(ln(m)||Ka.test(n(m)))return false;let h=s.get(m)??[];return h.length!==1?h.length>1:n(m).length>h[0].name.length+3},a=m=>{let h=(E,v)=>n(v.el).length-n(E.el).length,g=m.filter(({el:E})=>E.matches("a[href], [role=link]"));return [...g.filter(({el:E})=>e.pathOf(E))].sort(h)[0]??[...g].sort(h)[0]??m[0]},l=(m,h)=>{let g=m[0].parentElement;for(let S=0;g&&S<3;S+=1,g=g.parentElement){let E=g.getAttribute("aria-label")?.trim();if(E)return nt(E,60);let v=g.previousElementSibling;for(let b=0;v&&b<3;b+=1){let R=v.matches("h1, h2, h3, [role=heading]")?v:v.querySelector("h1, h2, h3, [role=heading]"),P=R?n(R):"";if(P)return nt(P,60);v=v.previousElementSibling;}}return `List ${h}`},d=Za(r.map(m=>({...m,cards:m.cards.filter(o)})).filter(m=>m.cards.length>=3)).sort((m,h)=>cr(m.cards[0],h.cards[0])),c={lists:[],primary:new Map,secondary:new Set},p=new Set;for(let m of d){if(c.lists.length>=6)break;let h=c.lists.length+1,g=[],S=[],E=0;for(let v of m.cards){let b=(s.get(v)??[]).filter(({el:O})=>!p.has(O)),R=a(b);if(!R)continue;let P=n(R.el),C=nt(n(v).replace(P," ").replace(/\s+/g," ").trim(),90);g.push([R.el,{list:h,position:g.length+1,...Ja(v)&&{screenPosition:++E},...C&&{detail:C},name:nt(P,60)||R.name}]);for(let{el:O}of b)O!==R.el&&S.push(O);}if(!(g.length<3)){c.lists.push({id:h,name:l(m.cards,h),total:g.length});for(let[v,b]of g)c.primary.set(v,b),p.add(v);for(let v of S)c.secondary.add(v),p.add(v);}}return c}var cn=/^skip (?:to\b|navigation\b|nav\b|main\b|links\b)/i,el=25,tl=60,nl=40,mn={maxControls:tl,reservedLinks:0,groupLists:false,maxItems:0,preferVisible:false},fh={maxControls:120,reservedLinks:60,groupLists:true,maxItems:40,preferVisible:true},Sr=60,il=120,rl=200,dr=2,Er="main, section, article, aside, nav, header, footer, [role=region], [role=tabpanel], [role=main], [role=navigation], [role=banner], [role=contentinfo]",Ar="h1, h2, h3, [role=heading]",br="button, summary, [role=button], [role=tab], [role=menuitem], [role=menuitemradio], [role=menuitemcheckbox], [role=option], input[type=submit], input[type=button], input[type=reset]",sl=new Set(["option","menuitemradio","menuitemcheckbox"]),yr="a[href], [role=link]",hn="input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]), select, textarea, [contenteditable=''], [contenteditable=true], [role=textbox], [role=combobox]",ol="form, [role=form]",hr={section:"s",button:"b",link:"l",field:"f",form:"frm"},_=(i,e)=>(i.getAttribute(e)||"").trim(),_r=/\s*[.(]?\s*opens? in (?:a )?new (?:tab|window)\)?\.?/gi,k=(i,e=Sr)=>i.replace(_r,"").replace(/\s+/g," ").trim().slice(0,e),Tr=(i,e)=>{let t=k(i,1/0);if(t.length<=e)return t;let n=t.slice(0,e),r=n.lastIndexOf(" ");return r>0?n.slice(0,r):n},al=i=>!!i.body&&i.body.getBoundingClientRect().width>0,fn=(i,e)=>{let t=i;if(typeof t.checkVisibility=="function"&&!t.checkVisibility({contentVisibilityAuto:true,visibilityProperty:true}))return false;if(!e)return true;let n=i.getBoundingClientRect();return n.width>=dr&&n.height>=dr},ll=(i,e)=>{let t=e.defaultView;if(!t)return false;let n=i.getBoundingClientRect(),r=n.left+n.width/2,s=n.top+n.height/2;if(r<0||s<0||r>t.innerWidth||s>t.innerHeight)return false;let o=e.elementFromPoint(r,s);return !!o&&o!==i&&!i.contains(o)&&!o.contains(i)},cl=(i,e)=>{let t=e.defaultView;if(!t)return true;let n=i.getBoundingClientRect();return n.bottom>0&&n.right>0&&n.top<t.innerHeight&&n.left<t.innerWidth},ul=(i,e)=>{if(i.closest("[inert]"))return true;let t=e.defaultView;return t?t.getComputedStyle(i).pointerEvents==="none":false},st=i=>{let e=_(i,"aria-label");if(e)return k(e);let t=_(i,"aria-labelledby");if(!t)return "";let n=t.split(/\s+/).map(r=>{let s=i.ownerDocument.getElementById(r);return s?V(s):""}).join(" ");return k(n)},dl=new Set(["A","ABBR","B","BDI","BDO","CITE","CODE","DATA","DFN","EM","I","KBD","MARK","Q","RUBY","S","SAMP","SMALL","SPAN","STRONG","SUB","SUP","TIME","U","VAR"]),Mr="script, style, [aria-hidden=true], [hidden]",V=(i,e,t=true)=>{if(i.nodeType===Node.TEXT_NODE)return i.nodeValue||"";if(i.nodeType!==Node.ELEMENT_NODE)return "";let n=i;if(!t&&e&&n.matches(e))return "";let r="";for(let s of Array.from(n.childNodes))r+=V(s,e,false);return dl.has(n.tagName)?r:` ${r} `},wr=(i,e)=>{let t=[],n=i.ownerDocument.createTreeWalker(i,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:r=>r!==i&&r.nodeType===Node.ELEMENT_NODE&&r.matches(e)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT});for(let r=n.nextNode();r;r=n.nextNode())r.nodeType===Node.TEXT_NODE&&t.push(r.nodeValue??"");return t},hl=i=>{let e=k(V(i,Mr));return e.length>rl?"":e},pl=i=>{let e=i.querySelector("img[alt], [role=img][aria-label]");return e?k(_(e,"alt")||_(e,"aria-label")):""},ml=i=>{let e=i.labels?.[0];if(e)return k(V(e));if(i.id){let n=i.ownerDocument.querySelector(`label[for="${CSS.escape(i.id)}"]`);if(n)return k(V(n))}let t=i.closest("label");return t?k(V(t)):""},fl=i=>i.length>=3&&/[a-z]/i.test(i)&&/[aeiou]/i.test(i)&&!/\d{3}/.test(i),Q=i=>{if(!i)return "";let e=k(i.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_\-.:]+/g," ").toLowerCase());return fl(e)?e:""},gl=i=>{let e=_(i,"autocomplete");if(e&&e!=="off"&&e!=="on")return Q(e);let t=_(i,"type");return t&&t!=="text"?`${t} field`:""},vl=(i,e)=>{for(let t=e.parentElement;t&&t!==i;t=t.parentElement)if(t.matches(Er))return false;return true},Rr=i=>{for(let e of Array.from(i.querySelectorAll(Ar)))if(vl(i,e))return k(V(e));return ""},Sl=4,kr=30,Ae=i=>{for(let[e,t]of i){let n=t();if(n)return {name:n,namedBy:e}}return {name:"",namedBy:"none"}},El={nav:"navigation",header:"header",footer:"footer",main:"main content",aside:"sidebar"},Al=i=>Ae([["aria",()=>st(i)],["heading",()=>Rr(i)],["id",()=>Q(i.id)],["landmark",()=>El[i.tagName.toLowerCase()]??""]]),pr=i=>Ae([["aria",()=>st(i)],["text",()=>hl(i)],["img-alt",()=>pl(i)],["title",()=>_(i,"title")],["id",()=>Q(_(i,"name")||i.id)]]),bl=i=>Ae([["aria",()=>st(i)],["label",()=>ml(i)],["placeholder",()=>_(i,"placeholder")],["title",()=>_(i,"title")],["id",()=>Q(_(i,"name")||i.id)],["type",()=>gl(i)]]),Ir=i=>_(i,"role")==="combobox"&&!(i instanceof HTMLInputElement||i instanceof HTMLSelectElement||i instanceof HTMLTextAreaElement),yl=i=>i.hasAttribute("data-placeholder")?"":k(wr(i,"[aria-hidden=true]").join("")),_l=(i,e)=>{if(!sl.has(_(i,"role")))return null;let t=i.closest("[role=listbox], [role=menu]");if(!t?.id)return null;let n=CSS.escape(t.id);return e.querySelector(`[aria-controls~="${n}"], [aria-owns~="${n}"]`)},Tl=i=>{let e=_(i,"type");if(e==="checkbox"||e==="radio")return e;if(Ir(i))return "combobox";let t=_(i,"autocomplete");if(t&&t!=="off"&&t!=="on")return t;if(e)return e;let n=i.tagName.toLowerCase();return n==="select"||n==="textarea"||n==="input"?n:_(i,"role")==="combobox"?"combobox":"text"},Ml=i=>i instanceof HTMLInputElement&&(i.type==="checkbox"||i.type==="radio"),un=12,wl=i=>{let e=Array.from(i.options).filter(n=>!n.disabled&&n.value!=="").map(n=>k(n.label||n.text,Sr)).filter(Boolean);if(e.length<=un)return e;let t=e.length-un;return [...e.slice(0,un),`+${t} more`]},mr=i=>i.disabled===true||_(i,"aria-disabled")==="true",Rl=i=>{if(Ml(i))return {checked:i.checked};if(!Ir(i))return {filled:kl(i)};let e=yl(i);return e?{shows:e}:{filled:false}},kl=i=>{let e=i.value;return typeof e=="string"?e.trim().length>0:k(i.textContent||"").length>0},fr=(i,e)=>{let t=_(i,"href");if(!(!t||t.startsWith("#")))try{let n=new URL(t,e.baseURI);return n.origin===e.location.origin?n.pathname+n.search:void 0}catch{return}},dn=60,Il=i=>{if(i.length<=dn)return i;let e=i.split("?")[0];return e.length<=dn?e:`${e.slice(0,dn)}\u2026`},Pl=i=>{for(let e of ["q","url","u"]){let t=i.searchParams.get(e);if(!(!t||!/^https?:\/\//i.test(t)))try{let n=new URL(t);if(n.origin!==i.origin)return n}catch{}}},Cl=i=>i.querySelector("cite")?.textContent?.trim().match(/^(?:https?:\/\/)?(?:www\.)?([a-z0-9-]+(?:\.[a-z0-9-]+)+)/i)?.[1]?.toLowerCase(),Ol=(i,e)=>{let t=_(i,"href");if(!(!t||t.startsWith("#")))try{let n=new URL(t,e.baseURI);return /^https?:$/.test(n.protocol)?(n.origin===e.location.origin?Pl(n):n)?.hostname.replace(/^www\./,"")??Cl(i):void 0}catch{return}},gr=i=>i.split("?")[0].replace(/\/+$/,"")||"/",Nl=/\s+[—–|·:]\s+/,Ll=(i,e)=>Ae([["route",()=>Dl(Q(xl(i.location.pathname)))],["self-link",()=>k(e)],["title",()=>k(i.title.split(Nl)[0]||"")]]),xl=i=>i.split("/").filter(Boolean).pop()||"",Dl=i=>i?i[0].toUpperCase()+i.slice(1):"",Fl=(i,e)=>{let t=i;for(let n=0;n<e&&t;n+=1)t=t.parentElement;return t?Tr(V(t,`${br}, ${yr}, ${hn}`),kr):""},it=(i,e=[])=>{let t=new Map;for(let r of i){let s=t.get(r.name);s?s.push(r):t.set(r.name,[r]);}let n=[];for(let r of t.values()){if(r.length===1){n.push(r[0]);continue}let s=_(r[0].el,"href");if(s&&r.every(l=>_(l.el,"href")===s)){n.push({...r[0],count:r.length});continue}let o=r.map(l=>Tr(Pr(l.el,e),kr));if(o.every(Boolean)&&new Set(o).size===r.length){r.forEach((l,d)=>{l.name=`${l.name} \u2014 in "${o[d]}"`;}),n.push(...r);continue}let a=false;for(let l=1;l<=Sl&&!a;l+=1){let d=r.map(c=>Fl(c.el,l));d.some(c=>!c)||new Set(d).size===r.length&&(r.forEach((c,p)=>{c.name=`${c.name} \u2014 ${d[p]}`;}),a=true);}a?n.push(...r):n.push({...r[0],count:r.length});}return n.sort(pn)},rt=(i,e,t,n,r=false)=>{let s=[],o=[],a=0;for(let l of Array.from(i.querySelectorAll(e))){if(!fn(l,t)||r&&t&&ul(l,i))continue;let d=r&&t&&ll(l,i),c=n(l);if(d){c.name&&o.push(c.name);continue}if(!c.name){a+=1;continue}s.push({el:l,name:c.name,namedBy:c.namedBy});}return {named:s,unnamed:a,covered:o}},Hl=i=>i.length>=2&&/[a-z]/i.test(i),Bl=(i,e,t)=>{let n=[];for(let r of Array.from(i.querySelectorAll(Ar))){if(!fn(r,e)||t.some(o=>o.contains(r)))continue;let s=k(r.textContent||"");Hl(s)&&n.push({el:r,name:s,namedBy:"heading-block"});}return n},pn=(i,e)=>i.el.compareDocumentPosition(e.el)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1,Ul=i=>{let e=[];for(let t of i)e.some(r=>r.name===t.name&&(r.el.contains(t.el)||t.el.contains(r.el)))||e.push(t);return e},Pr=(i,e)=>{let t="",n="";for(let r of e)r.el.contains(i)?t=r.name:r.el.compareDocumentPosition(i)&Node.DOCUMENT_POSITION_FOLLOWING&&(n=r.name);return t||n},Wl=i=>wr(i,Mr).join(" ").replace(_r,"").replace(/\s+/g," ").trim(),Vl=(i,e)=>{let t=Array.from(i.primary).sort(([,n],[,r])=>(n.screenPosition?0:1)-(r.screenPosition?0:1)||n.list-r.list||n.position-r.position);return new Map(t.slice(0,e))},vr=({list:i,position:e,screenPosition:t,detail:n})=>({list:i,position:e,...t&&{screenPosition:t},...n&&{detail:n}});function Cr(i=document,e=1,t=mn){let n=al(i),r=new Map,s=[],o={},a={section:0,button:0,link:0,field:0,form:0},l=new Map,d=(f,A)=>{a[A]+=1;let y=`${hr[A]}${a[A]}`;return r.set(y,f),l.set(f,y),y},c=rt(i,Er,n,Al);o.section=c.unnamed;let p=Ul([...c.named,...Bl(i,n,c.named.map(f=>f.el))].sort(pn)),m=it(p).slice(0,el),h=m.filter(f=>f.namedBy!=="landmark");for(let{el:f,name:A,namedBy:y}of h)s.push({handle:d(f,"section"),kind:"section",name:A,namedBy:y});let g=rt(i,br,n,pr,true);g.named=g.named.filter(f=>!f.el.matches(hn));let S=rt(i,yr,n,pr,true);g.named=g.named.filter(({name:f})=>!cn.test(f)),S.named=S.named.filter(({name:f})=>!cn.test(f));let E=rt(i,hn,n,bl,true);o.button=g.unnamed,o.link=S.unnamed,o.field=E.unnamed;let v=t.groupLists&&n?ur([...g.named,...S.named],{textOf:Wl,pathOf:f=>fr(f,i)}):null,b=v?Vl(v,t.maxItems):null;if(v&&b){let f=A=>v.primary.has(A.el)&&!b.has(A.el);g.named=g.named.filter(A=>!f(A)),S.named=S.named.filter(A=>!f(A));for(let A of [...g.named,...S.named]){let y=b.get(A.el);y&&(A.name=y.name);}}let R=it(E.named,m),P=it(g.named,m),C=it(S.named,m),O=Math.min(t.reservedLinks,C.length),K={left:t.maxControls-O},ye=f=>{let A=cl(f.el,i)?0:3;return v?.secondary.has(f.el)?A?7:6:b?.has(f.el)?A:A+(ln(f.el)?2:1)},D=f=>{let A=Math.max(0,K.left),y=f.slice(0,A);if(t.preferVisible&&n&&f.length>A){let w=f.map(T=>({candidate:T,rank:ye(T)}));w.sort((T,N)=>T.rank-N.rank),y=w.slice(0,A).map(({candidate:T})=>T).sort(pn);}return K.left-=y.length,y};for(let{el:f,name:A,namedBy:y,count:w}of D(R))s.push({handle:d(f,"field"),kind:"field",name:A,namedBy:y,fieldType:Tl(f),...Rl(f),...f instanceof HTMLSelectElement&&{options:wl(f)},...w&&{count:w},...mr(f)&&{disabled:true},...tt(f,A)&&{sensitive:true}});for(let{el:f,name:A,namedBy:y,count:w}of D(P)){let T=_l(f,i),N=T?l.get(T):void 0,ie=b?.get(f);s.push({handle:d(f,"button"),kind:"button",name:A,namedBy:y,...ie&&{item:vr(ie)},...N&&{choiceOf:N},...w&&{count:w},...Ee(f)&&{submits:true},...mr(f)&&{disabled:true}});}let at=gr(i.location.pathname),te="";K.left+=O;for(let{el:f,name:A,namedBy:y,count:w}of D(C)){let T=fr(f,i),N=Ol(f,i),ie=T?.includes("?")?T.slice(T.indexOf("?")):"",yn=!!T&&gr(T)===at&&(!ie||ie===i.location.search);yn&&!te&&(te=A);let ut=b?.get(f);s.push({handle:d(f,"link"),kind:"link",name:A,namedBy:y,...ut&&{item:vr(ut)},...w&&{count:w},...T&&!ut&&!N&&{path:Il(T)},...N&&{site:N},...yn&&{current:true}});}let lt=new Map(s.map(f=>[r.get(f.handle),f.handle]));for(let f of Array.from(i.querySelectorAll(ol))){if(!fn(f,n))continue;let A=[];for(let[T,N]of lt)f.contains(T)&&!N.startsWith(hr.section)&&A.push(N);if(A.length===0)continue;let{name:y,namedBy:w}=Ae([["aria",()=>st(f)],["heading",()=>Rr(f)],["section",()=>Pr(f,m)],["id",()=>Q(_(f,"name")||f.id)]]);s.push({handle:d(f,"form"),kind:"form",name:y||"form",namedBy:w,children:A});}let{name:ct,namedBy:ne}=Ll(i,te),I=new Set(s.map(f=>f.item?.list)),M=v?.lists.filter(f=>I.has(f.id))??[],G=[...new Set([...g.covered,...S.covered,...E.covered].filter(f=>!cn.test(f)))].slice(0,nl);return {index:{generation:e,url:i.location.pathname+i.location.search,title:k(i.title,il),pageName:ct||"this",pageNamedBy:ne,nodes:s,unnamed:o,...M.length>0&&{lists:M},...n&&{covered:G}},elements:r}}var Z=0,X=0,ot=null,Gl=()=>{let i=ot;if(ot=null,i==="forward"){Z+=1,X=Math.max(0,X-1);return}i==="back"?X+=1:X=0,Z=Math.max(0,Z-1);},gn={canGo:i=>i==="back"?Z>0:X>0,go(i){ot=i,i==="back"?window.history.back():window.history.forward();}};function vh(i){let e=window.navigation;if(!e)return $l(i);let t=null,n=()=>{t&&clearTimeout(t),t=setTimeout(i,500);};return e.addEventListener("navigatesuccess",n),()=>{t&&clearTimeout(t),e.removeEventListener("navigatesuccess",n);}}function $l(i){if(typeof window>"u")return ()=>{};let e=null,t=()=>{e&&clearTimeout(e),e=setTimeout(i,500);};Z=0,X=0,ot=null;let{pushState:n,replaceState:r}=window.history,s=(d,c)=>function(...p){let m=d.apply(this,p);return c&&(Z+=1,X=0),t(),m},o=()=>{Gl(),t();},a=s(n,true),l=s(r,false);return window.history.pushState=a,window.history.replaceState=l,window.addEventListener("popstate",o),window.addEventListener("hashchange",t),()=>{e&&clearTimeout(e),window.history.pushState===a&&(window.history.pushState=n),window.history.replaceState===l&&(window.history.replaceState=r),window.removeEventListener("popstate",o),window.removeEventListener("hashchange",t);}}var Dr=/^(?:true|yes|y|on|1|check|checked|tick|ticked|select|selected)$/i,Xl=/^(?:false|no|n|off|0|uncheck|unchecked|untick|unticked|deselect)$/i,Kl={date:"dates go in as YYYY-MM-DD",time:"times go in as HH:MM, 24-hour","datetime-local":"a date and time goes in as YYYY-MM-DDTHH:MM",month:"a month goes in as YYYY-MM",week:"a week goes in as YYYY-Www",number:"only a plain number fits",range:"only a plain number fits",color:"a colour goes in as #rrggbb"},Or=i=>i.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim(),Nr=(i,e)=>{let t=i.filter(e);return t.length===1?t[0]:void 0},Fr=(i,e,t)=>{let n=Or(t);if(!n)return;let r=s=>e(s).map(Or);return i.find(s=>r(s).includes(n))??Nr(i,s=>r(s).some(o=>o.startsWith(n)))??Nr(i,s=>r(s).some(o=>o.includes(n)))},jl=(i,e)=>{let t=Object.getPrototypeOf(i),n=Object.getOwnPropertyDescriptor(t,"value")?.set;n?n.call(i,e):i.value=e;},Hr=(i,e)=>{i.focus({preventScroll:true}),jl(i,e),i.dispatchEvent(new Event("input",{bubbles:true})),i.dispatchEvent(new Event("change",{bubbles:true})),i.blur();},Lr=(i,e)=>i.readOnly?{outcome:"read_only"}:(Hr(i,e),e&&i.value===""?{outcome:"rejected",detail:Kl[i.type]}:e&&!i.validity.valid?{outcome:"invalid",detail:i.validationMessage}:{outcome:"ok"}),ql=(i,e)=>{let t=Array.from(i.options).filter(r=>!r.disabled),n=Fr(t,r=>[r.value,r.label||r.text],e);return n?(Hr(i,n.value),{outcome:"ok"}):{outcome:"no_such_option",detail:t.filter(r=>r.value!=="").map(r=>r.label||r.text).join(", ")}},xr=i=>i.labels?.[0]?.textContent?.trim()||i.getAttribute("aria-label")||i.value,zl=(i,e)=>{let t=i.form??i.ownerDocument,n=i.name?Array.from(t.querySelectorAll(`input[type=radio][name="${CSS.escape(i.name)}"]`)):[i],r=Fr(n,s=>[s.value,xr(s)],e)??(Dr.test(e.trim())?i:void 0);return r?r.disabled?{outcome:"disabled"}:(r.checked||r.click(),r.checked?{outcome:"ok"}:{outcome:"rejected"}):{outcome:"no_such_option",detail:n.map(xr).join(", ")}},Yl=(i,e)=>{let t=Dr.test(e.trim())?true:Xl.test(e.trim())?false:void 0;return t===void 0?{outcome:"rejected",detail:'a tick box takes "yes" or "no"'}:(i.checked!==t&&i.click(),i.checked===t?{outcome:"ok"}:{outcome:"rejected"})},Jl=(i,e)=>(i.focus({preventScroll:true}),window.getSelection()?.selectAllChildren(i),(e?document.execCommand("insertText",false,e):document.execCommand("delete"))||(i.textContent=e,i.dispatchEvent(new InputEvent("input",{bubbles:true,inputType:"insertText",data:e}))),i.blur(),{outcome:"ok"}),Br=(i,e)=>i instanceof HTMLSelectElement?ql(i,e):i instanceof HTMLTextAreaElement?Lr(i,e):i instanceof HTMLInputElement?i.type==="radio"?zl(i,e):i.type==="checkbox"?Yl(i,e):i.type==="file"?{outcome:"not_fillable"}:Lr(i,e):i instanceof HTMLElement&&i.isContentEditable?Jl(i,e):{outcome:"not_fillable"},Ql=i=>"willValidate"in i&&i.willValidate,Zl=(i,e)=>{let t=Array.from(i.elements).find(r=>Ql(r)&&!r.validity.valid);if(!t)return;let n=t.validationMessage||"still needs a valid value";return `"${e(t)}": ${n}`},Ur=(i,e,t=false)=>{let n=i.form;if(n&&!n.noValidate&&!i.formNoValidate){let a=Zl(n,e);if(a)return {outcome:"invalid",detail:a}}let r=false,s=false,o=a=>{r=true,s=a.defaultPrevented,t||a.preventDefault();};window.addEventListener("submit",o);try{i.click();}finally{window.removeEventListener("submit",o);}return !r||s||t?{outcome:"ok"}:{outcome:"requires_reload"}};var ec=new Set(["date","time","datetime-local","month","week","color"]),tc=i=>{let e=i.getBoundingClientRect();return {clientX:e.left+e.width/2,clientY:e.top+e.height/2}},be=(i,e,t,n)=>{let r={bubbles:true,cancelable:true,composed:true,view:window,button:0,buttons:n?1:0,...t};return e.startsWith("pointer")?typeof PointerEvent!="function"?true:i.dispatchEvent(new PointerEvent(e,{...r,pointerId:1,pointerType:"mouse",isPrimary:true})):i.dispatchEvent(new MouseEvent(e,r))},vn=i=>{let e=tc(i),t=be(i,"pointerdown",e,true),n=be(i,"mousedown",e,true);t&&n&&i instanceof HTMLElement&&i.focus({preventScroll:true}),be(i,"pointerup",e,false),be(i,"mouseup",e,false),i instanceof HTMLElement?i.click():be(i,"click",e,false);},nc=i=>{if(i instanceof HTMLSelectElement||i instanceof HTMLInputElement&&ec.has(i.type))try{i.showPicker?.();}catch{}},Wr=i=>{vn(i),nc(i);};var ic=.8,rc="l",bn="b",Sn="f",Xr="s",sc=new Set([Xr,bn]),ee=i=>/^([a-z]{1,4})\d{1,4}$/.exec(i)?.[1]??"",oc=/\s+—\s+.*$/,En=i=>i.toLowerCase().replace(/\s+/g," ").trim(),ac=i=>{try{return new URL(i,window.location.href).origin===window.location.origin}catch{return false}},Vr=i=>i.replace(/\/+$/,"")||"/",lc=i=>{try{return Vr(new URL(i,window.location.href).pathname)===Vr(window.location.pathname)}catch{return false}},Gr=(i,e,t)=>{let n=false,r=o=>{n=o.defaultPrevented,e||o.preventDefault();};window.addEventListener("click",r);try{i.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}));}finally{window.removeEventListener("click",r);}if(n||e)return "ok";let s=i.href;return t===void 0||!s?"requires_reload":(setTimeout(()=>window.location.assign(s),t),"ok")},An=i=>i.matches(":disabled")||i.getAttribute("aria-disabled")==="true",cc=new Set(["back","forward"]),Kr=i=>gn.canGo(i)?(gn.go(i),"ok"):"no_history",uc=i=>{let e=window.navigation;return e?(i==="back"?!e.canGoBack:!e.canGoForward)?"no_history":(i==="back"?e.back():e.forward(),"ok"):Kr(i)},dc=()=>{let i=document.documentElement;return {x:Math.max(0,i.scrollWidth-window.innerWidth),y:Math.max(0,i.scrollHeight-window.innerHeight)}},$r=(i,e,t,n)=>{if(!i)return e;if(i.relative){let r=i.percent?n*i.value/100:i.value;return e+r}return i.percent?t*i.value/100:i.value},hc=i=>{let e=dc();if(i.kind==="edge"){let t=i.edge==="top"?0:i.edge==="bottom"?e.y:e.y/2;window.scrollTo({top:t,behavior:"smooth"});return}if(i.kind==="step"){let t=window.innerHeight*ic;window.scrollBy({top:i.direction==="up"?-t:t,behavior:"smooth"});return}window.scrollTo({left:$r(i.x,window.scrollX,e.x,window.innerWidth),top:$r(i.y,window.scrollY,e.y,window.innerHeight),behavior:"smooth"});};function pc(i={}){let e=i.survivesDocumentLoad??false,t=i.indexProfile??mn,n=i.followLinksAnywhere??false,r=i.documentLoadAfterMs,s=null,o=(c,p)=>!s||s.generation!==p?null:s.elements.get(c)??null,a=c=>{let p=s?.elements.get(c);return p?.isConnected?{element:p,isSection:ee(c)===Xr}:null},l=c=>s?.generation===c?"unknown_target":"stale",d=c=>{for(let[p,m]of s?.elements??[])if(m===c)return s?.names.get(p)??p;return c.labels?.[0]?.textContent?.trim()||c.getAttribute("aria-label")||c.getAttribute("placeholder")||c.getAttribute("name")||"a field"};return {elementNamed(c){let p=En(c);if(!s||!p)return null;let m=null;for(let[h,g]of s.names)if(sc.has(ee(h))){if(En(g)===p)return a(h);!m&&En(g.replace(oc,""))===p&&(m=h);}return m?a(m):null},read(c){let{index:p,elements:m}=Cr(document,c,t),h=new Map(p.nodes.map(g=>[g.handle,g.name]));return s={generation:c,elements:m,names:h},p},retag(c){s&&(s.generation=c);},scroll(c,p){let m=tn(c);if(m)return hc(m),"ok";if(p===void 0)return "unknown_target";let h=o(c,p);return h?h.isConnected?(h.scrollIntoView({behavior:"smooth",block:"start"}),"ok"):"stale":l(p)},navigate(c,p){if(cc.has(c)){let S=c;return e?uc(S):Kr(S)}if(p===void 0)return "unknown_target";if(ee(c)!==rc)return "not_navigable";let m=o(c,p);if(!m)return l(p);if(!m.isConnected)return "stale";let h=m.getAttribute("href");if(!h)return "not_navigable";let g=ac(h);return !g&&!n?"not_navigable":g&&lc(h)?"already_here":Gr(m,e,r)},click(c,p){if(p===void 0)return "unknown_target";let m=ee(c);if(m!==bn&&m!==Sn)return "not_clickable";let h=o(c,p);return h?h.isConnected?Ee(h)?"submits_form":An(h)?"disabled":(h.scrollIntoView({behavior:"smooth",block:"center"}),m===Sn?(Wr(h),"ok"):h.closest("a[href]")?Gr(h,e,r)==="ok"?"ok":"requires_reload":(vn(h),"ok")):"stale":l(p)},fill(c,p){let m=false;return c.map(({handle:h,value:g})=>{let S=s?.names.get(h)??h,E=(P,C)=>({handle:h,name:S,outcome:P,...C&&{detail:C}});if(p===void 0)return E("unknown_target");if(ee(h)!==Sn)return E("not_fillable");let v=o(h,p);if(!v)return E(l(p));if(!v.isConnected)return E("stale");if(tt(v,S))return E("sensitive");if(An(v))return E("disabled");m||(v.scrollIntoView({behavior:"smooth",block:"center"}),m=true);let{outcome:b,detail:R}=Br(v,g);return E(b,R)})},submit(c,p){if(p===void 0)return {outcome:"unknown_target"};if(ee(c)!==bn)return {outcome:"not_a_submit"};let m=o(c,p);return m?m.isConnected?Ee(m)?An(m)?{outcome:"disabled"}:(m.scrollIntoView({behavior:"smooth",block:"center"}),Ur(m,d,e)):{outcome:"not_a_submit"}:{outcome:"stale"}:{outcome:l(p)}}}}var Rh=pc();
|
|
4
|
+
export{Yr as A,L as B,Jr as C,$o as D,ji as E,zo as F,Yo as G,Qo as H,Zt as I,ea as J,ta as K,ia as L,en as M,fa as N,nn as O,rn as P,Ea as Q,sn as R,ya as S,_a as T,Ta as U,an as V,fh as W,vh as X,$l as Y,pc as Z,Rh as _,Qr as a,u as b,vt as c,At as d,_t as e,is as f,rs as g,ss as h,os as i,as as j,ls as k,cs as l,us as m,ds as n,Bt as o,se as p,Xn as q,bs as r,wi as s,Pi as t,dt as u,ht as v,pt as w,Jt as x,_n as y,zr as z};
|