@runtypelabs/persona 4.9.0 → 4.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,36 +1,36 @@
1
- var qg=Object.defineProperty;var pr=(e,t)=>()=>(e&&(t=e(e=0)),t);var el=(e,t)=>{for(var n in t)qg(e,n,{get:t[n],enumerable:!0})};var Wd={};el(Wd,{DOMPurify:()=>Kg,Marked:()=>Vg});import{Marked as Vg}from"marked";import Kg from"dompurify";var Hd=pr(()=>{"use strict"});var yr,vl=pr(()=>{"use strict";yr=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let s=n.createBufferSource();s.buffer=o,s.connect(n.destination);let r=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=r:this.nextStartTime<r&&(this.nextStartTime=r,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let r=0;r<n;r++){let a=s.getInt16(r*2,!0);o[r]=a/32768}return o}}});function gh(e){return e.replace(/\/+$/,"")}async function mh(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Ra,Pp=pr(()=>{"use strict";vl();Ra=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new yr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let s=await this.ensurePlayer();if(t!==this.generation)return;s.flush(),s.resume(),s.onStarted(()=>{t===this.generation&&o.onStart?.()}),s.onFinished(()=>{t===this.generation&&o.onEnd?.()});let r=`${gh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await mh(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&s.enqueue(d)}s.markStreamEnd()}catch(s){if(t!==this.generation)return;let r=s instanceof Error?s:new Error(String(s));this.opts.onError?.(r),o.onError?.(r)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Ia,Rp=pr(()=>{"use strict";Ia=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:s=>{if(o){n.onError?.(s);return}this.options.onFallback?.(s),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Ip={};el(Ip,{FallbackSpeechEngine:()=>Ia,RuntypeSpeechEngine:()=>Ra});var Wp=pr(()=>{"use strict";Pp();Rp()});var Bp={};el(Bp,{createReconnectController:()=>yh});function yh(e){let t=0,n=null,o=null,s=!1,r=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},a=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||r()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{s||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),s=!0)},c=()=>{s&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),s=!1)},u=h=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},h)}),y=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let E=e.buildErrorContent("Connection lost and the response could not be resumed.");E?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??hh,C=e.config.reconnect?.maxAttempts??h.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),R=L.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let I=null;try{let _=await E({executionId:L.executionId,after:L.lastEventId,signal:A.signal});_&&_.ok&&_.body&&(I=_.body)}catch{I=null}if(A.signal.aborted)return;if(I){let _=e.getMessages().find(w=>w.id===L.assistantMessageId)?.content,O=typeof _=="string"?_:"";try{await e.resumeConnect(I,L.assistantMessageId,O)}catch{}if(A.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==R&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),A.signal.aborted))return}e.getResumable()&&y()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:r}}var hh,Dp=pr(()=>{"use strict";hh=[1e3,2e3,4e3,8e3,8e3]});import{Marked as Xg}from"marked";import Qg from"dompurify";var ur=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,s=null,r=null;return{setLoader:c=>{o=c,n&&(s=null,r=null)},load:()=>s?Promise.resolve(s):r||(r=(o??t)().then(u=>(s=u,u)).catch(u=>{throw r=null,u}),r),provide:c=>{s=c},getSync:()=>s}};var{setLoader:Sw,load:Gg,provide:Jg,getSync:tl}=ur({fallbackImport:()=>Promise.resolve().then(()=>(Hd(),Wd))}),ga=new Set,Bd=()=>{let e=[...ga];ga.clear();for(let t of e)try{t()}catch{}};var Dd=()=>{let e=tl();return e?Promise.resolve(e):Gg().then(t=>(Bd(),t))},rs=e=>tl()?()=>{}:(ga.add(e),Dd().catch(()=>{}),()=>{ga.delete(e)}),Od=e=>{Jg(e),Bd()},_n=tl;Od({Marked:Xg,DOMPurify:Qg});var Yg=e=>{if(e)return e},ma=e=>{let t=null;return n=>{let o=_n();if(!o)return $n(n);if(!t){let{Marked:s}=o,r=e?.markedOptions;t=new s({gfm:r?.gfm??!0,breaks:r?.breaks??!0,pedantic:r?.pedantic,silent:r?.silent});let a=Yg(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},fr=e=>e?ma({markedOptions:e.options,renderer:e.renderer}):ma(),Zg=ma(),Fd=e=>Zg(e),$n=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),_d=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Nd=e=>`%%FORM_PLACEHOLDER_${e}%%`,$d=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,s)=>{try{let r=JSON.parse(s.trim());if(r&&typeof r=="object"&&r.component==="form"&&r.type){let a=Nd(t.length);return t.push({token:a,type:String(r.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,s)=>{let r=Nd(t.length);return t.push({token:r,type:s}),r}),n},em=e=>{let t=fr(e);return n=>{let o=[],s=$d(n,o),r=t(s);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${_d(i)}"></div>`;r=r.replace(p,c)}),r}},tm=e=>{let t=[],n=$d(e,t),o=Fd(n);return t.forEach(({token:s,type:r})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${_d(r)}"></div>`;o=o.replace(a,p)}),o};var nm={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},om=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,jd=()=>{let e=null;return t=>{let n=_n();if(!n)return $n(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(s,r)=>{if(r.attrName==="src"||r.attrName==="href"){let a=r.attrValue;a.toLowerCase().startsWith("data:")&&!om.test(a)&&(r.attrValue="",r.keepAttr=!1)}})}return e.sanitize(t,nm)}},ss=e=>e===!1?null:typeof e=="function"?e:jd();var Ud=/^\s*\|?[\s:|-]*-[\s:|-]*$/,zd=e=>e.includes("|"),qd=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},rm=e=>`| ${e.join(" | ")} |`,sm=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,am=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Vd=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let o=0;o<t.length-1;o++){let s=t[o],r=t[o+1];if(!zd(s)||Ud.test(s)||!Ud.test(r))continue;let a=qd(s).length;if(a<1)continue;let i=sm(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!zd(d))break;let c=rm(am(qd(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
- `):e};var Mn="webmcp:",nl=new Map,Kd=e=>{nl.clear();for(let t of e){let n=t.title?.trim();n&&nl.set(t.name,n)}},is=e=>nl.get(ol(e)),ha={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Gd=null;function Xd(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${im(t.join(""))}`}function Jd(e,t){let n=3735928559^t,o=1103547991^t;for(let s=0;s<e.length;s++){let r=e.charCodeAt(s);n=Math.imul(n^r,2654435761),o=Math.imul(o^r,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function im(e){let t=Jd(e,0).toString(36),n=Jd(e,2654435761).toString(36);return`${t}.${n}`}var as=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}Kd(n);let o=typeof location<"u"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let r={name:s.name,description:s.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=cm(s.inputSchema);return a&&(r.parametersSchema=a),r})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Cn("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let h=typeof document<"u"&&!!document.modelContext;return Cn(h?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let r=ol(t),a;try{a=await s.getTools()}catch(h){let C=h instanceof Error?h.message:String(h);return Cn(`Failed to read WebMCP registry: ${C}`)}Kd(a);let i=a.find(h=>h.name===r);if(!i)return Cn(`WebMCP tool not registered on this page: ${r}`);if(!this.passesClientAllowlist(r))return Cn(`WebMCP tool not allowed by client allowlist: ${r}`);if(o?.aborted)return Cn("Aborted by cancel()");let p=is(r),d={toolName:r,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Cn("User declined the tool call.");if(o?.aborted)return Cn("Aborted by cancel()");let c=new AbortController,u=!1,y=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await s.executeTool(i,fm(n),{signal:c.signal});return dm(h)}catch(h){if(u)return Cn(`WebMCP tool '${r}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Cn("Aborted by cancel()");let C=h instanceof Error?h.message:String(h);return Cn(C)}finally{clearTimeout(y),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Gd?await Gd():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??pm;try{return await n(t)}catch(o){return ha.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>lm(t,o))}},ol=e=>e.startsWith(Mn)?e.slice(Mn.length):e,No=e=>e.startsWith(Mn),lm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},cm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},dm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:gm(t)}]}},Cn=e=>({isError:!0,content:[{type:"text",text:e}]}),pm=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=um(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var Gg=Object.defineProperty;var pr=(e,t)=>()=>(e&&(t=e(e=0)),t);var nl=(e,t)=>{for(var n in t)Gg(e,n,{get:t[n],enumerable:!0})};var Hd={};nl(Hd,{DOMPurify:()=>Xg,Marked:()=>Jg});import{Marked as Jg}from"marked";import Xg from"dompurify";var Bd=pr(()=>{"use strict"});var yr,Cl=pr(()=>{"use strict";yr=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let s=n.createBufferSource();s.buffer=o,s.connect(n.destination);let r=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=r:this.nextStartTime<r&&(this.nextStartTime=r,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let r=0;r<n;r++){let a=s.getInt16(r*2,!0);o[r]=a/32768}return o}}});function yh(e){return e.replace(/\/+$/,"")}async function bh(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Ra,Rp=pr(()=>{"use strict";Cl();Ra=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new yr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let s=await this.ensurePlayer();if(t!==this.generation)return;s.flush(),s.resume(),s.onStarted(()=>{t===this.generation&&o.onStart?.()}),s.onFinished(()=>{t===this.generation&&o.onEnd?.()});let r=`${yh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await bh(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&s.enqueue(d)}s.markStreamEnd()}catch(s){if(t!==this.generation)return;let r=s instanceof Error?s:new Error(String(s));this.opts.onError?.(r),o.onError?.(r)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Ia,Ip=pr(()=>{"use strict";Ia=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:s=>{if(o){n.onError?.(s);return}this.options.onFallback?.(s),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Wp={};nl(Wp,{FallbackSpeechEngine:()=>Ia,RuntypeSpeechEngine:()=>Ra});var Hp=pr(()=>{"use strict";Rp();Ip()});var Dp={};nl(Dp,{createReconnectController:()=>xh});function xh(e){let t=0,n=null,o=null,s=!1,r=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},a=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||r()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{s||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),s=!0)},c=()=>{s&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),s=!1)},u=h=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},h)}),y=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let E=e.buildErrorContent("Connection lost and the response could not be resumed.");E?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??vh,C=e.config.reconnect?.maxAttempts??h.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),R=L.lastEventId,A=new AbortController;e.setAbortController(A),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let I=null;try{let _=await E({executionId:L.executionId,after:L.lastEventId,signal:A.signal});_&&_.ok&&_.body&&(I=_.body)}catch{I=null}if(A.signal.aborted)return;if(I){let _=e.getMessages().find(w=>w.id===L.assistantMessageId)?.content,O=typeof _=="string"?_:"";try{await e.resumeConnect(I,L.assistantMessageId,O)}catch{}if(A.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==R&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),A.signal.aborted))return}e.getResumable()&&y()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:r}}var vh,Op=pr(()=>{"use strict";vh=[1e3,2e3,4e3,8e3,8e3]});import{Marked as Zg}from"marked";import em from"dompurify";var ur=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,s=null,r=null;return{setLoader:c=>{o=c,n&&(s=null,r=null)},load:()=>s?Promise.resolve(s):r||(r=(o??t)().then(u=>(s=u,u)).catch(u=>{throw r=null,u}),r),provide:c=>{s=c},getSync:()=>s}};var{setLoader:kw,load:Qg,provide:Yg,getSync:ol}=ur({fallbackImport:()=>Promise.resolve().then(()=>(Bd(),Hd))}),ga=new Set,Dd=()=>{let e=[...ga];ga.clear();for(let t of e)try{t()}catch{}};var Od=()=>{let e=ol();return e?Promise.resolve(e):Qg().then(t=>(Dd(),t))},rs=e=>ol()?()=>{}:(ga.add(e),Od().catch(()=>{}),()=>{ga.delete(e)}),Nd=e=>{Yg(e),Dd()},_n=ol;Nd({Marked:Zg,DOMPurify:em});var tm=e=>{if(e)return e},ma=e=>{let t=null;return n=>{let o=_n();if(!o)return $n(n);if(!t){let{Marked:s}=o,r=e?.markedOptions;t=new s({gfm:r?.gfm??!0,breaks:r?.breaks??!0,pedantic:r?.pedantic,silent:r?.silent});let a=tm(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},fr=e=>e?ma({markedOptions:e.options,renderer:e.renderer}):ma(),nm=ma(),_d=e=>nm(e),$n=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),$d=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Fd=e=>`%%FORM_PLACEHOLDER_${e}%%`,jd=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,s)=>{try{let r=JSON.parse(s.trim());if(r&&typeof r=="object"&&r.component==="form"&&r.type){let a=Fd(t.length);return t.push({token:a,type:String(r.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,s)=>{let r=Fd(t.length);return t.push({token:r,type:s}),r}),n},om=e=>{let t=fr(e);return n=>{let o=[],s=jd(n,o),r=t(s);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${$d(i)}"></div>`;r=r.replace(p,c)}),r}},rm=e=>{let t=[],n=jd(e,t),o=_d(n);return t.forEach(({token:s,type:r})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${$d(r)}"></div>`;o=o.replace(a,p)}),o};var sm={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},am=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ud=()=>{let e=null;return t=>{let n=_n();if(!n)return $n(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(s,r)=>{if(r.attrName==="src"||r.attrName==="href"){let a=r.attrValue;a.toLowerCase().startsWith("data:")&&!am.test(a)&&(r.attrValue="",r.keepAttr=!1)}})}return e.sanitize(t,sm)}},ss=e=>e===!1?null:typeof e=="function"?e:Ud();var zd=/^\s*\|?[\s:|-]*-[\s:|-]*$/,qd=e=>e.includes("|"),Vd=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},im=e=>`| ${e.join(" | ")} |`,lm=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,cm=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Kd=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let o=0;o<t.length-1;o++){let s=t[o],r=t[o+1];if(!qd(s)||zd.test(s)||!zd.test(r))continue;let a=Vd(s).length;if(a<1)continue;let i=lm(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!qd(d))break;let c=im(cm(Vd(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
+ `):e};var Mn="webmcp:",rl=new Map,Gd=e=>{rl.clear();for(let t of e){let n=t.title?.trim();n&&rl.set(t.name,n)}},is=e=>rl.get(sl(e)),ha={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Jd=null;function Qd(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${dm(t.join(""))}`}function Xd(e,t){let n=3735928559^t,o=1103547991^t;for(let s=0;s<e.length;s++){let r=e.charCodeAt(s);n=Math.imul(n^r,2654435761),o=Math.imul(o^r,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function dm(e){let t=Xd(e,0).toString(36),n=Xd(e,2654435761).toString(36);return`${t}.${n}`}var as=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}Gd(n);let o=typeof location<"u"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let r={name:s.name,description:s.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=um(s.inputSchema);return a&&(r.parametersSchema=a),r})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Cn("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let h=typeof document<"u"&&!!document.modelContext;return Cn(h?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let r=sl(t),a;try{a=await s.getTools()}catch(h){let C=h instanceof Error?h.message:String(h);return Cn(`Failed to read WebMCP registry: ${C}`)}Gd(a);let i=a.find(h=>h.name===r);if(!i)return Cn(`WebMCP tool not registered on this page: ${r}`);if(!this.passesClientAllowlist(r))return Cn(`WebMCP tool not allowed by client allowlist: ${r}`);if(o?.aborted)return Cn("Aborted by cancel()");let p=is(r),d={toolName:r,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Cn("User declined the tool call.");if(o?.aborted)return Cn("Aborted by cancel()");let c=new AbortController,u=!1,y=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await s.executeTool(i,hm(n),{signal:c.signal});return fm(h)}catch(h){if(u)return Cn(`WebMCP tool '${r}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Cn("Aborted by cancel()");let C=h instanceof Error?h.message:String(h);return Cn(C)}finally{clearTimeout(y),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Jd?await Jd():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??gm;try{return await n(t)}catch(o){return ha.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>pm(t,o))}},sl=e=>e.startsWith(Mn)?e.slice(Mn.length):e,No=e=>e.startsWith(Mn),pm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},um=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},fm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:ym(t)}]}},Cn=e=>({isError:!0,content:[{type:"text",text:e}]}),gm=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=mm(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
4
4
 
5
5
  Arguments:
6
6
  ${t}`:"")+(e.description?`
7
7
 
8
- ${e.description}`:"");return window.confirm(n)},um=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},fm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},gm=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Fo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function ya(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var mm="agent_",hm="flow_";function Qd(e){return e.startsWith(mm)?{kind:"agentId",agentId:e}:e.startsWith(hm)?{kind:"flowId",flowId:e}:null}function Yd(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=Qd(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let s=Qd(n);if(s)return s;let r=t?.default;if(r)return{kind:"payload",payload:r(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as ym,ARR as bm,OBJ as vm,STR as xm}from"partial-json";var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},kn=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},Zd=()=>document.createDocumentFragment(),_e=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[r,a]of Object.entries(t.attrs))o.setAttribute(r,a);if(t.style){let r=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(r[i]=p)}}let s=n.filter(r=>r!=null);return s.length>0&&o.append(...s),o},jn=(...e)=>e.filter(Boolean).join(" ");var ba="ask_user_question",ls=8,gr="data-persona-ask-sheet-for",Cm="Other",wm="Other\u2026",tp="Type your own answer here",np="Send",Am="Next",Sm="Back",Tm="Submit all",Em="Skip",Mm=3,rl="data-ask-current-index",sl="data-ask-question-count",op="data-ask-answers",al="data-ask-grouped",rp="data-ask-layout",km=e=>e.layout==="pills"?"pills":"rows",Lm=e=>e.getAttribute(rp)==="pills"?"pills":"rows",ep=!1,sp=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ba,va=e=>e?.features?.askUserQuestion??{},ro=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let s=o.join(""),r=ym(s,xm|vm|bm);if(r&&typeof r=="object")return{payload:r,complete:n}}catch{}return{payload:null,complete:n}},cs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ls&&!ep&&(ep=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ls}.`)),t.slice(0,ls)},Pm=e=>cs(e)[0]??null,Rm=(e,t)=>cs(e)[t]??null,ap=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ip=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let s=m("span","persona-ask-row-check");o.appendChild(s)}else{let s=m("span","persona-ask-row-badge");s.textContent=String(n+1),o.appendChild(s)}return o},Im=(e,t,n,o)=>{let r=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(r.type="button",r.setAttribute("role",o?"checkbox":"button"),r.setAttribute("aria-pressed","false"),r.setAttribute("data-ask-user-action","pick"),r.setAttribute("data-option-index",String(t)),r.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=m("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}r.appendChild(a);let p=ip(n,o,t);p&&r.appendChild(p)}else r.textContent=e.label,e.description&&(r.title=e.description);return r},Wm=e=>{let n=m("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Hm=(e,t,n,o)=>{let r=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");r.setAttribute("role","group"),r.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Mm;c++)r.appendChild(Wm(o));return r}if(p.forEach((c,u)=>{r.appendChild(Im(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Cm:wm;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let y=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??tp,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),y.appendChild(f),u.appendChild(y);let h=ip(o,a,p.length);h&&u.appendChild(h),r.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,r.appendChild(u)}}return r},lp=(e,t)=>{let o=m("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=e.freeTextPlaceholder??tp,s.setAttribute("data-ask-free-text-input","true"),o.appendChild(s),t!=="rows"){let r=m("button","persona-ask-free-text-submit persona-pointer-events-auto");r.type="button",r.textContent=e.submitLabel??np,r.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(r)}return o},Bm=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??np,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Dm=(e,t,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let s=m("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=n.backLabel??Sm,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,o.appendChild(s);let r=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Em,a.setAttribute("data-ask-user-action","skip"),r.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??Tm:n.nextLabel??Am,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,r.appendChild(i),o.appendChild(r),o},_o=e=>{let t=e.getAttribute(op);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cp=(e,t)=>{e.setAttribute(op,JSON.stringify(t))},fn=e=>{let t=Number(e.getAttribute(rl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Om=(e,t)=>{e.setAttribute(rl,String(Math.max(0,Math.floor(t))))},mr=e=>{let t=Number(e.getAttribute(sl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},so=e=>e.getAttribute(al)==="true",Nm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,r)=>{let a=typeof s?.question=="string"?s.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[r]=i)}}),o},Fm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},xa=(e,t)=>{let{payload:n}=ro(t),o=cs(n),s=_o(e),r={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(s,p)&&(r[d]=s[p]))}),r},dp=e=>{let t=_o(e),n=fn(e),o=t[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(p=>s.add(p));let r=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');r.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=s.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(r).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},pp=e=>{if(!so(e))return;let t=_o(e),n=fn(e),o=t[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,r=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');r&&(r.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},il=(e,t,n)=>{let o=va(n),s=Lm(e),{payload:r,complete:a}=ro(t),i=so(e),p=fn(e),d=mr(e),c=i?Rm(r,p):Pm(r),u=!!c?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let R=typeof c?.question=="string"?c.question:"";h.textContent=R,h.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let R=Hm(c,o,a,s);C.replaceWith(R)}if(s!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(lp(o,s))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(Bm(o)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=Dm(p,d,o);L?L.replaceWith(R):e.appendChild(R)}else L&&L.remove();dp(e),pp(e)},_m=(e,t,n)=>{let o=va(t),s=km(o),r=e.toolCall.id,a=cs(n),i=Math.max(1,a.length),p=i>1,d=Nm(e,a),c=p?Fm(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(gr,r),u.setAttribute("data-tool-call-id",r),u.setAttribute("data-message-id",e.id),u.setAttribute(sl,String(i)),u.setAttribute(rl,String(c)),u.setAttribute(al,p?"true":"false"),u.setAttribute(rp,s),cp(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),ap(u,o);let y=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",y.appendChild(f);let h=m("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",y.appendChild(h),u.appendChild(y);let E=m("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),s!=="rows"&&u.appendChild(lp(o,s)),il(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},$m=(e,t,n)=>{let{payload:o}=ro(t),s=Math.max(1,cs(o).length);s>mr(e)&&(e.setAttribute(sl,String(s)),s>1&&!so(e)&&e.setAttribute(al,"true")),il(e,t,n)},jm=(e,t)=>{let n=m("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=va(t);ap(n,o);let s=m("span","persona-ask-stub-label"),{complete:r}=ro(e);return s.textContent=r?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},ds=(e,t,n)=>{if(!n||!oo(e)||va(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${gr}]`).forEach(d=>{d.getAttribute(gr)!==s&&d.remove()});let a=n.querySelector(`[${gr}="${sp(s)}"]`);if(a){$m(a,e,t);return}let{payload:i}=ro(e),p=_m(e,t,i);n.appendChild(p)},$o=(e,t)=>{if(!e)return;let n=t?`[${gr}="${sp(t)}"]`:`[${gr}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let r=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(r)?r:180)})},ll=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ao=(e,t)=>{let n=_o(e),o=fn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,cp(e,n),dp(e),pp(e)},Ca=(e,t,n,o)=>{let s=mr(e),r=Math.max(0,Math.min(s-1,o));Om(e,r),il(e,t,n)};var Ln="suggest_replies";var up={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},cl={name:Ln,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:up,origin:"sdk",annotations:{readOnlyHint:!0}},dl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),wa=e=>e.variant==="tool"&&e.toolCall?.name===Ln,fp=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},pl=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!wa(n))continue;let o=fp(n.toolCall?.args);return o.length>0?o:null}return null},gp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var mp={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ls,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},hp={name:ba,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:mp,origin:"sdk",annotations:{readOnlyHint:!0}},ps=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(hp),gp(e)&&t.push(cl),t};import{parse as yp,STR as bp,OBJ as vp}from"partial-json";var Aa=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),io=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Um=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},xp=e=>e.status==="complete"?Um(e):e.status==="pending"?"Waiting":"",zm=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Cp=e=>e.status==="complete"?zm(e):"Using tool...",Sa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},fs=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Sa(t)},Ta=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Sa(t)},ul=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",s=fs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,s)},Ea=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,r=0,a;for(;(a=s.exec(n))!==null;)a.index>r&&us(o,n.slice(r,a.index),[]),a[1]!==void 0?us(o,a[1],["bold"]):a[2]!==void 0?us(o,a[2],["italic"]):a[3]!==void 0&&us(o,a[3],["dim"]),r=a.index+a[0].length;return r<n.length&&us(o,n.slice(r),[]),o},us=(e,t,n)=>{let o=t.split("{duration}");for(let s=0;s<o.length;s++)o[s]&&e.push({text:o[s],styles:n}),s<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},qm=()=>{let e=null,t=0,n=o=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,r=o.match(s);if(r&&r[1])try{return r[1].replace(/\\n/g,`
8
+ ${e.description}`:"");return window.confirm(n)},mm=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},hm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ym=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Fo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function ya(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var bm="agent_",vm="flow_";function Yd(e){return e.startsWith(bm)?{kind:"agentId",agentId:e}:e.startsWith(vm)?{kind:"flowId",flowId:e}:null}function Zd(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=Yd(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let s=Yd(n);if(s)return s;let r=t?.default;if(r)return{kind:"payload",payload:r(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as xm,ARR as Cm,OBJ as wm,STR as Am}from"partial-json";var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},kn=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},ep=()=>document.createDocumentFragment(),Ne=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[r,a]of Object.entries(t.attrs))o.setAttribute(r,a);if(t.style){let r=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(r[i]=p)}}let s=n.filter(r=>r!=null);return s.length>0&&o.append(...s),o},jn=(...e)=>e.filter(Boolean).join(" ");var ba="ask_user_question",ls=8,gr="data-persona-ask-sheet-for",Sm="Other",Tm="Other\u2026",np="Type your own answer here",op="Send",Em="Next",Mm="Back",km="Submit all",Lm="Skip",Pm=3,al="data-ask-current-index",il="data-ask-question-count",rp="data-ask-answers",ll="data-ask-grouped",sp="data-ask-layout",Rm=e=>e.layout==="pills"?"pills":"rows",Im=e=>e.getAttribute(sp)==="pills"?"pills":"rows",tp=!1,ap=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ba,va=e=>e?.features?.askUserQuestion??{},ro=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let s=o.join(""),r=xm(s,Am|wm|Cm);if(r&&typeof r=="object")return{payload:r,complete:n}}catch{}return{payload:null,complete:n}},cs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ls&&!tp&&(tp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ls}.`)),t.slice(0,ls)},Wm=e=>cs(e)[0]??null,Hm=(e,t)=>cs(e)[t]??null,ip=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},lp=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let s=m("span","persona-ask-row-check");o.appendChild(s)}else{let s=m("span","persona-ask-row-badge");s.textContent=String(n+1),o.appendChild(s)}return o},Bm=(e,t,n,o)=>{let r=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(r.type="button",r.setAttribute("role",o?"checkbox":"button"),r.setAttribute("aria-pressed","false"),r.setAttribute("data-ask-user-action","pick"),r.setAttribute("data-option-index",String(t)),r.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=m("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}r.appendChild(a);let p=lp(n,o,t);p&&r.appendChild(p)}else r.textContent=e.label,e.description&&(r.title=e.description);return r},Dm=e=>{let n=m("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Om=(e,t,n,o)=>{let r=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");r.setAttribute("role","group"),r.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Pm;c++)r.appendChild(Dm(o));return r}if(p.forEach((c,u)=>{r.appendChild(Bm(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Sm:Tm;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let y=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??np,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),y.appendChild(f),u.appendChild(y);let h=lp(o,a,p.length);h&&u.appendChild(h),r.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,r.appendChild(u)}}return r},cp=(e,t)=>{let o=m("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=e.freeTextPlaceholder??np,s.setAttribute("data-ask-free-text-input","true"),o.appendChild(s),t!=="rows"){let r=m("button","persona-ask-free-text-submit persona-pointer-events-auto");r.type="button",r.textContent=e.submitLabel??op,r.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(r)}return o},Nm=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??op,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Fm=(e,t,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let s=m("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=n.backLabel??Mm,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,o.appendChild(s);let r=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Lm,a.setAttribute("data-ask-user-action","skip"),r.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??km:n.nextLabel??Em,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,r.appendChild(i),o.appendChild(r),o},_o=e=>{let t=e.getAttribute(rp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},dp=(e,t)=>{e.setAttribute(rp,JSON.stringify(t))},un=e=>{let t=Number(e.getAttribute(al)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},_m=(e,t)=>{e.setAttribute(al,String(Math.max(0,Math.floor(t))))},mr=e=>{let t=Number(e.getAttribute(il)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},so=e=>e.getAttribute(ll)==="true",$m=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,r)=>{let a=typeof s?.question=="string"?s.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[r]=i)}}),o},jm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},xa=(e,t)=>{let{payload:n}=ro(t),o=cs(n),s=_o(e),r={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(s,p)&&(r[d]=s[p]))}),r},pp=e=>{let t=_o(e),n=un(e),o=t[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(p=>s.add(p));let r=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');r.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=s.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(r).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},up=e=>{if(!so(e))return;let t=_o(e),n=un(e),o=t[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,r=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');r&&(r.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},cl=(e,t,n)=>{let o=va(n),s=Im(e),{payload:r,complete:a}=ro(t),i=so(e),p=un(e),d=mr(e),c=i?Hm(r,p):Wm(r),u=!!c?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let R=typeof c?.question=="string"?c.question:"";h.textContent=R,h.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let R=Om(c,o,a,s);C.replaceWith(R)}if(s!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(cp(o,s))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(Nm(o)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=Fm(p,d,o);L?L.replaceWith(R):e.appendChild(R)}else L&&L.remove();pp(e),up(e)},Um=(e,t,n)=>{let o=va(t),s=Rm(o),r=e.toolCall.id,a=cs(n),i=Math.max(1,a.length),p=i>1,d=$m(e,a),c=p?jm(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(gr,r),u.setAttribute("data-tool-call-id",r),u.setAttribute("data-message-id",e.id),u.setAttribute(il,String(i)),u.setAttribute(al,String(c)),u.setAttribute(ll,p?"true":"false"),u.setAttribute(sp,s),dp(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),ip(u,o);let y=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",y.appendChild(f);let h=m("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",y.appendChild(h),u.appendChild(y);let E=m("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),s!=="rows"&&u.appendChild(cp(o,s)),cl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},zm=(e,t,n)=>{let{payload:o}=ro(t),s=Math.max(1,cs(o).length);s>mr(e)&&(e.setAttribute(il,String(s)),s>1&&!so(e)&&e.setAttribute(ll,"true")),cl(e,t,n)},qm=(e,t)=>{let n=m("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=va(t);ip(n,o);let s=m("span","persona-ask-stub-label"),{complete:r}=ro(e);return s.textContent=r?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},ds=(e,t,n)=>{if(!n||!oo(e)||va(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${gr}]`).forEach(d=>{d.getAttribute(gr)!==s&&d.remove()});let a=n.querySelector(`[${gr}="${ap(s)}"]`);if(a){zm(a,e,t);return}let{payload:i}=ro(e),p=Um(e,t,i);n.appendChild(p)},$o=(e,t)=>{if(!e)return;let n=t?`[${gr}="${ap(t)}"]`:`[${gr}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let r=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(r)?r:180)})},dl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ao=(e,t)=>{let n=_o(e),o=un(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,dp(e,n),pp(e),up(e)},Ca=(e,t,n,o)=>{let s=mr(e),r=Math.max(0,Math.min(s-1,o));_m(e,r),cl(e,t,n)};var Ln="suggest_replies";var fp={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},pl={name:Ln,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:fp,origin:"sdk",annotations:{readOnlyHint:!0}},ul=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),wa=e=>e.variant==="tool"&&e.toolCall?.name===Ln,gp=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},fl=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!wa(n))continue;let o=gp(n.toolCall?.args);return o.length>0?o:null}return null},mp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var hp={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ls,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},yp={name:ba,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:hp,origin:"sdk",annotations:{readOnlyHint:!0}},ps=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(yp),mp(e)&&t.push(pl),t};import{parse as bp,STR as vp,OBJ as xp}from"partial-json";var Aa=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),io=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Vm=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Cp=e=>e.status==="complete"?Vm(e):e.status==="pending"?"Waiting":"",Km=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var wp=e=>e.status==="complete"?Km(e):"Using tool...",Sa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},fs=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Sa(t)},Ta=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Sa(t)},gl=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",s=fs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,s)},Ea=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,r=0,a;for(;(a=s.exec(n))!==null;)a.index>r&&us(o,n.slice(r,a.index),[]),a[1]!==void 0?us(o,a[1],["bold"]):a[2]!==void 0?us(o,a[2],["italic"]):a[3]!==void 0&&us(o,a[3],["dim"]),r=a.index+a[0].length;return r<n.length&&us(o,n.slice(r),[]),o},us=(e,t,n)=>{let o=t.split("{duration}");for(let s=0;s<o.length;s++)o[s]&&e.push({text:o[s],styles:n}),s<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Gm=()=>{let e=null,t=0,n=o=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,r=o.match(s);if(r&&r[1])try{return r[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return r[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let s=o.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let r=n(o);return r!==null&&(e=r),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},gs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},gl=()=>{let e=qm();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},ml=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=yp(n,bp|vp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Aa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Aa(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Vm=e=>{let t=null,n=0,s=e||(r=>{if(!r||typeof r!="object")return null;let a=i=>typeof i=="string"?Aa(i):null;if(r.component&&typeof r.component=="string")return typeof r.text=="string"?Aa(r.text):"";if(r.type==="init"&&r.form)return"";if(r.action)switch(r.action){case"nav_then_click":return a(r.on_load_text)||a(r.text)||null;case"message":case"message_and_click":case"checkout":return a(r.text)||null;default:return a(r.text)||a(r.display_text)||a(r.message)||null}return a(r.text)||a(r.display_text)||a(r.message)||a(r.content)||null});return{getExtractedText:()=>t,processChunk:r=>{let a=r.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let i=yp(r,bp|vp),p=s(i);p!==null&&(t=p)}catch{}return n=r.length,{text:t||"",raw:r}},close:()=>{}}},hl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var wp="4.9.0";var wn=wp;var Gm="https://api.runtype.com/v1/dispatch",Ma="https://api.runtype.com";function Jm(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let s=t.indexOf("/");if(s>0){let r=t.slice(s+1).split(";")[0]?.trim()??"";if(r&&r!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(r))return`attachment.${r}`}return"attachment"}var yl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Xm(e){switch(e){case"json":return ml;case"regex-json":return gl;case"xml":return hl;default:return fl}}var Ap=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Qm(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let s=Ap(n);if(!Ap(o))return e;if(!s||o===n||o.startsWith(n))return t;let a=gs(e);return gs(t)!==null&&a===null?t:e}var hr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Gm,this.headers={"Content-Type":"application/json","X-Persona-Version":wn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Xm(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new as(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:t,flowId:n};let r=Yd(o,s);return r.kind==="agentId"?{agentId:r.agentId}:r.kind==="flowId"?{flowId:r.flowId}:{targetPayload:r.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,s={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":wn},body:JSON.stringify(s)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s={...t,...this.config.clientToken&&{token:this.config.clientToken}},r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":wn},body:JSON.stringify(s)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let s=await this.buildPayload(t.messages),r=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(yl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...r&&Object.keys(r).length>0&&{metadata:r},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,s.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":wn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(i.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let s=o instanceof Error?o:new Error(String(o));throw!s.message.includes("Session expired")&&!s.message.includes("Message limit")&&n({type:"error",error:s}),s}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Chat backend request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Agent execution request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,s){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let s=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(s,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,s){let r=!!(n&&n.length>0),a=r?Xd(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=r&&i&&this.lastSentClientToolsFingerprint===a,d=!r&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let y=0;;y++){if(u=await o({...r&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&y===0&&r&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,r?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let s=this.isClientTokenMode(),r=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ma}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),s&&a){let d=[...ps(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,y=>{let f={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(r,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(r,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async s=>{try{let r=await s({messages:t,config:this.config});r&&typeof r=="object"&&Object.assign(n,r)}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",r)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(yl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),s={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...ps(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];r.length>0&&(s.clientTools=r);let a=await this.buildContextAggregate(t);return a&&(s.context=a),s}async buildPayload(t){let n=t.slice().filter(yl).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),s={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(s[i]=p);let r=[...ps(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];r.length>0&&(s.clientTools=r);let a=await this.buildContextAggregate(t);if(a&&(s.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...s},config:this.config});if(i&&typeof i=="object"){let p=i;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return s}async handleCustomSSEEvent(t,n,o,s,r,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:r(),...c!==void 0&&{partId:c}};return o.current=u,s(u),u},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,s(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,s(c)}return i.done&&(o.current&&(o.current.streaming=!1,s(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,s){let r=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=M=>{let J=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,x=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,T=M.tools?M.tools.map(k=>({...k,chunks:k.chunks?[...k.chunks]:void 0})):void 0;return{...M,reasoning:J,toolCall:x,tools:T}},y=M=>{if(M.role!=="assistant"||M.variant)return!0;let J=Array.isArray(M.contentParts)&&M.contentParts.length>0,x=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||J||x||!!M.stopReason},f=M=>{y(M)&&n({type:"message",message:u(M)})},h=null,C=null,E={current:null},L={current:null},R=null,A="",I=new Map,_=new Map,O=new Map,w=new Map,U=new Map,q={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},D=M=>{if(M==null)return null;try{return String(M)}catch{return null}},j=M=>D(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),ge=M=>D(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ye=o,Ee=!1,De=()=>{if(h)return h;let M,J="",x=R;return!Ee&&ye?(M=ye,Ee=!0,J=s??""):ye&&x?M=`${ye}_${x}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:M,role:"assistant",content:J,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},se=(M,J)=>{q.lastId=J,M&&q.byStep.set(M,J)},be=(M,J)=>{let x=M.reasoningId??M.id,T=j(M);if(x){let H=String(x);return se(T,H),H}if(T){let H=q.byStep.get(T);if(H)return q.lastId=H,H}if(q.lastId&&!J)return q.lastId;if(!J)return null;let k=`reason-${c()}`;return se(T,k),k},Y=M=>{let J=w.get(M);if(J)return J;let x={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return w.set(M,x),f(x),x},ce=(M,J)=>{Q.lastId=J,M&&Q.byCall.set(M,J)},Z=new Set,xe=new Map,me=new Set,ue=new Map,Pe=M=>{if(!M)return!1;let J=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return J==="emit_artifact_markdown"||J==="emit_artifact_component"},Oe=(M,J)=>{let x=M.toolId??M.id,T=ge(M);if(x){let H=String(x);return ce(T,H),H}if(T){let H=Q.byCall.get(T);if(H)return Q.lastId=H,H}if(Q.lastId&&!J)return Q.lastId;if(!J)return null;let k=`tool-${c()}`;return ce(T,k),k},Ue=M=>{let J=U.get(M);if(J)return J;let x={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return U.set(M,x),f(x),x},Ne=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let J=Number(M);if(!Number.isNaN(J)&&Number.isFinite(J))return J;let x=Date.parse(M);if(!Number.isNaN(x))return x}return Date.now()},we=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Le=new Map,ot=new Map,ie=new Map,Re=(M,J,x)=>{let T=ie.get(M);T||(T=[],ie.set(M,T));let k=0,H=T.length;for(;k<H;){let B=k+H>>>1;T[B].seq<J?k=B+1:H=B}T[k]?.seq===J?T[k]={seq:J,text:x}:T.splice(k,0,{seq:J,text:x});let G="";for(let B=0;B<T.length;B++)G+=T[B].text;return G},xt=(M,J)=>{let x=we(J),T=ot.get(M.id),k=Qm(T,x);M.rawContent=k;let H=Le.get(M.id),G=Te=>{let ct=M.content??"";Te.trim()!==""&&(ct.trim().length===0||Te.startsWith(ct)||Te.trimStart().startsWith(ct.trim()))&&(M.content=Te)},B=()=>{if(H){let Te=H.close?.();Te instanceof Promise&&Te.catch(()=>{})}Le.delete(M.id),ot.delete(M.id),M.streaming=!1,f(M)};if(!H){G(x),B();return}let z=gs(k);if(z!==null&&z.trim()!==""){G(z),B();return}let ae=Te=>{let ct=typeof Te=="string"?Te:Te?.text??null;if(ct!==null&&ct.trim()!=="")return ct;let V=H.getExtractedText();return V!==null&&V.trim()!==""?V:x},tt;try{tt=H.processChunk(k)}catch{G(x),B();return}if(tt instanceof Promise){tt.then(Te=>{G(ae(Te)),B()}).catch(()=>{G(x),B()});return}G(ae(tt)),B()},yt=null,rt=(M,J,x,T)=>{M.rawContent=J,Le.has(M.id)||Le.set(M.id,this.createStreamParser());let k=Le.get(M.id),H=J.trim().startsWith("{")||J.trim().startsWith("[");if(H&&ot.set(M.id,J),k.__isPlainTextParser===!0){M.content=T!==void 0?J:M.content+x,ot.delete(M.id),Le.delete(M.id),M.rawContent=void 0,f(M);return}let B=k.processChunk(J);if(B instanceof Promise)B.then(z=>{let ae=typeof z=="string"?z:z?.text??null;ae!==null&&ae.trim()!==""?(M.content=ae,f(M)):!H&&!J.trim().startsWith("<")&&(M.content=T!==void 0?J:M.content+x,ot.delete(M.id),Le.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=T!==void 0?J:M.content+x,ot.delete(M.id),Le.delete(M.id),M.rawContent=void 0,f(M)});else{let z=typeof B=="string"?B:B?.text??null;z!==null&&z.trim()!==""?(M.content=z,f(M)):!H&&!J.trim().startsWith("<")&&(M.content=T!==void 0?J:M.content+x,ot.delete(M.id),Le.delete(M.id),M.rawContent=void 0,f(M))}},Me=(M,J)=>{let x=J??M.content;if(x==null||x===""){M.streaming=!1,f(M);return}let k=ot.get(M.id)??we(x);M.rawContent=k;let H=Le.get(M.id),G=null,B=!1;if(H&&(G=H.getExtractedText(),G===null&&(G=gs(k)),G===null)){let z=H.processChunk(k);z instanceof Promise?(B=!0,z.then(ae=>{let tt=typeof ae=="string"?ae:ae?.text??null;tt!==null&&(M.content=tt,M.streaming=!1,Le.delete(M.id),ot.delete(M.id),f(M))}).catch(()=>{})):G=typeof z=="string"?z:z?.text??null}if(!B){G!==null&&G.trim()!==""?M.content=G:ot.has(M.id)||(M.content=we(x));let z=Le.get(M.id);if(z){let ae=z.close?.();ae instanceof Promise&&ae.catch(()=>{}),Le.delete(M.id)}ot.delete(M.id),M.streaming=!1,f(M)}},he=(M,J,x)=>{let T=_.get(M);if(T)return T;let k={id:`nested-${J}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:J}};return _.set(M,k),f(k),k},lt=[],Ie,fe=new Map,le=0,ve="agent",Ct=!1,N=null,te=null,Fe=new Map,Se=this.config.iterationDisplay??"separate";for(Ie=()=>{for(let M=0;M<lt.length;M++){let J=lt[M].payloadType,x=lt[M].payload;if(!Ct&&ve!=="flow"&&typeof x.stepType=="string"&&(ve="flow"),J==="reasoning_start"){let T=typeof x.id=="string"?x.id:null,k=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(T&&k){I.set(T,k),he(T,k,"reasoning");continue}let H=be(x,!0)??`reason-${c()}`,G=Y(H);G.reasoning=G.reasoning??{id:H,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??Ne(x.startedAt??x.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(J==="reasoning_delta"){let T=typeof x.id=="string"?x.id:null;if(T&&I.has(T)&&_.has(T)){let B=_.get(T),z=x.reasoningText??x.text??x.delta??"";z&&x.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(z)),f(B));continue}let k=be(x,!1)??be(x,!0)??`reason-${c()}`,H=Y(k);H.reasoning=H.reasoning??{id:k,status:"streaming",chunks:[]},H.reasoning.startedAt=H.reasoning.startedAt??Ne(x.startedAt??x.timestamp);let G=x.reasoningText??x.text??x.delta??"";if(G&&x.hidden!==!0){let B=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(B!==void 0){let z=Re(k,B,String(G));H.reasoning.chunks=[z]}else H.reasoning.chunks.push(String(G))}if(H.reasoning.status=x.done?"complete":"streaming",x.done){H.reasoning.completedAt=Ne(x.completedAt??x.timestamp);let B=H.reasoning.startedAt??Date.now();H.reasoning.durationMs=Math.max(0,(H.reasoning.completedAt??Date.now())-B)}H.streaming=H.reasoning.status!=="complete",f(H)}else if(J==="reasoning_complete"){let T=typeof x.id=="string"?x.id:null;if(T&&I.has(T)&&_.has(T)){let z=_.get(T);if(z.reasoning){let ae=typeof x.text=="string"?x.text:"";ae&&z.reasoning.chunks.length===0&&z.reasoning.chunks.push(ae),z.reasoning.status="complete",z.streaming=!1,f(z)}I.delete(T),_.delete(T);continue}let k=be(x,!1)??be(x,!0)??`reason-${c()}`,H=typeof x.text=="string"?x.text:"";!w.get(k)&&(H||x.scope==="loop")&&Y(k);let G=w.get(k);if(G?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),H&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(H),G.reasoning.status="complete",G.reasoning.completedAt=Ne(x.completedAt??x.timestamp);let z=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-z),G.streaming=!1,f(G)}let B=j(x);B&&q.byStep.delete(B)}else if(J==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof x.iteration=="number"&&(le=x.iteration);let T=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??Oe(x,!0)??`tool-${c()}`,k=x.toolName??x.name;if(Pe(k)){Z.add(T);continue}ce(ge(x),T);let H=Ue(T),G=H.toolCall??{id:T,status:"pending"};G.name=k??G.name,G.status="running",x.parameters!==void 0?G.args=x.parameters:x.args!==void 0&&(G.args=x.args),G.startedAt=G.startedAt??Ne(x.startedAt??x.timestamp),G.completedAt=void 0,G.durationMs=void 0,H.toolCall=G,H.streaming=!0,x.executionId&&(H.agentMetadata={executionId:x.executionId,iteration:x.iteration}),f(H)}else if(J==="tool_output_delta"){let T=Oe(x,!1)??Oe(x,!0)??`tool-${c()}`;if(Z.has(T))continue;let k=Ue(T),H=k.toolCall??{id:T,status:"running"};H.startedAt=H.startedAt??Ne(x.startedAt??x.timestamp);let G=x.text??x.delta??x.message??"";G&&(H.chunks=H.chunks??[],H.chunks.push(String(G))),H.status="running",k.toolCall=H,k.streaming=!0;let B=x.agentContext;(B||x.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??x.executionId,iteration:B?.iteration??x.iteration}),f(k)}else if(J==="tool_complete"){let T=Oe(x,!1)??Oe(x,!0)??`tool-${c()}`;if(Z.has(T)){Z.delete(T);continue}let k=Ue(T),H=k.toolCall??{id:T,status:"running"};H.status="complete",x.result!==void 0&&(H.result=x.result),typeof x.duration=="number"&&(H.duration=x.duration),H.completedAt=Ne(x.completedAt??x.timestamp);let G=x.duration??x.executionTime;if(typeof G=="number")H.durationMs=G;else{let ae=H.startedAt??Date.now();H.durationMs=Math.max(0,(H.completedAt??Date.now())-ae)}k.toolCall=H,k.streaming=!1;let B=x.agentContext;(B||x.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??x.executionId,iteration:B?.iteration??x.iteration}),f(k);let z=ge(x);z&&Q.byCall.delete(z)}else if(J==="await"&&x.toolName){let T=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,k=T??x.toolId??`local-${c()}`,H=Ue(k),G=x.toolName,B=x.origin==="webmcp"&&!No(G)?`webmcp:${G}`:G,z=No(B),ae=H.toolCall??{id:k,status:"pending"};ae.name=B,ae.args=x.parameters,ae.status=z?"running":"complete",ae.chunks=ae.chunks??[],ae.startedAt=ae.startedAt??Ne(x.startedAt??x.timestamp??x.awaitedAt),z?(ae.completedAt=void 0,ae.duration=void 0,ae.durationMs=void 0):ae.completedAt=ae.completedAt??ae.startedAt,H.toolCall=ae,H.streaming=!1,H.agentMetadata={...H.agentMetadata,executionId:x.executionId??H.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},f(H)}else if(J==="text_start"){let T=typeof x.id=="string"?x.id:null,k=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(T&&k){I.set(T,k);continue}let H=h;H&&(ve==="flow"?(Me(H),yt=H):(H.streaming=!1,f(H)),h=null),R=typeof x.id=="string"?x.id:R,A=""}else if(J==="text_delta"){let T=typeof x.id=="string"?x.id:null,k=T?I.get(T):void 0;if(T&&k){let G=typeof x.delta=="string"?x.delta:"",B=(O.get(T)??"")+G;if(O.set(T,B),B.trim()==="")continue;let z=he(T,k);z.agentMetadata={...z.agentMetadata,executionId:x.executionId,parentToolId:k},rt(z,B,G,void 0);continue}if(R=typeof x.id=="string"?x.id:R,ve==="flow"){let G=typeof x.delta=="string"?x.delta:"";if(A+=G,A.trim()==="")continue;let B=De();B.agentMetadata={executionId:x.executionId,iteration:x.iteration},rt(B,A,G,void 0),C=B;continue}let H=De();H.content+=x.delta??"",H.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:N??void 0,agentName:te?.agentName},C=H,f(H)}else if(J==="text_complete"){let T=typeof x.id=="string"?x.id:null;if(T&&I.has(T)){let H=_.get(T);H&&Me(H),I.delete(T),O.delete(T),_.delete(T);continue}let k=h;k&&(ve==="flow"?(Me(k),yt=k):((k.content??"")===""&&typeof x.text=="string"&&(k.content=x.text),k.streaming=!1,f(k)),h=null),R=null,A=""}else if(J==="step_complete"){let T=x.stepType,k=x.executionType;if(T==="tool"||k==="context")continue;if(x.success===!1){let H=x.error,G=typeof H=="string"&&H!==""?H:H!=null&&typeof H=="object"&&Reflect.has(H,"message")?String(H.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let B=h;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"});continue}{let H=yt;yt=null;let G=x.stopReason,B=x.result?.response;if(H)G&&(H.stopReason=G),B!=null?xt(H,B):H.streaming!==!1&&(Le.delete(H.id),ot.delete(H.id),H.streaming=!1,f(H));else{let z=B!=null&&B!=="";if(z||G){let ae=De();G&&(ae.stopReason=G),z?Me(ae,B):(ae.streaming=!1,f(ae))}}continue}}else if(J==="execution_start")ve=x.kind==="flow"?"flow":"agent",Ct=!0,ve==="agent"&&(te={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:Ne(x.startedAt)});else if(J==="turn_start"){let T=typeof x.iteration=="number"?x.iteration:le;if(T!==le){if(te&&(te.currentIteration=T),Se==="separate"&&T>1){let k=h;k&&(k.streaming=!1,f(k),Fe.set(T-1,k),h=null)}le=T}N=typeof x.id=="string"?x.id:null,C=null}else if(J==="tool_input_delta"){let T=x.toolCallId??Q.lastId;if(T){let k=U.get(T);k?.toolCall&&(k.toolCall.chunks=k.toolCall.chunks??[],k.toolCall.chunks.push(x.delta??""),f(k))}}else{if(J==="tool_input_complete")continue;if(J==="turn_complete"){let T=x.stopReason,k=h??C;if(T&&k!==null){let H=x.id;(!H||k.agentMetadata?.turnId===H)&&(k.stopReason=T,f(k))}N===x.id&&(N=null)}else if(J==="media_start"){let T=String(x.id);fe.set(T,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(J==="media_delta"){let T=fe.get(String(x.id));T&&typeof x.delta=="string"&&T.parts.push(x.delta)}else if(J==="media_complete"){let T=String(x.id),k=fe.get(T);fe.delete(T);let H=(typeof x.mediaType=="string"?x.mediaType:void 0)??k?.mediaType??"application/octet-stream",G=typeof x.data=="string"?x.data:void 0,B=typeof x.url=="string"?x.url:k&&k.parts.length>0?k.parts.join(""):void 0,z=null;if(G)z={type:"media",data:G,mediaType:H};else if(B){let ct=H.toLowerCase();z={type:ct==="image"||ct.startsWith("image/")?"image-url":"file-url",url:B,mediaType:H}}let ae=x.toolCallId??k?.toolCallId,tt=z?[z]:[],Te=[];for(let ct of tt){if(!ct||typeof ct!="object")continue;let V=ct,ze=typeof V.type=="string"?V.type:void 0,We=typeof V.mediaType=="string"?V.mediaType.toLowerCase():"",He=null,ke="";if(ze==="media"){let Qe=typeof V.data=="string"?V.data:void 0;if(!Qe)continue;ke=We.length>0?We:"application/octet-stream",He=`data:${ke};base64,${Qe}`}else if(ze==="image-url"){let Qe=typeof V.url=="string"?V.url:void 0;if(!Qe)continue;ke=We,He=Qe}else if(ze==="file-url"){let Qe=typeof V.url=="string"?V.url:void 0;if(!Qe)continue;ke=We,He=Qe}else continue;if(He)if(ze==="image-url"||ke.startsWith("image/"))Te.push({type:"image",image:He,...ke.includes("/")?{mimeType:ke}:{}});else if(ke.startsWith("audio/"))Te.push({type:"audio",audio:He,mimeType:ke});else if(ke.startsWith("video/"))Te.push({type:"video",video:He,mimeType:ke});else{let Qe=ke||"application/octet-stream";Te.push({type:"file",data:He,mimeType:Qe,filename:Jm(Qe)})}}if(Te.length>0){let ct=c(),V=ae,We={id:`agent-media-${typeof V=="string"&&V.length>0?`${V}-${ct}`:String(ct)}`,role:"assistant",content:"",contentParts:Te,createdAt:new Date().toISOString(),streaming:!1,sequence:ct,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:le}};f(We);let He=h;He&&(He.streaming=!1,f(He)),h=null,E.current=null}}else if(J==="execution_complete"){let T=x.kind??ve;T==="agent"&&te&&(te.status=x.success?"complete":"error",te.completedAt=Ne(x.completedAt),te.stopReason=x.stopReason);let k=h;k&&(T==="flow"&&k.streaming!==!1?Me(k):(k.streaming=!1,f(k)),h=null),R=null,A="",yt=null,n({type:"status",status:"idle",terminal:!0})}else if(J==="execution_error"){let T=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(J!=="ping"){if(J==="approval_start"){let T=x.approvalId??`approval-${c()}`,k={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:te?.agentId??"virtual",executionId:x.executionId??te?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(k)}else if(J==="step_await"&&x.awaitReason==="approval_required"){let T=x.approvalId??`approval-${c()}`,k={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:te?.agentId??"virtual",executionId:x.executionId??te?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(k)}else if(J==="approval_complete"){let T=x.approvalId;if(T){let H={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:x.decision??"approved",agentId:te?.agentId??"virtual",executionId:x.executionId??te?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};f(H)}}else if(J==="artifact_start"||J==="artifact_delta"||J==="artifact_update"||J==="artifact_complete"){if(J==="artifact_start"){let T=x.artifactType,k=String(x.id),H=typeof x.title=="string"?x.title:void 0,G=x.file,B;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(B={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:k,artifactType:T,title:H,component:typeof x.component=="string"?x.component:void 0,...B?{file:B}:{}});let z=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(ue.set(k,{markdown:"",title:H,file:B,...z?{props:z}:{}}),!me.has(k)){me.add(k);let ae=Fo(this.config.features?.artifacts,T),tt=typeof x.component=="string"?x.component:void 0,Te={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ya(ae,{artifactId:k,title:H,artifactType:T,status:"streaming",...B?{file:B}:{},...tt?{component:tt}:{}})};xe.set(k,Te),f(Te)}}else if(J==="artifact_delta"){let T=String(x.id),k=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:T,artDelta:k});let H=ue.get(T);H&&(H.markdown+=k)}else if(J==="artifact_update"){let T=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:T,component:typeof x.component=="string"?x.component:void 0});let k=ue.get(String(x.id));k&&(k.props={...k.props??{},...T})}else if(J==="artifact_complete"){let T=String(x.id);n({type:"artifact_complete",id:T});let k=xe.get(T);if(k){k.streaming=!1;try{let H=JSON.parse(k.rawContent??"{}");if(H.props){H.props.status="complete";let G=ue.get(T);G?.markdown&&(H.props.markdown=G.markdown),G?.file&&(H.props.file=G.file),H.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(H.props.componentProps=G.props)}k.rawContent=JSON.stringify(H)}catch{}ue.delete(T),f(k),xe.delete(T)}}}else if(J==="transcript_insert"){let T=x.message;if(!T||typeof T!="object")continue;let k=String(T.id??`msg-${c()}`),H=T.role,B={id:k,role:H==="user"?"user":H==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(f(B),B.rawContent)try{let ae=JSON.parse(B.rawContent)?.props?.artifactId;typeof ae=="string"&&me.add(ae)}catch{}h=null,E.current=null,Le.delete(k),ot.delete(k)}else if(J==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let T=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(T)});let k=h;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}else if(J==="step_error"||J==="dispatch_error"||J==="flow_error"){let T=null;if(x.error instanceof Error)T=x.error;else if(J==="dispatch_error"){let k=x.message??x.error;k!=null&&k!==""&&(T=new Error(String(k)))}else{let k=x.error;typeof k=="string"&&k!==""?T=new Error(k):k!=null&&typeof k=="object"&&Reflect.has(k,"message")&&(T=new Error(String(k.message??k)))}if(T){n({type:"error",error:T});let k=h;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:M,value:J}=await r.read();if(M)break;i+=a.decode(J,{stream:!0});let x=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let s=o.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let r=n(o);return r!==null&&(e=r),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},gs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ml=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},hl=()=>{let e=Gm();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},yl=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=bp(n,vp|xp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Aa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Aa(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Jm=e=>{let t=null,n=0,s=e||(r=>{if(!r||typeof r!="object")return null;let a=i=>typeof i=="string"?Aa(i):null;if(r.component&&typeof r.component=="string")return typeof r.text=="string"?Aa(r.text):"";if(r.type==="init"&&r.form)return"";if(r.action)switch(r.action){case"nav_then_click":return a(r.on_load_text)||a(r.text)||null;case"message":case"message_and_click":case"checkout":return a(r.text)||null;default:return a(r.text)||a(r.display_text)||a(r.message)||null}return a(r.text)||a(r.display_text)||a(r.message)||a(r.content)||null});return{getExtractedText:()=>t,processChunk:r=>{let a=r.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let i=bp(r,vp|xp),p=s(i);p!==null&&(t=p)}catch{}return n=r.length,{text:t||"",raw:r}},close:()=>{}}},bl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ap="4.10.0";var wn=Ap;var Qm="https://api.runtype.com/v1/dispatch",Ma="https://api.runtype.com";function Ym(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let s=t.indexOf("/");if(s>0){let r=t.slice(s+1).split(";")[0]?.trim()??"";if(r&&r!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(r))return`attachment.${r}`}return"attachment"}var vl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Zm(e){switch(e){case"json":return yl;case"regex-json":return hl;case"xml":return bl;default:return ml}}var Sp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function eh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let s=Sp(n);if(!Sp(o))return e;if(!s||o===n||o.startsWith(n))return t;let a=gs(e);return gs(t)!==null&&a===null?t:e}var hr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Qm,this.headers={"Content-Type":"application/json","X-Persona-Version":wn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Zm(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new as(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:t,flowId:n};let r=Zd(o,s);return r.kind==="agentId"?{agentId:r.agentId}:r.kind==="flowId"?{flowId:r.flowId}:{targetPayload:r.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,s={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":wn},body:JSON.stringify(s)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s={...t,...this.config.clientToken&&{token:this.config.clientToken}},r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":wn},body:JSON.stringify(s)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let s=await this.buildPayload(t.messages),r=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(vl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...r&&Object.keys(r).length>0&&{metadata:r},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,s.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":wn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(i.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let s=o instanceof Error?o:new Error(String(o));throw!s.message.includes("Session expired")&&!s.message.includes("Message limit")&&n({type:"error",error:s}),s}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Chat backend request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Agent execution request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,s){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let s=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(s,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,s){let r=!!(n&&n.length>0),a=r?Qd(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=r&&i&&this.lastSentClientToolsFingerprint===a,d=!r&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let y=0;;y++){if(u=await o({...r&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&y===0&&r&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,r?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let s=this.isClientTokenMode(),r=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ma}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),s&&a){let d=[...ps(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,y=>{let f={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(r,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(r,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async s=>{try{let r=await s({messages:t,config:this.config});r&&typeof r=="object"&&Object.assign(n,r)}catch(r){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",r)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(vl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),s={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...ps(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];r.length>0&&(s.clientTools=r);let a=await this.buildContextAggregate(t);return a&&(s.context=a),s}async buildPayload(t){let n=t.slice().filter(vl).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),s={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(s[i]=p);let r=[...ps(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];r.length>0&&(s.clientTools=r);let a=await this.buildContextAggregate(t);if(a&&(s.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...s},config:this.config});if(i&&typeof i=="object"){let p=i;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return s}async handleCustomSSEEvent(t,n,o,s,r,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:r(),...c!==void 0&&{partId:c}};return o.current=u,s(u),u},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,s(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,s(c)}return i.done&&(o.current&&(o.current.streaming=!1,s(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,s){let r=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=M=>{let N=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,v=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,S=M.tools?M.tools.map(k=>({...k,chunks:k.chunks?[...k.chunks]:void 0})):void 0;return{...M,reasoning:N,toolCall:v,tools:S}},y=M=>{if(M.role!=="assistant"||M.variant)return!0;let N=Array.isArray(M.contentParts)&&M.contentParts.length>0,v=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||N||v||!!M.stopReason},f=M=>{y(M)&&n({type:"message",message:u(M)})},h=null,C=null,E={current:null},L={current:null},R=null,A="",I=new Map,_=new Map,O=new Map,w=new Map,z=new Map,q={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},D=M=>{if(M==null)return null;try{return String(M)}catch{return null}},j=M=>D(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),ge=M=>D(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),be=o,Ee=!1,De=()=>{if(h)return h;let M,N="",v=R;return!Ee&&be?(M=be,Ee=!0,N=s??""):be&&v?M=`${be}_${v}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:M,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},ae=(M,N)=>{q.lastId=N,M&&q.byStep.set(M,N)},ve=(M,N)=>{let v=M.reasoningId??M.id,S=j(M);if(v){let H=String(v);return ae(S,H),H}if(S){let H=q.byStep.get(S);if(H)return q.lastId=H,H}if(q.lastId&&!N)return q.lastId;if(!N)return null;let k=`reason-${c()}`;return ae(S,k),k},Y=M=>{let N=w.get(M);if(N)return N;let v={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return w.set(M,v),f(v),v},le=(M,N)=>{Q.lastId=N,M&&Q.byCall.set(M,N)},Z=new Set,Ce=new Map,me=new Set,pe=new Map,Pe=M=>{if(!M)return!1;let N=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return N==="emit_artifact_markdown"||N==="emit_artifact_component"},Oe=(M,N)=>{let v=M.toolId??M.id,S=ge(M);if(v){let H=String(v);return le(S,H),H}if(S){let H=Q.byCall.get(S);if(H)return Q.lastId=H,H}if(Q.lastId&&!N)return Q.lastId;if(!N)return null;let k=`tool-${c()}`;return le(S,k),k},$e=M=>{let N=z.get(M);if(N)return N;let v={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,v),f(v),v},He=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let N=Number(M);if(!Number.isNaN(N)&&Number.isFinite(N))return N;let v=Date.parse(M);if(!Number.isNaN(v))return v}return Date.now()},je=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Je=new Map,Me=new Map,ne=new Map,Re=(M,N,v)=>{let S=ne.get(M);S||(S=[],ne.set(M,S));let k=0,H=S.length;for(;k<H;){let B=k+H>>>1;S[B].seq<N?k=B+1:H=B}S[k]?.seq===N?S[k]={seq:N,text:v}:S.splice(k,0,{seq:N,text:v});let V="";for(let B=0;B<S.length;B++)V+=S[B].text;return V},xt=(M,N)=>{let v=je(N),S=Me.get(M.id),k=eh(S,v);M.rawContent=k;let H=Je.get(M.id),V=Se=>{let lt=M.content??"";Se.trim()!==""&&(lt.trim().length===0||Se.startsWith(lt)||Se.trimStart().startsWith(lt.trim()))&&(M.content=Se)},B=()=>{if(H){let Se=H.close?.();Se instanceof Promise&&Se.catch(()=>{})}Je.delete(M.id),Me.delete(M.id),M.streaming=!1,f(M)};if(!H){V(v),B();return}let U=gs(k);if(U!==null&&U.trim()!==""){V(U),B();return}let oe=Se=>{let lt=typeof Se=="string"?Se:Se?.text??null;if(lt!==null&&lt.trim()!=="")return lt;let K=H.getExtractedText();return K!==null&&K.trim()!==""?K:v},Xe;try{Xe=H.processChunk(k)}catch{V(v),B();return}if(Xe instanceof Promise){Xe.then(Se=>{V(oe(Se)),B()}).catch(()=>{V(v),B()});return}V(oe(Xe)),B()},ht=null,ct=(M,N,v,S)=>{M.rawContent=N,Je.has(M.id)||Je.set(M.id,this.createStreamParser());let k=Je.get(M.id),H=N.trim().startsWith("{")||N.trim().startsWith("[");if(H&&Me.set(M.id,N),k.__isPlainTextParser===!0){M.content=S!==void 0?N:M.content+v,Me.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M);return}let B=k.processChunk(N);if(B instanceof Promise)B.then(U=>{let oe=typeof U=="string"?U:U?.text??null;oe!==null&&oe.trim()!==""?(M.content=oe,f(M)):!H&&!N.trim().startsWith("<")&&(M.content=S!==void 0?N:M.content+v,Me.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=S!==void 0?N:M.content+v,Me.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M)});else{let U=typeof B=="string"?B:B?.text??null;U!==null&&U.trim()!==""?(M.content=U,f(M)):!H&&!N.trim().startsWith("<")&&(M.content=S!==void 0?N:M.content+v,Me.delete(M.id),Je.delete(M.id),M.rawContent=void 0,f(M))}},Ie=(M,N)=>{let v=N??M.content;if(v==null||v===""){M.streaming=!1,f(M);return}let k=Me.get(M.id)??je(v);M.rawContent=k;let H=Je.get(M.id),V=null,B=!1;if(H&&(V=H.getExtractedText(),V===null&&(V=gs(k)),V===null)){let U=H.processChunk(k);U instanceof Promise?(B=!0,U.then(oe=>{let Xe=typeof oe=="string"?oe:oe?.text??null;Xe!==null&&(M.content=Xe,M.streaming=!1,Je.delete(M.id),Me.delete(M.id),f(M))}).catch(()=>{})):V=typeof U=="string"?U:U?.text??null}if(!B){V!==null&&V.trim()!==""?M.content=V:Me.has(M.id)||(M.content=je(v));let U=Je.get(M.id);if(U){let oe=U.close?.();oe instanceof Promise&&oe.catch(()=>{}),Je.delete(M.id)}Me.delete(M.id),M.streaming=!1,f(M)}},he=(M,N,v)=>{let S=_.get(M);if(S)return S;let k={id:`nested-${N}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:N}};return _.set(M,k),f(k),k},Ye=[],ke,fe=new Map,ie=0,xe="agent",Ct=!1,ye=null,ue=null,gn=new Map,X=this.config.iterationDisplay??"separate";for(ke=()=>{for(let M=0;M<Ye.length;M++){let N=Ye[M].payloadType,v=Ye[M].payload;if(!Ct&&xe!=="flow"&&typeof v.stepType=="string"&&(xe="flow"),N==="reasoning_start"){let S=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&k){I.set(S,k),he(S,k,"reasoning");continue}let H=ve(v,!0)??`reason-${c()}`,V=Y(H);V.reasoning=V.reasoning??{id:H,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??He(v.startedAt??v.timestamp),V.reasoning.completedAt=void 0,V.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(V.reasoning.scope=v.scope),V.streaming=!0,V.reasoning.status="streaming",f(V)}else if(N==="reasoning_delta"){let S=typeof v.id=="string"?v.id:null;if(S&&I.has(S)&&_.has(S)){let B=_.get(S),U=v.reasoningText??v.text??v.delta??"";U&&v.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(U)),f(B));continue}let k=ve(v,!1)??ve(v,!0)??`reason-${c()}`,H=Y(k);H.reasoning=H.reasoning??{id:k,status:"streaming",chunks:[]},H.reasoning.startedAt=H.reasoning.startedAt??He(v.startedAt??v.timestamp);let V=v.reasoningText??v.text??v.delta??"";if(V&&v.hidden!==!0){let B=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(B!==void 0){let U=Re(k,B,String(V));H.reasoning.chunks=[U]}else H.reasoning.chunks.push(String(V))}if(H.reasoning.status=v.done?"complete":"streaming",v.done){H.reasoning.completedAt=He(v.completedAt??v.timestamp);let B=H.reasoning.startedAt??Date.now();H.reasoning.durationMs=Math.max(0,(H.reasoning.completedAt??Date.now())-B)}H.streaming=H.reasoning.status!=="complete",f(H)}else if(N==="reasoning_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&I.has(S)&&_.has(S)){let U=_.get(S);if(U.reasoning){let oe=typeof v.text=="string"?v.text:"";oe&&U.reasoning.chunks.length===0&&U.reasoning.chunks.push(oe),U.reasoning.status="complete",U.streaming=!1,f(U)}I.delete(S),_.delete(S);continue}let k=ve(v,!1)??ve(v,!0)??`reason-${c()}`,H=typeof v.text=="string"?v.text:"";!w.get(k)&&(H||v.scope==="loop")&&Y(k);let V=w.get(k);if(V?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(V.reasoning.scope=v.scope),H&&V.reasoning.chunks.length===0&&V.reasoning.chunks.push(H),V.reasoning.status="complete",V.reasoning.completedAt=He(v.completedAt??v.timestamp);let U=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-U),V.streaming=!1,f(V)}let B=j(v);B&&q.byStep.delete(B)}else if(N==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof v.iteration=="number"&&(ie=v.iteration);let S=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Oe(v,!0)??`tool-${c()}`,k=v.toolName??v.name;if(Pe(k)){Z.add(S);continue}le(ge(v),S);let H=$e(S),V=H.toolCall??{id:S,status:"pending"};V.name=k??V.name,V.status="running",v.parameters!==void 0?V.args=v.parameters:v.args!==void 0&&(V.args=v.args),V.startedAt=V.startedAt??He(v.startedAt??v.timestamp),V.completedAt=void 0,V.durationMs=void 0,H.toolCall=V,H.streaming=!0,v.executionId&&(H.agentMetadata={executionId:v.executionId,iteration:v.iteration}),f(H)}else if(N==="tool_output_delta"){let S=Oe(v,!1)??Oe(v,!0)??`tool-${c()}`;if(Z.has(S))continue;let k=$e(S),H=k.toolCall??{id:S,status:"running"};H.startedAt=H.startedAt??He(v.startedAt??v.timestamp);let V=v.text??v.delta??v.message??"";V&&(H.chunks=H.chunks??[],H.chunks.push(String(V))),H.status="running",k.toolCall=H,k.streaming=!0;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),f(k)}else if(N==="tool_complete"){let S=Oe(v,!1)??Oe(v,!0)??`tool-${c()}`;if(Z.has(S)){Z.delete(S);continue}let k=$e(S),H=k.toolCall??{id:S,status:"running"};H.status="complete",v.result!==void 0&&(H.result=v.result),typeof v.duration=="number"&&(H.duration=v.duration),H.completedAt=He(v.completedAt??v.timestamp);let V=v.duration??v.executionTime;if(typeof V=="number")H.durationMs=V;else{let oe=H.startedAt??Date.now();H.durationMs=Math.max(0,(H.completedAt??Date.now())-oe)}k.toolCall=H,k.streaming=!1;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),f(k);let U=ge(v);U&&Q.byCall.delete(U)}else if(N==="await"&&v.toolName){let S=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,k=S??v.toolId??`local-${c()}`,H=$e(k),V=v.toolName,B=v.origin==="webmcp"&&!No(V)?`webmcp:${V}`:V,U=No(B),oe=H.toolCall??{id:k,status:"pending"};oe.name=B,oe.args=v.parameters,oe.status=U?"running":"complete",oe.chunks=oe.chunks??[],oe.startedAt=oe.startedAt??He(v.startedAt??v.timestamp??v.awaitedAt),U?(oe.completedAt=void 0,oe.duration=void 0,oe.durationMs=void 0):oe.completedAt=oe.completedAt??oe.startedAt,H.toolCall=oe,H.streaming=!1,H.agentMetadata={...H.agentMetadata,executionId:v.executionId??H.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},f(H)}else if(N==="text_start"){let S=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&k){I.set(S,k);continue}let H=h;H&&(xe==="flow"?(Ie(H),ht=H):(H.streaming=!1,f(H)),h=null),R=typeof v.id=="string"?v.id:R,A=""}else if(N==="text_delta"){let S=typeof v.id=="string"?v.id:null,k=S?I.get(S):void 0;if(S&&k){let V=typeof v.delta=="string"?v.delta:"",B=(O.get(S)??"")+V;if(O.set(S,B),B.trim()==="")continue;let U=he(S,k);U.agentMetadata={...U.agentMetadata,executionId:v.executionId,parentToolId:k},ct(U,B,V,void 0);continue}if(R=typeof v.id=="string"?v.id:R,xe==="flow"){let V=typeof v.delta=="string"?v.delta:"";if(A+=V,A.trim()==="")continue;let B=De();B.agentMetadata={executionId:v.executionId,iteration:v.iteration},ct(B,A,V,void 0),C=B;continue}let H=De();H.content+=v.delta??"",H.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:ye??void 0,agentName:ue?.agentName},C=H,f(H)}else if(N==="text_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&I.has(S)){let H=_.get(S);H&&Ie(H),I.delete(S),O.delete(S),_.delete(S);continue}let k=h;k&&(xe==="flow"?(Ie(k),ht=k):((k.content??"")===""&&typeof v.text=="string"&&(k.content=v.text),k.streaming=!1,f(k)),h=null),R=null,A=""}else if(N==="step_complete"){let S=v.stepType,k=v.executionType;if(S==="tool"||k==="context")continue;if(v.success===!1){let H=v.error,V=typeof H=="string"&&H!==""?H:H!=null&&typeof H=="object"&&Reflect.has(H,"message")?String(H.message??"Step failed"):"Step failed";n({type:"error",error:new Error(V)});let B=h;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"});continue}{let H=ht;ht=null;let V=v.stopReason,B=v.result?.response;if(H)V&&(H.stopReason=V),B!=null?xt(H,B):H.streaming!==!1&&(Je.delete(H.id),Me.delete(H.id),H.streaming=!1,f(H));else{let U=B!=null&&B!=="";if(U||V){let oe=De();V&&(oe.stopReason=V),U?Ie(oe,B):(oe.streaming=!1,f(oe))}}continue}}else if(N==="execution_start")xe=v.kind==="flow"?"flow":"agent",Ct=!0,xe==="agent"&&(ue={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:He(v.startedAt)});else if(N==="turn_start"){let S=typeof v.iteration=="number"?v.iteration:ie;if(S!==ie){if(ue&&(ue.currentIteration=S),X==="separate"&&S>1){let k=h;k&&(k.streaming=!1,f(k),gn.set(S-1,k),h=null)}ie=S}ye=typeof v.id=="string"?v.id:null,C=null}else if(N==="tool_input_delta"){let S=v.toolCallId??Q.lastId;if(S){let k=z.get(S);k?.toolCall&&(k.toolCall.chunks=k.toolCall.chunks??[],k.toolCall.chunks.push(v.delta??""),f(k))}}else{if(N==="tool_input_complete")continue;if(N==="turn_complete"){let S=v.stopReason,k=h??C;if(S&&k!==null){let H=v.id;(!H||k.agentMetadata?.turnId===H)&&(k.stopReason=S,f(k))}ye===v.id&&(ye=null)}else if(N==="media_start"){let S=String(v.id);fe.set(S,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(N==="media_delta"){let S=fe.get(String(v.id));S&&typeof v.delta=="string"&&S.parts.push(v.delta)}else if(N==="media_complete"){let S=String(v.id),k=fe.get(S);fe.delete(S);let H=(typeof v.mediaType=="string"?v.mediaType:void 0)??k?.mediaType??"application/octet-stream",V=typeof v.data=="string"?v.data:void 0,B=typeof v.url=="string"?v.url:k&&k.parts.length>0?k.parts.join(""):void 0,U=null;if(V)U={type:"media",data:V,mediaType:H};else if(B){let lt=H.toLowerCase();U={type:lt==="image"||lt.startsWith("image/")?"image-url":"file-url",url:B,mediaType:H}}let oe=v.toolCallId??k?.toolCallId,Xe=U?[U]:[],Se=[];for(let lt of Xe){if(!lt||typeof lt!="object")continue;let K=lt,Ue=typeof K.type=="string"?K.type:void 0,Te=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",We=null,Le="";if(Ue==="media"){let et=typeof K.data=="string"?K.data:void 0;if(!et)continue;Le=Te.length>0?Te:"application/octet-stream",We=`data:${Le};base64,${et}`}else if(Ue==="image-url"){let et=typeof K.url=="string"?K.url:void 0;if(!et)continue;Le=Te,We=et}else if(Ue==="file-url"){let et=typeof K.url=="string"?K.url:void 0;if(!et)continue;Le=Te,We=et}else continue;if(We)if(Ue==="image-url"||Le.startsWith("image/"))Se.push({type:"image",image:We,...Le.includes("/")?{mimeType:Le}:{}});else if(Le.startsWith("audio/"))Se.push({type:"audio",audio:We,mimeType:Le});else if(Le.startsWith("video/"))Se.push({type:"video",video:We,mimeType:Le});else{let et=Le||"application/octet-stream";Se.push({type:"file",data:We,mimeType:et,filename:Ym(et)})}}if(Se.length>0){let lt=c(),K=oe,Te={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${lt}`:String(lt)}`,role:"assistant",content:"",contentParts:Se,createdAt:new Date().toISOString(),streaming:!1,sequence:lt,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ie}};f(Te);let We=h;We&&(We.streaming=!1,f(We)),h=null,E.current=null}}else if(N==="execution_complete"){let S=v.kind??xe;S==="agent"&&ue&&(ue.status=v.success?"complete":"error",ue.completedAt=He(v.completedAt),ue.stopReason=v.stopReason);let k=h;k&&(S==="flow"&&k.streaming!==!1?Ie(k):(k.streaming=!1,f(k)),h=null),R=null,A="",ht=null,n({type:"status",status:"idle",terminal:!0})}else if(N==="execution_error"){let S=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(N!=="ping"){if(N==="approval_start"){let S=v.approvalId??`approval-${c()}`,k={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(k)}else if(N==="step_await"&&v.awaitReason==="approval_required"){let S=v.approvalId??`approval-${c()}`,k={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(k)}else if(N==="approval_complete"){let S=v.approvalId;if(S){let H={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:v.decision??"approved",agentId:ue?.agentId??"virtual",executionId:v.executionId??ue?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(H)}}else if(N==="artifact_start"||N==="artifact_delta"||N==="artifact_update"||N==="artifact_complete"){if(N==="artifact_start"){let S=v.artifactType,k=String(v.id),H=typeof v.title=="string"?v.title:void 0,V=v.file,B;V&&typeof V=="object"&&!Array.isArray(V)&&typeof V.path=="string"&&typeof V.mimeType=="string"&&(B={path:V.path,mimeType:V.mimeType,...typeof V.language=="string"?{language:V.language}:{}}),n({type:"artifact_start",id:k,artifactType:S,title:H,component:typeof v.component=="string"?v.component:void 0,...B?{file:B}:{}});let U=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(pe.set(k,{markdown:"",title:H,file:B,...U?{props:U}:{}}),!me.has(k)){me.add(k);let oe=Fo(this.config.features?.artifacts,S),Xe=typeof v.component=="string"?v.component:void 0,Se={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ya(oe,{artifactId:k,title:H,artifactType:S,status:"streaming",...B?{file:B}:{},...Xe?{component:Xe}:{}})};Ce.set(k,Se),f(Se)}}else if(N==="artifact_delta"){let S=String(v.id),k=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:S,artDelta:k});let H=pe.get(S);H&&(H.markdown+=k)}else if(N==="artifact_update"){let S=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:S,component:typeof v.component=="string"?v.component:void 0});let k=pe.get(String(v.id));k&&(k.props={...k.props??{},...S})}else if(N==="artifact_complete"){let S=String(v.id);n({type:"artifact_complete",id:S});let k=Ce.get(S);if(k){k.streaming=!1;try{let H=JSON.parse(k.rawContent??"{}");if(H.props){H.props.status="complete";let V=pe.get(S);V?.markdown&&(H.props.markdown=V.markdown),V?.file&&(H.props.file=V.file),H.component==="PersonaArtifactInline"&&V?.props&&Object.keys(V.props).length>0&&(H.props.componentProps=V.props)}k.rawContent=JSON.stringify(H)}catch{}pe.delete(S),f(k),Ce.delete(S)}}}else if(N==="transcript_insert"){let S=v.message;if(!S||typeof S!="object")continue;let k=String(S.id??`msg-${c()}`),H=S.role,B={id:k,role:H==="user"?"user":H==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:c()};if(f(B),B.rawContent)try{let oe=JSON.parse(B.rawContent)?.props?.artifactId;typeof oe=="string"&&me.add(oe)}catch{}h=null,E.current=null,Je.delete(k),Me.delete(k)}else if(N==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let S=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(S)});let k=h;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}else if(N==="step_error"||N==="dispatch_error"||N==="flow_error"){let S=null;if(v.error instanceof Error)S=v.error;else if(N==="dispatch_error"){let k=v.message??v.error;k!=null&&k!==""&&(S=new Error(String(k)))}else{let k=v.error;typeof k=="string"&&k!==""?S=new Error(k):k!=null&&typeof k=="object"&&Reflect.has(k,"message")&&(S=new Error(String(k.message??k)))}if(S){n({type:"error",error:S});let k=h;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}Ye.length=0};;){let{done:M,value:N}=await r.read();if(M)break;i+=a.decode(N,{stream:!0});let v=i.split(`
12
12
 
13
- `);i=x.pop()??"";for(let T of x){let k=T.split(`
14
- `),H="message",G="",B=null;for(let Te of k)Te.startsWith("event:")?H=Te.replace("event:","").trim():Te.startsWith("data:")?G+=Te.replace("data:","").trim():Te.startsWith("id:")&&(B=Te.slice(3).trim());let z=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!G){z();continue}let ae;try{ae=JSON.parse(G)}catch(Te){n({type:"error",error:Te instanceof Error?Te:new Error("Failed to parse chat stream payload")});continue}let tt=H!=="message"?H:ae.type??"message";if(this.onSSEEvent?.(tt,ae),this.parseSSEEvent){E.current=h;let Te=await this.handleCustomSSEEvent(ae,n,E,f,c,L);if(E.current&&E.current!==h&&(h=E.current),Te){z();continue}}lt.push({payloadType:tt,payload:ae}),Ie(),z()}}Ie()}};function Ym(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ms(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function jo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ka="[Image]";function Zm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function eh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function bl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function th(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Uo(e){return{type:"text",text:e}}function nh(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function oh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function rh(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Sp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],sh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Un=[...Sp,...sh];function ah(e){return Sp.includes(e)||e.startsWith("image/")}function La(e){return ah(e.type)}async function Tp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;La(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Ep(e,t=Un,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function ih(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Mp(e,t){let n=ih(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}vl();var kp=16e3,lh=24e3,ch=4096,dh=1380533830;function ph(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===dh?new Uint8Array(e,44):new Uint8Array(e)}function uh(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let r=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:kp,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){r.getTracks().forEach(u=>u.stop());return}this.mediaStream=r;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:kp});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new yr(lh);if(s!==this.callGeneration){p.destroy(),r.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${uh(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,r,c,s))},c.onmessage=u=>this.handleMessage(u,s),c.onerror=()=>{s===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(s===this.callGeneration){if(u.code!==1e3){let y=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(r){throw this.cleanup(),this.emitError(r),this.emitStatus("error"),r}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,s){let r=t.createMediaStreamSource(n);this.sourceNode=r;let a=t.createScriptProcessor(ch,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},r.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=ph(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(s=>s(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var zo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(r=>r[0]).map(r=>r.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(r=>r({text:o,confidence:s?.8:.5,provider:"browser"})),s&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function qo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!zo.isSupported())throw new Error("Browser speech recognition not supported");return new zo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function xl(e){if(e?.type==="custom"&&e.custom)return qo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return qo({type:"runtype",runtype:e.runtype});if(zo.isSupported())return qo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Pa(e){try{return xl(e),!0}catch{return!1}}function ys(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(s=>s.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Vo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(t.text),r=o.getVoices();if(t.voice){let a=r.find(i=>i.name===t.voice);a&&(s.voice=a)}else r.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(r):ys(r));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>n.onEnd?.(),s.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var br=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(o!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Cl(e){if(!e)return"";let t=fh(e);return Lp(t!==null?t:e)}function fh(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Lp(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
+ `);i=v.pop()??"";for(let S of v){let k=S.split(`
14
+ `),H="message",V="",B=null;for(let Se of k)Se.startsWith("event:")?H=Se.replace("event:","").trim():Se.startsWith("data:")?V+=Se.replace("data:","").trim():Se.startsWith("id:")&&(B=Se.slice(3).trim());let U=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!V){U();continue}let oe;try{oe=JSON.parse(V)}catch(Se){n({type:"error",error:Se instanceof Error?Se:new Error("Failed to parse chat stream payload")});continue}let Xe=H!=="message"?H:oe.type??"message";if(this.onSSEEvent?.(Xe,oe),this.parseSSEEvent){E.current=h;let Se=await this.handleCustomSSEEvent(oe,n,E,f,c,L);if(E.current&&E.current!==h&&(h=E.current),Se){U();continue}}Ye.push({payloadType:Xe,payload:oe}),ke(),U()}}ke()}};function th(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ms(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function jo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ka="[Image]";function nh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function oh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function xl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function rh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Uo(e){return{type:"text",text:e}}function sh(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function ah(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function ih(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Tp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],lh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Un=[...Tp,...lh];function ch(e){return Tp.includes(e)||e.startsWith("image/")}function La(e){return ch(e.type)}async function Ep(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;La(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Mp(e,t=Un,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function dh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function kp(e,t){let n=dh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}Cl();var Lp=16e3,ph=24e3,uh=4096,fh=1380533830;function gh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===fh?new Uint8Array(e,44):new Uint8Array(e)}function mh(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let r=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Lp,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){r.getTracks().forEach(u=>u.stop());return}this.mediaStream=r;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:Lp});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new yr(ph);if(s!==this.callGeneration){p.destroy(),r.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${mh(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,r,c,s))},c.onmessage=u=>this.handleMessage(u,s),c.onerror=()=>{s===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(s===this.callGeneration){if(u.code!==1e3){let y=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(r){throw this.cleanup(),this.emitError(r),this.emitStatus("error"),r}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,s){let r=t.createMediaStreamSource(n);this.sourceNode=r;let a=t.createScriptProcessor(uh,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},r.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=gh(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(s=>s(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var zo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(r=>r[0]).map(r=>r.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(r=>r({text:o,confidence:s?.8:.5,provider:"browser"})),s&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function qo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!zo.isSupported())throw new Error("Browser speech recognition not supported");return new zo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function wl(e){if(e?.type==="custom"&&e.custom)return qo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return qo({type:"runtype",runtype:e.runtype});if(zo.isSupported())return qo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Pa(e){try{return wl(e),!0}catch{return!1}}function ys(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(s=>s.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Vo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(t.text),r=o.getVoices();if(t.voice){let a=r.find(i=>i.name===t.voice);a&&(s.voice=a)}else r.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(r):ys(r));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>n.onEnd?.(),s.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var br=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(o!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Al(e){if(!e)return"";let t=hh(e);return Pp(t!==null?t:e)}function hh(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Pp(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
- `),t.trim()}var Hp=null;var wl=()=>Hp?Hp():Promise.resolve().then(()=>(Wp(),Ip));var bh=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function vh(e,t){return bh.some(n=>e[n]!==t[n])}function Al(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
16
+ `),t.trim()}var Bp=null;var Sl=()=>Bp?Bp():Promise.resolve().then(()=>(Hp(),Wp));var Ch=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function wh(e,t){return Ch.some(n=>e[n]!==t[n])}function Tl(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
17
17
 
18
- _Details: ${n.message}_`:o}var bs=e=>({isError:!0,content:[{type:"text",text:e}]}),Op=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Np=e=>No(e)||e===Ln,vs=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new br(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(No(n.name)||n.name===Ln&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new hr(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Pa(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Vo.isSupported()?new Vo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,s=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,r=this.config.clientToken,a=t.browserFallback!==!1;if(o&&s&&r)return wl().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:s,clientToken:r,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return r&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=qo(n);let s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!vh(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new hr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:s,contentParts:r,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?ms():n==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...s!==void 0&&{llmContent:s},...r!==void 0&&{contentParts:r},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:s,content:r,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:y,rawContent:f}=o,C={id:p??(s==="user"?ms():s==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:r,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...y!==void 0&&{voiceProcessing:y},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:s="",llmContent:r,id:a,createdAt:i,sequence:p}=t,d={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(d),...r!==void 0&&{llmContent:r},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let s;try{s=await o()}catch{return}let r=s.blocks.join(`
18
+ _Details: ${n.message}_`:o}var bs=e=>({isError:!0,content:[{type:"text",text:e}]}),Np=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Fp=e=>No(e)||e===Ln,vs=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new br(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(No(n.name)||n.name===Ln&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new hr(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Sl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Pa(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Vo.isSupported()?new Vo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,s=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,r=this.config.clientToken,a=t.browserFallback!==!1;if(o&&s&&r)return Sl().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:s,clientToken:r,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return r&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=qo(n);let s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!wh(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new hr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:s,contentParts:r,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?ms():n==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...s!==void 0&&{llmContent:s},...r!==void 0&&{contentParts:r},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:s,content:r,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:y,rawContent:f}=o,C={id:p??(s==="user"?ms():s==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:r,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...y!==void 0&&{voiceProcessing:y},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:s="",llmContent:r,id:a,createdAt:i,sequence:p}=t,d={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(d),...r!==void 0&&{llmContent:r},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let s;try{s=await o()}catch{return}let r=s.blocks.join(`
19
19
 
20
20
  `),a=[r,n].filter(Boolean).join(`
21
21
 
22
- `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=s.contentParts.length>0;if(i){let d=[];r&&d.push(Uo(r)),d.push(...s.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(Uo(a)),d.push(...s.contentParts),t.contentParts=d}else r&&(t.llmContent=a);Object.keys(s.context).length>0&&(t.mentionContext=s.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=ms(),r=jo();this.activeAssistantMessageId=null;let a=n?.contentParts&&bl(n.contentParts)?ka:"",i={id:s,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===s)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:r},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let y=Al(c,this.config.errorMessage);if(y){let f={id:r,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=jo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;let r=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!r){let a=Al(s,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,r||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let r of this.messages)r.streaming&&r.id!==o&&(r.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(r instanceof Error?r:new Error(String(r)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(r=>r.id===t);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let s=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===s),i={id:s,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:r};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let y=await c.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(s=>s.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(s=>s.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let s=t.agentMetadata?.executionId,r=t.toolCall?.name;if(!s||!r){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let y=typeof u[0]?.question=="string"?u[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,y])=>`${u}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,y)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=c[f],C=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${i}-${y}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${y}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(s,{[r]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let r=this.webMcpEpoch;queueMicrotask(()=>{r===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(s=>s.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Ln?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,s=Date.now(),r){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...r},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],s=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let y=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Ln)return{dedupeKey:u,resumeKey:f,output:dl(),toolMessage:p,startedAt:y,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),s.push(h);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,h.signal),E;if(!C)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await C}catch(L){let R=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return R||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,bs(R?"Aborted by cancel()":Op(L)),y),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,bs("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:E,toolMessage:p,startedAt:y,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:r.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Ln?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,bs("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,s=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!s){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(h)}return}let r=`${n}:${s}`;if(this.webMcpInflightKeys.has(r)||this.webMcpResolvedKeys.has(r)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(r);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===Ln,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),y="execute",f=a;try{let h;if(d?h=dl():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,bs("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,C,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(r),this.markWebMcpToolComplete(t,h,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let C=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(y==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,bs(C||p.aborted?"Aborted by cancel()":Op(h)),a),C||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(r),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,s){let r=await this.client.resumeFlow(t,{[n]:o},{signal:s?.signal});if(!r.ok){let a=await r.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${r.status}`)}s?.onHttpOk?.(),r.body?await this.connectStream(r.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Fo(this.config.features?.artifacts,t.artifactType),s=ya(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),r=this.messages.find(a=>a.id===n);if(r){r.rawContent=s,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Dp(),Bp)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,s)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Al(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=jo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(r=>r.role==="assistant"&&r.content&&!r.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=Cl(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ys(t)}toggleReadAloud(t){let n=this.messages.find(r=>r.id===t);if(!n||n.role!=="assistant")return;let o=Cl(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,r)=>{if(r!==o)return s;let a={...s,...n};if(s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let c=s.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&Np(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),y=this.webMcpResolvedKeys.has(c),f=s.toolCall?.name,h=s.agentMetadata?.executionId===p&&s.toolCall?.id===d&&f!==void 0&&Np(f)&&s.toolCall?.status==="complete";(u||y||h)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),r=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(r)&&s!==r)return s-r;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};import{Activity as xh,ArrowDown as Ch,ArrowUp as wh,ArrowUpRight as Ah,Bot as Sh,ChevronDown as Th,ChevronUp as Eh,ChevronRight as Mh,ChevronLeft as kh,Check as Lh,Clipboard as Ph,ClipboardCopy as Rh,CodeXml as Ih,Copy as Wh,File as Hh,FileCode as Bh,FileSpreadsheet as Dh,FileText as Oh,ImagePlus as Nh,Loader as Fh,LoaderCircle as _h,Mic as $h,Paperclip as jh,RefreshCw as Uh,Search as zh,Send as qh,ShieldAlert as Vh,ShieldCheck as Kh,ShieldX as Gh,Square as Jh,ThumbsDown as Xh,ThumbsUp as Qh,Upload as Yh,Volume2 as Zh,X as ey,User as ty,Mail as ny,Phone as oy,Calendar as ry,Clock as sy,Building as ay,MapPin as iy,Lock as ly,Key as cy,CreditCard as dy,AtSign as py,Hash as uy,Globe as fy,Link as gy,CircleCheck as my,CircleX as hy,TriangleAlert as yy,Info as by,Ban as vy,Shield as xy,ArrowLeft as Cy,ArrowRight as wy,ExternalLink as Ay,Ellipsis as Sy,EllipsisVertical as Ty,Menu as Ey,House as My,Plus as ky,Minus as Ly,Pencil as Py,Trash as Ry,Trash2 as Iy,Save as Wy,Download as Hy,Share as By,Funnel as Dy,Settings as Oy,RotateCw as Ny,Maximize as Fy,Minimize as _y,ShoppingCart as $y,ShoppingBag as jy,Package as Uy,Truck as zy,Tag as qy,Gift as Vy,Receipt as Ky,Wallet as Gy,Store as Jy,DollarSign as Xy,Percent as Qy,Play as Yy,Pause as Zy,VolumeX as eb,Camera as tb,Image as nb,Film as ob,Headphones as rb,MessageCircle as sb,MessageSquare as ab,Bell as ib,Heart as lb,Star as cb,Eye as db,EyeOff as pb,Bookmark as ub,CalendarDays as fb,History as gb,Timer as mb,Folder as hb,FolderOpen as yb,Files as bb,Sparkles as vb,Zap as xb,Sun as Cb,Moon as wb,Flag as Ab,Monitor as Sb,Smartphone as Tb}from"lucide";var Eb={activity:xh,"arrow-down":Ch,"arrow-up":wh,"arrow-up-right":Ah,bot:Sh,"chevron-down":Th,"chevron-up":Eh,"chevron-right":Mh,"chevron-left":kh,check:Lh,clipboard:Ph,"clipboard-copy":Rh,"code-xml":Ih,copy:Wh,file:Hh,"file-code":Bh,"file-spreadsheet":Dh,"file-text":Oh,"image-plus":Nh,loader:Fh,"loader-circle":_h,mic:$h,paperclip:jh,"refresh-cw":Uh,search:zh,send:qh,"shield-alert":Vh,"shield-check":Kh,"shield-x":Gh,square:Jh,"thumbs-down":Xh,"thumbs-up":Qh,upload:Yh,"volume-2":Zh,x:ey,user:ty,mail:ny,phone:oy,calendar:ry,clock:sy,building:ay,"map-pin":iy,lock:ly,key:cy,"credit-card":dy,"at-sign":py,hash:uy,globe:fy,link:gy,"circle-check":my,"circle-x":hy,"triangle-alert":yy,info:by,ban:vy,shield:xy,"arrow-left":Cy,"arrow-right":wy,"external-link":Ay,ellipsis:Sy,"ellipsis-vertical":Ty,menu:Ey,house:My,plus:ky,minus:Ly,pencil:Py,trash:Ry,"trash-2":Iy,save:Wy,download:Hy,share:By,funnel:Dy,settings:Oy,"rotate-cw":Ny,maximize:Fy,minimize:_y,"shopping-cart":$y,"shopping-bag":jy,package:Uy,truck:zy,tag:qy,gift:Vy,receipt:Ky,wallet:Gy,store:Jy,"dollar-sign":Xy,percent:Qy,play:Yy,pause:Zy,"volume-x":eb,camera:tb,image:nb,film:ob,headphones:rb,"message-circle":sb,"message-square":ab,bell:ib,heart:lb,star:cb,eye:db,"eye-off":pb,bookmark:ub,"calendar-days":fb,history:gb,timer:mb,folder:hb,"folder-open":yb,files:bb,sparkles:vb,zap:xb,sun:Cb,moon:wb,flag:Ab,monitor:Sb,smartphone:Tb},ne=(e,t=24,n="currentColor",o=2)=>{let s=Eb[e];return s?Mb(s,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Mb(e,t,n,o){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(o)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(r=>{if(!Array.isArray(r)||r.length<2)return;let a=r[0],i=r[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),s.appendChild(p)}),s}var Wa={allowedTypes:Un,maxFileSize:10*1024*1024,maxFiles:4};function kb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Lb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var vr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Wa.allowedTypes,maxFileSize:t.maxFileSize??Wa.maxFileSize,maxFiles:t.maxFiles??Wa.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Wa.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Ep(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let s=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,s);continue}try{let s=await Tp(n),r=La(n)?URL.createObjectURL(n):null,a={id:kb(),file:n,previewUrl:r,contentPart:s};this.attachments.push(a),this.renderPreview(a)}catch(s){console.error("[AttachmentManager] Failed to process file:",s)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(r=>r.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=La(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Lb(t.file.type),p=ne(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=Mp(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let s=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let r=ne("x",10,"var(--persona-text-inverse, #ffffff)",2);r?s.appendChild(r):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(s),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Fp=/\s/;function Pb(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
- `:o===""||Fp.test(o)}function Rb(e,t,n="@",o="anywhere",s=!1){if(!n||t<=0||t>e.length)return null;let r=t-1;for(;r>=0;){let a=e[r];if(a===n)return Pb(e,r,o)?{triggerIndex:r,query:e.slice(r+1,t)}:null;if(a===`
24
- `||a==="\uFFFC"||!s&&Fp.test(a))return null;r--}return null}function _p(e,t,n){for(let o of n){let s=Rb(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(s)return{channel:o,match:s}}return null}function $p(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function jp(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}function Up(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",s=parseFloat(o)||40,r=Math.round(s*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=_e("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ne(a,r,"currentColor",1.5);c?d.appendChild(c):d.textContent="+",d.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),n()}),p.appendChild(d);let u=m("div","persona-send-button-tooltip");return u.textContent=i,p.appendChild(u),{button:d,wrapper:p}}var{setLoader:XA,load:Ib}=ur({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Sl=Ib;var{setLoader:ZA,load:Wb}=ur({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var zp=Wb;function xs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=_e("span",{className:jn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ne(e.iconName??"at-sign",13,"currentColor",2);if(o){let s=m("span","persona-mention-token-icon");s.appendChild(o),n.appendChild(s)}return n.appendChild(_e("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function qp(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=jp(t).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(I=>typeof I.matchCommand=="function")),s=A=>o.some(I=>I.trigger?I.position==="line-start"?A.split(`
22
+ `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=s.contentParts.length>0;if(i){let d=[];r&&d.push(Uo(r)),d.push(...s.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(Uo(a)),d.push(...s.contentParts),t.contentParts=d}else r&&(t.llmContent=a);Object.keys(s.context).length>0&&(t.mentionContext=s.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=ms(),r=jo();this.activeAssistantMessageId=null;let a=n?.contentParts&&xl(n.contentParts)?ka:"",i={id:s,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===s)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:r},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let y=Tl(c,this.config.errorMessage);if(y){let f={id:r,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=jo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;let r=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!r){let a=Tl(s,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,r||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let r of this.messages)r.streaming&&r.id!==o&&(r.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(r instanceof Error?r:new Error(String(r)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(r=>r.id===t);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let s=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===s),i={id:s,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:r};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let y=await c.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(s=>s.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(s=>s.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let s=t.agentMetadata?.executionId,r=t.toolCall?.name;if(!s||!r){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let y=typeof u[0]?.question=="string"?u[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,y])=>`${u}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,y)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=c[f],C=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${i}-${y}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${y}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(s,{[r]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let r=this.webMcpEpoch;queueMicrotask(()=>{r===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(s=>s.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Ln?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,s=Date.now(),r){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...r},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],s=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let y=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Ln)return{dedupeKey:u,resumeKey:f,output:ul(),toolMessage:p,startedAt:y,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),s.push(h);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,h.signal),E;if(!C)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await C}catch(L){let R=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return R||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,bs(R?"Aborted by cancel()":Np(L)),y),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,bs("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:E,toolMessage:p,startedAt:y,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:r.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Ln?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,bs("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,s=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!s){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(h)}return}let r=`${n}:${s}`;if(this.webMcpInflightKeys.has(r)||this.webMcpResolvedKeys.has(r)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(r);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===Ln,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),y="execute",f=a;try{let h;if(d?h=ul():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,bs("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,C,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(r),this.markWebMcpToolComplete(t,h,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let C=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(y==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,bs(C||p.aborted?"Aborted by cancel()":Np(h)),a),C||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(r),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,s){let r=await this.client.resumeFlow(t,{[n]:o},{signal:s?.signal});if(!r.ok){let a=await r.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${r.status}`)}s?.onHttpOk?.(),r.body?await this.connectStream(r.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Fo(this.config.features?.artifacts,t.artifactType),s=ya(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),r=this.messages.find(a=>a.id===n);if(r){r.rawContent=s,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Op(),Dp)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,s)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Tl(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=jo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(r=>r.role==="assistant"&&r.content&&!r.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=Al(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ys(t)}toggleReadAloud(t){let n=this.messages.find(r=>r.id===t);if(!n||n.role!=="assistant")return;let o=Al(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,r)=>{if(r!==o)return s;let a={...s,...n};if(s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let c=s.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&Fp(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),y=this.webMcpResolvedKeys.has(c),f=s.toolCall?.name,h=s.agentMetadata?.executionId===p&&s.toolCall?.id===d&&f!==void 0&&Fp(f)&&s.toolCall?.status==="complete";(u||y||h)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),r=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(r)&&s!==r)return s-r;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};import{Activity as Ah,ArrowDown as Sh,ArrowUp as Th,ArrowUpRight as Eh,Bot as Mh,ChevronDown as kh,ChevronUp as Lh,ChevronRight as Ph,ChevronLeft as Rh,Check as Ih,Clipboard as Wh,ClipboardCopy as Hh,CodeXml as Bh,Copy as Dh,File as Oh,FileCode as Nh,FileSpreadsheet as Fh,FileText as _h,ImagePlus as $h,Loader as jh,LoaderCircle as Uh,Mic as zh,Paperclip as qh,RefreshCw as Vh,Search as Kh,Send as Gh,ShieldAlert as Jh,ShieldCheck as Xh,ShieldX as Qh,Square as Yh,ThumbsDown as Zh,ThumbsUp as ey,Upload as ty,Volume2 as ny,X as oy,User as ry,Mail as sy,Phone as ay,Calendar as iy,Clock as ly,Building as cy,MapPin as dy,Lock as py,Key as uy,CreditCard as fy,AtSign as gy,Hash as my,Globe as hy,Link as yy,CircleCheck as by,CircleX as vy,TriangleAlert as xy,Info as Cy,Ban as wy,Shield as Ay,ArrowLeft as Sy,ArrowRight as Ty,ExternalLink as Ey,Ellipsis as My,EllipsisVertical as ky,Menu as Ly,House as Py,Plus as Ry,Minus as Iy,Pencil as Wy,Trash as Hy,Trash2 as By,Save as Dy,Download as Oy,Share as Ny,Funnel as Fy,Settings as _y,RotateCw as $y,Maximize as jy,Minimize as Uy,ShoppingCart as zy,ShoppingBag as qy,Package as Vy,Truck as Ky,Tag as Gy,Gift as Jy,Receipt as Xy,Wallet as Qy,Store as Yy,DollarSign as Zy,Percent as eb,Play as tb,Pause as nb,VolumeX as ob,Camera as rb,Image as sb,Film as ab,Headphones as ib,MessageCircle as lb,MessageSquare as cb,Bell as db,Heart as pb,Star as ub,Eye as fb,EyeOff as gb,Bookmark as mb,CalendarDays as hb,History as yb,Timer as bb,Folder as vb,FolderOpen as xb,Files as Cb,Sparkles as wb,Zap as Ab,Sun as Sb,Moon as Tb,Flag as Eb,Monitor as Mb,Smartphone as kb}from"lucide";var Lb={activity:Ah,"arrow-down":Sh,"arrow-up":Th,"arrow-up-right":Eh,bot:Mh,"chevron-down":kh,"chevron-up":Lh,"chevron-right":Ph,"chevron-left":Rh,check:Ih,clipboard:Wh,"clipboard-copy":Hh,"code-xml":Bh,copy:Dh,file:Oh,"file-code":Nh,"file-spreadsheet":Fh,"file-text":_h,"image-plus":$h,loader:jh,"loader-circle":Uh,mic:zh,paperclip:qh,"refresh-cw":Vh,search:Kh,send:Gh,"shield-alert":Jh,"shield-check":Xh,"shield-x":Qh,square:Yh,"thumbs-down":Zh,"thumbs-up":ey,upload:ty,"volume-2":ny,x:oy,user:ry,mail:sy,phone:ay,calendar:iy,clock:ly,building:cy,"map-pin":dy,lock:py,key:uy,"credit-card":fy,"at-sign":gy,hash:my,globe:hy,link:yy,"circle-check":by,"circle-x":vy,"triangle-alert":xy,info:Cy,ban:wy,shield:Ay,"arrow-left":Sy,"arrow-right":Ty,"external-link":Ey,ellipsis:My,"ellipsis-vertical":ky,menu:Ly,house:Py,plus:Ry,minus:Iy,pencil:Wy,trash:Hy,"trash-2":By,save:Dy,download:Oy,share:Ny,funnel:Fy,settings:_y,"rotate-cw":$y,maximize:jy,minimize:Uy,"shopping-cart":zy,"shopping-bag":qy,package:Vy,truck:Ky,tag:Gy,gift:Jy,receipt:Xy,wallet:Qy,store:Yy,"dollar-sign":Zy,percent:eb,play:tb,pause:nb,"volume-x":ob,camera:rb,image:sb,film:ab,headphones:ib,"message-circle":lb,"message-square":cb,bell:db,heart:pb,star:ub,eye:fb,"eye-off":gb,bookmark:mb,"calendar-days":hb,history:yb,timer:bb,folder:vb,"folder-open":xb,files:Cb,sparkles:wb,zap:Ab,sun:Sb,moon:Tb,flag:Eb,monitor:Mb,smartphone:kb},te=(e,t=24,n="currentColor",o=2)=>{let s=Lb[e];return s?Pb(s,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Pb(e,t,n,o){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(o)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(r=>{if(!Array.isArray(r)||r.length<2)return;let a=r[0],i=r[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),s.appendChild(p)}),s}var Wa={allowedTypes:Un,maxFileSize:10*1024*1024,maxFiles:4};function Rb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ib(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var vr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Wa.allowedTypes,maxFileSize:t.maxFileSize??Wa.maxFileSize,maxFiles:t.maxFiles??Wa.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Wa.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Mp(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let s=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,s);continue}try{let s=await Ep(n),r=La(n)?URL.createObjectURL(n):null,a={id:Rb(),file:n,previewUrl:r,contentPart:s};this.attachments.push(a),this.renderPreview(a)}catch(s){console.error("[AttachmentManager] Failed to process file:",s)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(r=>r.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=La(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Ib(t.file.type),p=te(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=kp(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let s=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let r=te("x",10,"var(--persona-text-inverse, #ffffff)",2);r?s.appendChild(r):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(s),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var _p=/\s/;function Wb(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
+ `:o===""||_p.test(o)}function Hb(e,t,n="@",o="anywhere",s=!1){if(!n||t<=0||t>e.length)return null;let r=t-1;for(;r>=0;){let a=e[r];if(a===n)return Wb(e,r,o)?{triggerIndex:r,query:e.slice(r+1,t)}:null;if(a===`
24
+ `||a==="\uFFFC"||!s&&_p.test(a))return null;r--}return null}function $p(e,t,n){for(let o of n){let s=Hb(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(s)return{channel:o,match:s}}return null}function jp(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Up(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}function zp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",s=parseFloat(o)||40,r=Math.round(s*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=te(a,r,"currentColor",1.5);c?d.appendChild(c):d.textContent="+",d.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),n()}),p.appendChild(d);let u=m("div","persona-send-button-tooltip");return u.textContent=i,p.appendChild(u),{button:d,wrapper:p}}var{setLoader:eS,load:Bb}=ur({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var El=Bb;var{setLoader:oS,load:Db}=ur({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var qp=Db;function xs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ne("span",{className:jn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=te(e.iconName??"at-sign",13,"currentColor",2);if(o){let s=m("span","persona-mention-token-icon");s.appendChild(o),n.appendChild(s)}return n.appendChild(Ne("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Vp(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Up(t).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(I=>typeof I.matchCommand=="function")),s=A=>o.some(I=>I.trigger?I.position==="line-start"?A.split(`
25
25
  `).some(O=>O.startsWith(I.trigger)):(I.position==="anywhere"?A:A.split(`
26
- `)[0]).startsWith(I.trigger):!1),r=(A,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:I}))}catch{}},a=_e("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,u=null,y=null,f=null,h=()=>{if(i)return Promise.resolve(i);if(p)return p;let A=Sl().then(I=>(i=I.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:R,emit:r}),i)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===A&&(p=null),null));return p=A,A},C=()=>{zp().then(A=>{let I=A.mountInlineComposer({textarea:e.textarea,renderToken:O=>xs(O,{render:t.renderMentionToken}),onMentionRemoved:O=>i?.untrackMention(O)});c=I.input,u=I.destroy;let _=d;_.replaceWith(I.element),d=I.element,f={next:I.element,prev:_},y?.(I.element,_),i?i.rebindComposer(I.input):p&&p.then(O=>O?.rebindComposer(I.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&C();let E=[],L=new Map;for(let A of n){if(!A.showButton)continue;let I=Up({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(_=>_?.openMenu(A.trigger))}});E.push(I),L.set(A.trigger,I.button)}let R=(A,I,_)=>{let O=L.get(I);O&&(O.setAttribute("aria-expanded",A?"true":"false"),A?O.setAttribute("aria-controls",_):O.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:a,handleInput:A=>{if(i){i.handleInput();return}if(!$p(A))return;let I=d,_=I.selectionStart??0;_p(I.value,_,n)&&h().then(O=>O?.handleInput())},handleKeydown:A=>{if(i?.isMenuOpen())return i.handleKeydown(A);if(A.key==="Backspace"&&i?.hasMentions()&&!f){let I=d,_=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||_)&&i.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async A=>s(A)?(i??await h())?.dispatchInlineCommand(A)??null:null,clear:()=>i?.clear(),prefetch:()=>{Sl().catch(()=>{})},onComposerSwap:A=>{y=A,f&&A(f.next,f.prev)},destroy:()=>{i?.destroy(),u?.();for(let A of E)A.wrapper.remove();a.remove()}}}var Vp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Cs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];Vp(r)&&Vp(s)?n[o]=Cs(r,s):n[o]=s}return n}var gn="min(440px, calc(100vw - 24px))",Tl="440px",Hb={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:gn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Hb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Kp(e,t){if(!(!e&&!t))return e?t?Cs(e,t):e:t}function El(e){return e?{...ft,...e,theme:Kp(ft.theme,e.theme),darkTheme:Kp(ft.darkTheme,e.darkTheme),launcher:{...ft.launcher,...e.launcher,dock:{...ft.launcher?.dock,...e.launcher?.dock},clearChat:{...ft.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...ft.copy,...e.copy},sendButton:{...ft.sendButton,...e.sendButton},statusIndicator:{...ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...ft.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=ft.features?.artifacts,n=e.features?.artifacts,o=ft.features?.scrollToBottom,s=e.features?.scrollToBottom,r=ft.features?.scrollBehavior,a=e.features?.scrollBehavior,i=ft.features?.streamAnimation,p=e.features?.streamAnimation,d=ft.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},y=o===void 0&&s===void 0?void 0:{...o,...s},f=r===void 0&&a===void 0?void 0:{...r,...a},h=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...ft.features,...e.features,...y!==void 0?{scrollToBottom:y}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??ft.suggestionChips,suggestionChipsConfig:{...ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ft.layout,...e.layout,header:{...ft.layout?.header,...e.layout?.header},messages:{...ft.layout?.messages,...e.layout?.messages,avatar:{...ft.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...ft.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...ft.layout?.slots,...e.layout?.slots}},markdown:{...ft.markdown,...e.markdown,options:{...ft.markdown?.options,...e.markdown?.options}},messageActions:{...ft.messageActions,...e.messageActions}}:ft}var Ha="16px",Ba="transparent",Gp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Jp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Xp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:gn,maxWidth:Tl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ha,canvasBackground:Ba},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Gt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gt(e,o):o}function Ml(e){let t={};function n(o,s){for(let[r,a]of Object.entries(o)){let i=`${s}.${r}`;if(typeof a=="string"){let p=Gt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Qp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Yp(e,t){let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];r&&typeof r=="object"&&!Array.isArray(r)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=Yp(r,s):n[o]=s}return n}function Bb(e,t){return t?Yp(e,t):e}function ws(e,t={}){let n={palette:Gp,semantic:Jp,components:Xp},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Bb(n.components,e?.components)};if(t.validate!==!1){let s=Qp(o);if(!s.valid)throw new Error(`Theme validation failed: ${s.errors.map(r=>r.message).join(", ")}`)}if(t.plugins)for(let s of t.plugins)o=s.transform(o);return o}function kl(e){let t=Ml(e),n={};for(let[w,U]of Object.entries(t)){let q=w.replace(/\./g,"-");n[`--persona-${q}`]=U.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Ha,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ba,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let r=n["--persona-components-markdown-heading-h1-fontWeight"];r&&(n["--persona-md-h1-weight"]=r);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let y=d?.toggleGroup;y&&(y.gap&&(n["--persona-toggle-group-gap"]=y.gap),y.borderRadius&&(n["--persona-toggle-group-radius"]=y.borderRadius));let f=d?.artifact;if(f?.toolbar){let w=f.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Gt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let U=Gt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=U}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Gt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Gt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let h=d?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Gt(e,h.background)??h.background));let C=n["--persona-surface"],E=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",R=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",I=!E||E===C,_=I?L:E,O=I?R:E;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??_,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??O,I&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??_,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??_,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??_,n}var Db={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var Ob={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Zp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Da=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Nb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Da()},Ll=e=>Nb(e),Fb=e=>ws(e),_b=e=>{let t=ws(void 0,{validate:!1});return ws({...e,palette:{...t.palette,colors:{...Ob.colors,...e?.palette?.colors}}},{validate:!1})},Ko=e=>{let t=Ll(e),n=Zp(e?.theme),o=Zp(e?.darkTheme);return t==="dark"?_b(Cs(n??{},o??{})):Fb(n)},$b=e=>kl(e),xr=(e,t)=>{let n=Ko(t),o=$b(n);for(let[s,r]of Object.entries(o))e.style.setProperty(s,r);e.setAttribute("data-persona-color-scheme",Ll(t))},As=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Da())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Da());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Pn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function eu(e){let t=Pn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Oa(e){if(typeof e!="string")return"";let t=e.indexOf(`
26
+ `)[0]).startsWith(I.trigger):!1),r=(A,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:I}))}catch{}},a=Ne("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,u=null,y=null,f=null,h=()=>{if(i)return Promise.resolve(i);if(p)return p;let A=El().then(I=>(i=I.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:R,emit:r}),i)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===A&&(p=null),null));return p=A,A},C=()=>{qp().then(A=>{let I=A.mountInlineComposer({textarea:e.textarea,renderToken:O=>xs(O,{render:t.renderMentionToken}),onMentionRemoved:O=>i?.untrackMention(O)});c=I.input,u=I.destroy;let _=d;_.replaceWith(I.element),d=I.element,f={next:I.element,prev:_},y?.(I.element,_),i?i.rebindComposer(I.input):p&&p.then(O=>O?.rebindComposer(I.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&C();let E=[],L=new Map;for(let A of n){if(!A.showButton)continue;let I=zp({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(_=>_?.openMenu(A.trigger))}});E.push(I),L.set(A.trigger,I.button)}let R=(A,I,_)=>{let O=L.get(I);O&&(O.setAttribute("aria-expanded",A?"true":"false"),A?O.setAttribute("aria-controls",_):O.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:a,handleInput:A=>{if(i){i.handleInput();return}if(!jp(A))return;let I=d,_=I.selectionStart??0;$p(I.value,_,n)&&h().then(O=>O?.handleInput())},handleKeydown:A=>{if(i?.isMenuOpen())return i.handleKeydown(A);if(A.key==="Backspace"&&i?.hasMentions()&&!f){let I=d,_=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||_)&&i.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async A=>s(A)?(i??await h())?.dispatchInlineCommand(A)??null:null,clear:()=>i?.clear(),prefetch:()=>{El().catch(()=>{})},onComposerSwap:A=>{y=A,f&&A(f.next,f.prev)},destroy:()=>{i?.destroy(),u?.();for(let A of E)A.wrapper.remove();a.remove()}}}var Kp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Cs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];Kp(r)&&Kp(s)?n[o]=Cs(r,s):n[o]=s}return n}var fn="min(440px, calc(100vw - 24px))",Ml="440px",Ob={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:fn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},ut={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ob,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Gp(e,t){if(!(!e&&!t))return e?t?Cs(e,t):e:t}function ws(e){return e?{...ut,...e,theme:Gp(ut.theme,e.theme),darkTheme:Gp(ut.darkTheme,e.darkTheme),launcher:{...ut.launcher,...e.launcher,dock:{...ut.launcher?.dock,...e.launcher?.dock},clearChat:{...ut.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...ut.copy,...e.copy},sendButton:{...ut.sendButton,...e.sendButton},statusIndicator:{...ut.statusIndicator,...e.statusIndicator},voiceRecognition:{...ut.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=ut.features?.artifacts,n=e.features?.artifacts,o=ut.features?.scrollToBottom,s=e.features?.scrollToBottom,r=ut.features?.scrollBehavior,a=e.features?.scrollBehavior,i=ut.features?.streamAnimation,p=e.features?.streamAnimation,d=ut.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},y=o===void 0&&s===void 0?void 0:{...o,...s},f=r===void 0&&a===void 0?void 0:{...r,...a},h=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...ut.features,...e.features,...y!==void 0?{scrollToBottom:y}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??ut.suggestionChips,suggestionChipsConfig:{...ut.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ut.layout,...e.layout,header:{...ut.layout?.header,...e.layout?.header},messages:{...ut.layout?.messages,...e.layout?.messages,avatar:{...ut.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...ut.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...ut.layout?.slots,...e.layout?.slots}},markdown:{...ut.markdown,...e.markdown,options:{...ut.markdown?.options,...e.markdown?.options}},messageActions:{...ut.messageActions,...e.messageActions}}:ut}var Ha="16px",Ba="transparent",Jp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Xp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Qp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:fn,maxWidth:Ml,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ha,canvasBackground:Ba},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Kt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Kt(e,o):o}function kl(e){let t={};function n(o,s){for(let[r,a]of Object.entries(o)){let i=`${s}.${r}`;if(typeof a=="string"){let p=Kt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Yp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Zp(e,t){let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];r&&typeof r=="object"&&!Array.isArray(r)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=Zp(r,s):n[o]=s}return n}function Nb(e,t){return t?Zp(e,t):e}function Da(e,t={}){let n={palette:Jp,semantic:Xp,components:Qp},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Nb(n.components,e?.components)};if(t.validate!==!1){let s=Yp(o);if(!s.valid)throw new Error(`Theme validation failed: ${s.errors.map(r=>r.message).join(", ")}`)}if(t.plugins)for(let s of t.plugins)o=s.transform(o);return o}function Ll(e){let t=kl(e),n={};for(let[w,z]of Object.entries(t)){let q=w.replace(/\./g,"-");n[`--persona-${q}`]=z.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Ha,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ba,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let r=n["--persona-components-markdown-heading-h1-fontWeight"];r&&(n["--persona-md-h1-weight"]=r);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let y=d?.toggleGroup;y&&(y.gap&&(n["--persona-toggle-group-gap"]=y.gap),y.borderRadius&&(n["--persona-toggle-group-radius"]=y.borderRadius));let f=d?.artifact;if(f?.toolbar){let w=f.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Kt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let z=Kt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=z}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Kt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Kt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Kt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Kt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Kt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let h=d?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Kt(e,h.background)??h.background));let C=n["--persona-surface"],E=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",R=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",I=!E||E===C,_=I?L:E,O=I?R:E;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??_,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??O,I&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??_,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??_,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??_,n}var Fb={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var _b={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},eu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Oa=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",$b=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Oa()},Pl=e=>$b(e),jb=e=>Da(e),Ub=e=>Da({...e,palette:{...e?.palette,colors:{..._b.colors,...e?.palette?.colors}}},{validate:!1}),Ko=e=>{let t=Pl(e),n=eu(e?.theme),o=eu(e?.darkTheme);return t==="dark"?Ub(Cs(n??{},o??{})):jb(n)},zb=e=>Ll(e),xr=(e,t)=>{let n=Ko(t),o=zb(n);for(let[s,r]of Object.entries(o))e.style.setProperty(s,r);e.setAttribute("data-persona-color-scheme",Pl(t))},As=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Oa())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Oa());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Pn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function tu(e){let t=Pn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Na(e){if(typeof e!="string")return"";let t=e.indexOf(`
27
27
  `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),s=o.lastIndexOf(`
28
- `);return(s===-1?o:o.slice(0,s)).split("`\u200B``").join("```")}function Ss(e){let t=eu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function lo(e){switch(Ss(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=eu(e.path);return t?t.toUpperCase():"File"}}}function tu(e){let t=e.markdown??"";return e.file?{filename:Pn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Oa(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Pl="http://www.w3.org/2000/svg";function nu(e){let t=document.createElementNS(Pl,"svg");t.setAttribute("class",jn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Pl,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Pl,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var co=(e,t,n)=>{let o=n;for(let s of t){let r=m("span","persona-tool-char");r.style.setProperty("--char-index",String(o)),r.textContent=s===" "?"\xA0":s,e.appendChild(r),o++}return o};function ou(e,t,n){let o=n?.loadingAnimation??"shimmer",s=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${s}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${s}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),co(e,t,0)}var Rl="persona-artifact-status-label",ru="persona-artifact-status-detail",su="data-artifact-status-label",Il=new Map,au=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Cr(e){e&&Il.delete(e)}function jb(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?lo(t):e.artifactType==="component"?"Component":"Document"}function wr(e,t,n){let o=jb(e),s=`Generating ${o.toLowerCase()}...`,r=t?.statusLabel;if(typeof r=="string")return{label:r};if(typeof r!="function")return{label:s};let a=e.id,i=Il.get(a);e.status!=="complete"&&i===void 0&&(i=au(),Il.set(a,i));let p=i===void 0?0:Math.max(0,au()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,y=d||c===""?0:c.split(`
29
- `).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:y,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=r(h);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:s}}catch{return{label:s}}}function Ub(e){e.className=Rl,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Go(e,t,n){let o=e.querySelector(`:scope > .${Rl}`);o||(o=m("span",Rl),e.appendChild(o)),o.getAttribute(su)!==t.label&&(Ub(o),ou(o,t.label,n),o.setAttribute(su,t.label));let s=e.querySelector(`:scope > .${ru}`),r=t.detail;r?(s||(s=m("span",ru),e.appendChild(s)),s.textContent!==r&&(s.textContent=r)):s&&s.remove()}var zb={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},qb=15e4,Na={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Vb(e,t){let n=(e||"").trim().toLowerCase();if(n&&Na[n])return Na[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let s=t.slice(o+1).toLowerCase();if(Na[s])return Na[s]}}return null}function Fa(e,t){let n=[],o=0,s=0,r=a=>{a>s&&n.push({type:"plain",value:e.slice(s,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){r(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,s=o,a=!0;break}}a||(o+=1)}return r(e.length),n}var Kb=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Gb=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Kb.has(e)?"keyword":"plain"}];function iu(e){return Fa(e,Gb)}var Jb=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Xb(e){let t=Fa(e,Jb);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let s=t[o];s&&s.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var Qb=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function lu(e){let t=Fa(e,Qb),n="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(s.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(s.type="property")}let r=s.value.replace(/\s+$/,"");r&&(n=r[r.length-1])}return t}var Yb=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function Zb(e){let t=[],n=(r,a)=>{a&&t.push({type:r,value:a})},o=e.length,s=0;for(;s<o;){if(e.startsWith("<!--",s)){let a=e.indexOf("-->",s+4),i=a===-1?o:a+3;n("comment",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&e[s+1]==="!"){let a=e.indexOf(">",s),i=a===-1?o:a+1;n("tag",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&/[A-Za-z/]/.test(e[s+1]||"")){let a=e.indexOf(">",s),i=a===-1?o:a+1,p=e.slice(s,i);for(let c of Fa(p,Yb))t.push(c);s=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),y=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(s)),f=y?s+y.index:o,h=e.slice(s,f),C=c==="script"?iu(h):lu(h);for(let E of C)t.push(E);s=f}continue}let r=e.indexOf("<",s);if(r===s)n("plain",e[s]),s+=1;else{let a=r===-1?o:r;n("plain",e.slice(s,a)),s=a}}return t}function ev(e,t){switch(t){case"html":return Zb(e);case"css":return lu(e);case"js":return iu(e);case"json":return Xb(e)}}function tv(e){let t=Zd(),n=m("span","persona-code-line"),o=(s,r)=>{if(!r)return;let a=zb[s];if(a){let i=m("span",a);i.textContent=r,n.appendChild(i)}else n.appendChild(document.createTextNode(r))};for(let s of e){let r=s.value.split(`
28
+ `);return(s===-1?o:o.slice(0,s)).split("`\u200B``").join("```")}function Ss(e){let t=tu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function lo(e){switch(Ss(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=tu(e.path);return t?t.toUpperCase():"File"}}}function nu(e){let t=e.markdown??"";return e.file?{filename:Pn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Na(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Rl="http://www.w3.org/2000/svg";function ou(e){let t=document.createElementNS(Rl,"svg");t.setAttribute("class",jn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Rl,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Rl,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var co=(e,t,n)=>{let o=n;for(let s of t){let r=m("span","persona-tool-char");r.style.setProperty("--char-index",String(o)),r.textContent=s===" "?"\xA0":s,e.appendChild(r),o++}return o};function ru(e,t,n){let o=n?.loadingAnimation??"shimmer",s=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${s}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${s}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),co(e,t,0)}var Il="persona-artifact-status-label",su="persona-artifact-status-detail",au="data-artifact-status-label",Wl=new Map,iu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Cr(e){e&&Wl.delete(e)}function qb(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?lo(t):e.artifactType==="component"?"Component":"Document"}function wr(e,t,n){let o=qb(e),s=`Generating ${o.toLowerCase()}...`,r=t?.statusLabel;if(typeof r=="string")return{label:r};if(typeof r!="function")return{label:s};let a=e.id,i=Wl.get(a);e.status!=="complete"&&i===void 0&&(i=iu(),Wl.set(a,i));let p=i===void 0?0:Math.max(0,iu()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,y=d||c===""?0:c.split(`
29
+ `).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:y,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=r(h);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:s}}catch{return{label:s}}}function Vb(e){e.className=Il,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Go(e,t,n){let o=e.querySelector(`:scope > .${Il}`);o||(o=m("span",Il),e.appendChild(o)),o.getAttribute(au)!==t.label&&(Vb(o),ru(o,t.label,n),o.setAttribute(au,t.label));let s=e.querySelector(`:scope > .${su}`),r=t.detail;r?(s||(s=m("span",su),e.appendChild(s)),s.textContent!==r&&(s.textContent=r)):s&&s.remove()}var Kb={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},Gb=15e4,Fa={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Jb(e,t){let n=(e||"").trim().toLowerCase();if(n&&Fa[n])return Fa[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let s=t.slice(o+1).toLowerCase();if(Fa[s])return Fa[s]}}return null}function _a(e,t){let n=[],o=0,s=0,r=a=>{a>s&&n.push({type:"plain",value:e.slice(s,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){r(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,s=o,a=!0;break}}a||(o+=1)}return r(e.length),n}var Xb=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Qb=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Xb.has(e)?"keyword":"plain"}];function lu(e){return _a(e,Qb)}var Yb=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Zb(e){let t=_a(e,Yb);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let s=t[o];s&&s.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var ev=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function cu(e){let t=_a(e,ev),n="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(s.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(s.type="property")}let r=s.value.replace(/\s+$/,"");r&&(n=r[r.length-1])}return t}var tv=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function nv(e){let t=[],n=(r,a)=>{a&&t.push({type:r,value:a})},o=e.length,s=0;for(;s<o;){if(e.startsWith("<!--",s)){let a=e.indexOf("-->",s+4),i=a===-1?o:a+3;n("comment",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&e[s+1]==="!"){let a=e.indexOf(">",s),i=a===-1?o:a+1;n("tag",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&/[A-Za-z/]/.test(e[s+1]||"")){let a=e.indexOf(">",s),i=a===-1?o:a+1,p=e.slice(s,i);for(let c of _a(p,tv))t.push(c);s=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),y=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(s)),f=y?s+y.index:o,h=e.slice(s,f),C=c==="script"?lu(h):cu(h);for(let E of C)t.push(E);s=f}continue}let r=e.indexOf("<",s);if(r===s)n("plain",e[s]),s+=1;else{let a=r===-1?o:r;n("plain",e.slice(s,a)),s=a}}return t}function ov(e,t){switch(t){case"html":return nv(e);case"css":return cu(e);case"js":return lu(e);case"json":return Zb(e)}}function rv(e){let t=ep(),n=m("span","persona-code-line"),o=(s,r)=>{if(!r)return;let a=Kb[s];if(a){let i=m("span",a);i.textContent=r,n.appendChild(i)}else n.appendChild(document.createTextNode(r))};for(let s of e){let r=s.value.split(`
30
30
  `);for(let a=0;a<r.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
31
- `)),n=m("span","persona-code-line")),o(s.type,r[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function cu(e,t,n){let o=e.length<=qb?Vb(t,n):null,s=o?ev(e,o):[{type:"plain",value:e}];return tv(s)}var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,po=Ut+1;function Jo(e){let{items:t,onSelect:n,anchor:o,position:s="bottom-left",portal:r}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),r?(a.style.position="fixed",a.style.zIndex=String(po)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let E=ne(f.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let C=document.createElement("span");C.textContent=f.label,h.appendChild(C),h.addEventListener("click",E=>{E.stopPropagation(),c(),n(f.id)}),a.appendChild(h)}let i=null;function p(){if(!r)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!a.contains(h.target)&&!o.contains(h.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function y(){c(),a.remove()}return r&&r.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:y}}function mt(e){let{icon:t,label:n,size:o,strokeWidth:s,className:r,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(r?" "+r:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ne(t,o??16,"currentColor",s??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))p.setAttribute(c,u);return p}function uo(e){let{icon:t,label:n,variant:o="default",size:s="sm",iconSize:r,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+s,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let y=ne(t,r??14,"currentColor",2);y&&c.appendChild(y)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[y,f]of Object.entries(p))c.setAttribute(y,f);return c}function fo(e){let{items:t,selectedId:n,onSelect:o,className:s}=e,r=m("div","persona-toggle-group"+(s?" "+s:""));r.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=mt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),r.appendChild(u)}function d(c){a=c,p()}return{element:r,setSelected:d}}function Wl(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:s,position:r="bottom-left",portal:a,className:i,hover:p}=e,d=m("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ne(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let y=Jo({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),s(f)},anchor:d,position:r,portal:a});return a||d.appendChild(y.element),d.addEventListener("click",f=>{f.stopPropagation();let h=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),y.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),y.show()},close:()=>{d.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let f=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),d.remove()}}}var _a="persona-artifact-custom-action-btn";function Ar(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let s="persona-label-btn persona-label-btn--sm "+_a+(n?" persona-artifact-doc-copy-btn":"");o=m("button",s)}else{let s="persona-icon-btn "+_a+(n?" persona-artifact-doc-icon-btn":"");o=m("button",s)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let s=e.icon();s&&o.appendChild(s)}catch{}if(e.showLabel){let s=m("span");s.textContent=e.label,o.appendChild(s)}}else e.showLabel||!e.icon?o=uo({icon:e.icon,label:e.label,className:_a+(n?" persona-artifact-doc-copy-btn":"")}):o=mt({icon:e.icon,label:e.label,className:_a+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ts(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function du(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=n?Pn(n.path):o,r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?lo(n):i==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${s} in artifact panel`),r&&d.setAttribute("data-open-artifact",r);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let y=document.createElement("div");y.className="persona-truncate persona-text-sm persona-font-medium",y.style.color="var(--persona-text, #1f2937)",y.textContent=s;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let h=t?.config?.features?.artifacts,C={id:r,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},E=wr(C,h,"card");Go(f,E,h)}else r&&Cr(r),f.textContent=p;if(u.append(y,f),d.append(c,u),a==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let E={artifactId:r||null,title:s,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of h)try{if(L.visible===void 0||L.visible(E)){let R=Ar(L);R.setAttribute("data-artifact-custom-action",L.id),R.className=`${R.className} persona-flex-shrink-0`,d.append(R)}}catch{}}let C=uo({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${s}`,C.setAttribute("data-download-artifact",r),d.append(C)}return d}var $a=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>du(e,t)});if(i)return i}return du(e,t)};var go=new WeakMap;function Hl(e,t,n){if(t.length===0)return;let o=new Map(t.map(s=>[s.id,s]));e.querySelectorAll("[data-artifact-inline]").forEach(s=>{let r=go.get(s);if(!r)return;let a=o.get(s.getAttribute("data-artifact-inline")??"");a&&r(a,n)})}function mu(e){return go.has(e)}function nv(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let r=e.componentProps,a=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{}}}function pu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Pn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function ov(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var uu=180,rv=240,sv=.8,av=300,iv=500,lv="cubic-bezier(0.2, 0, 0, 1)",fu=240,cv=.35;function dv(e,t,n){let{swap:o,onSettled:s}=n,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(!t||!e.isConnected||r||typeof e.animate!="function"){o(),s();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:uu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of a)L.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),s();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),s();return}let d=Math.abs(t-p),c=Math.round(Math.min(iv,Math.max(av,rv+d*sv))),u=Math.round(c*cv),y=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=y?y.animate([{opacity:0},{opacity:1}],{duration:fu,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:lv});e.style.height=`${p}px`;let C=!1,E=()=>{C||(C=!0,i(),s())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(c,u+fu)+120)},uu)}function pv(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Es="--persona-artifact-inline-body-height";function uv(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",s=320,r=320,a=t?.height;typeof a=="number"||a==="auto"?(s=a,r=a):a&&typeof a=="object"&&(s=a.streaming??320,r=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let y=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:s,completeHeight:r,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:y,completeDisplay:f}}function gu(e,t){let n=nv(e),o=t.config?.features?.artifacts,{chromeEnabled:s,showCopy:r,showExpand:a,showViewToggle:i}=pv(o),p=o?.inlineActions??[],d=uv(o),c=d.completeDisplay==="card",u=null,y=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=Y=>$a(ov(Y),t),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Es),f.replaceChildren(h(Y)),go.set(f,ce=>{f.replaceChildren(h(ce))})};if(c&&n.status==="complete")return C(n),f;let E=ja(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),L=m("div","persona-artifact-inline-body");L.appendChild(E.el);let R=Y=>{let ce=Y.status!=="complete",Z=ce?d.streamingHeight:d.completeHeight,xe=typeof Z=="number";xe?f.style.setProperty(Es,`${Z}px`):f.style.removeProperty(Es);let me=!!E.el.querySelector(".persona-code-pre"),ue=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",me),L.classList.toggle("persona-artifact-inline-body--sized",xe&&ue),L.classList.toggle("persona-artifact-inline-body--cap",!ce&&!ue&&typeof d.completeHeight=="number")},A=n.status,I=(Y,ce)=>{A!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(Es,`${d.completeHeight}px`):f.style.removeProperty(Es),yu(L,ce?.suppressTransition?"none":d.transition,Y.id,()=>{E.update(Y),R(Y)})):E.update(Y),R(Y),A=Y.status};R(n);let _=d.overflow==="clip"&&a&&!!n.id;if(_&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${pu(n).title} in panel`)),!s)return f.appendChild(L),go.set(f,I),f;let O=m("div","persona-artifact-inline-chrome");O.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),U=m("span","persona-flex persona-items-center persona-flex-shrink-0"),q=ne("file-text",16,"currentColor",2);q&&U.appendChild(q);let Q=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");w.append(U,Q,D);let j=m("div","persona-artifact-inline-chrome-actions"),ge=m("span","persona-flex persona-items-center persona-gap-1"),ye=()=>u??d.viewMode,Ee=i?fo({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ye(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let ce=Y==="source"?"source":"rendered";ce!==ye()&&(u=ce,E.update(y),R(y))}}):null,De=r?mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;De&&n.id&&De.setAttribute("data-copy-artifact",n.id);let se=a?mt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&n.id&&se.setAttribute("data-expand-artifact-inline",n.id),j.appendChild(ge),Ee&&j.appendChild(Ee.element),De&&j.appendChild(De),se&&j.appendChild(se),O.append(w,j),f.append(O,L);let be=Y=>{let{title:ce,typeLabel:Z}=pu(Y);Q.textContent=ce,Q.title=ce,_&&L.setAttribute("aria-label",`Open ${ce} in panel`);let xe=Y.status!=="complete";if(xe){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let me=wr(Y,o,"inline-chrome");Go(D,me,o)}else Cr(Y.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Z;if(De&&De.classList.toggle("persona-hidden",xe),Ee){let me=Y.artifactType==="markdown"?Y.file:void 0,ue=!1;if(!xe&&me&&d.viewMode!=="source"){let Pe=Ss(me);Pe==="markdown"?ue=!0:(Pe==="html"||Pe==="svg")&&(ue=o?.filePreview?.enabled!==!1)}Ee.element.classList.toggle("persona-hidden",!ue),Ee.setSelected(ye())}if(ge.replaceChildren(),!xe&&p.length>0){let me=Ts(Y);if(me)for(let ue of p)try{if(ue.visible===void 0||ue.visible(me)){let Pe=Ar(ue,{documentChrome:!0});Pe.setAttribute("data-artifact-custom-action",ue.id),Pe.classList.add("persona-flex-shrink-0"),ge.appendChild(Pe)}}catch{}}};return be(n),go.set(f,(Y,ce)=>{if(c&&A!=="complete"&&Y.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let xe=Y,me=!1,ue=Pe=>{xe=Pe,me=!0};go.set(f,ue),dv(f,Z,{swap:()=>{C(xe),me=!1,go.set(f,ue)},onSettled:()=>{me?C(xe):go.set(f,Pe=>{f.replaceChildren(h(Pe))})}});return}(Y.status!=="complete"||Y.id!==y.id)&&(u=null),y=Y,I(Y,ce),be(Y)}),f}var hu=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>gu(e,t)});if(i)return i}return gu(e,t)};var Bl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Rn=new Bl;Rn.register("PersonaArtifactCard",$a,{bubbleChrome:!1});Rn.register("PersonaArtifactInline",hu,{bubbleChrome:!1});function Ms(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Oa(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Dl=!1;function fv(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function yu(e,t,n,o){let s=typeof document<"u"?document.startViewTransition:void 0,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(t!=="auto"||!e||typeof s!="function"||Dl||r){o();return}Dl=!0;let a=fv(n);e.style.setProperty("view-transition-name",a);let i=()=>{Dl=!1,e.style.removeProperty("view-transition-name")};try{s.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var gv="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",mv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function hv(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function yv(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var bv=220;function vv(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function xv(e){return`
32
- <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Cv(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let s=m("div","persona-artifact-frame-loading-indicator");s.appendChild(nu());let r=null;return n.label!==!1&&(r=m("div","persona-artifact-frame-loading-text"),r.textContent=n.label,s.appendChild(r)),o.appendChild(s),{el:o,revealLabel:()=>{r&&r.classList.add("persona-artifact-frame-loading-text--visible")}}}function wv(e,t,n,o,s,r){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(A=>clearTimeout(A)),d.clear()},u=(A,I)=>{let _=setTimeout(()=>{d.delete(_),A()},I);d.add(_)},y=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let A=Cv(s,r,o);a=A.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},h=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(y,bv))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",R)},E=()=>{if(p||(p=!0,C(),c(),!a))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-i));A>0?u(h,A):h()};function L(A){if(n===null)return;let I=A.data;!I||I.persona!=="artifact-preview-ready"||I.token!==n||A.source===t.contentWindow&&E()}function R(){let A=I=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>I()):setTimeout(I,0)};A(()=>A(()=>E()))}return u(f,o.delayMs),u(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",R),()=>{p=!0,c(),C(),y()}}function ja(e,t){let{config:n}=t,o=t.registry??Rn,s=t.bodyLayout,r=n.markdown?fr(n.markdown):null,a=ss(n.sanitize),i=e,p=!1,d=se=>{let be=_n()!==null;r&&!be&&!p&&(p=!0,rs(()=>De(i)));let Y=r?r(se):$n(se);return r&&be&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,y=null,f=null,h=()=>{f&&(f(),f=null),u=null,y=null},C=null,E=null,L=null,R=!1,A=()=>{C=null,E=null,L=null,R=!1},I=null,_=null,O=()=>{I=null,_=null},w=40,U=0,q=se=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>se()):setTimeout(se,0),Q=se=>se.scrollHeight-se.clientHeight-se.scrollTop<=w,D=se=>{if(!s)return;let be=se.scrollHeight-se.clientHeight>1,Y=se.scrollHeight-se.clientHeight-se.scrollTop;se.classList.toggle("persona-artifact-fade-top",s.fadeTop&&be&&se.scrollTop>1),se.classList.toggle("persona-artifact-fade-bottom",s.fadeBottom&&be&&Y>1)},j=se=>{U||(U=q(()=>{U=0,se.scrollTop=se.scrollHeight,D(se)}))},ge=(se,be,Y,ce)=>{let Z=!!s,xe=Y.id+"|"+(Z?"w":"p");if(!C||L!==xe||C.parentElement!==c){h(),O(),c.replaceChildren();let Pe=m("pre",gv+" persona-code-pre"),Oe=m("code","persona-code");if(Pe.appendChild(Oe),Z){let Ue=m("div","persona-artifact-source-window");if(Ue.appendChild(Pe),c.appendChild(Ue),!(s?.overflow==="clip")&&typeof Ue.addEventListener=="function"){let we=()=>Ue.scrollHeight-Ue.clientHeight>1;Ue.addEventListener("scroll",()=>{Q(Ue)&&(R=!1),D(Ue)},{passive:!0}),Ue.addEventListener("wheel",Le=>{we()&&Le.deltaY<0&&(R=!0)},{passive:!0}),Ue.addEventListener("touchmove",()=>{we()&&(R=!0)},{passive:!0})}C=Ue}else c.appendChild(Pe),C=Pe;E=Oe,L=xe}let me=Z?C:null;me&&(me.classList.toggle("persona-artifact-source-window--fixed",ce),me.classList.toggle("persona-artifact-source-window--clip",ce&&s?.overflow==="clip"));let ue=me?Q(me):!0;if(E.replaceChildren(cu(se,be?.language,be?.path)),me){let Pe=Y.status!=="complete";ce&&Pe&&s?.followOutput&&!R&&ue?j(me):Pe||(R=!1),D(me)}},ye=se=>{h(),A(),O(),c.replaceChildren();let be=m("div",mv);be.innerHTML=d(se),c.appendChild(be)},Ee=se=>{let be=se.id,Y=n.features?.artifacts,ce=wr(se,Y,"status-body");if(I&&_===be&&I.parentElement===c){let me=I.querySelector(".persona-artifact-status-view-text");me&&Go(me,ce,Y);return}h(),A(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),xe=m("div","persona-artifact-status-view-text");Go(xe,ce,Y),Z.appendChild(xe),c.appendChild(Z),I=Z,_=be},De=se=>{i=se;let be=t.resolveViewMode?.(se)??s?.viewMode??"rendered",Y=se.artifactType==="markdown"?se.file:void 0,ce=se.status!=="complete";ce||Cr(se.id);let Z=ce?s?.streamingHeight:s?.completeHeight,xe=!!s&&typeof Z=="number";if(s?.streamingView==="status"&&ce){Ee(se);return}if(Y){let ue=Oa(se.markdown??""),Pe=Ss(Y),Oe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ce&&be==="rendered"&&Oe&&(Pe==="html"||Pe==="svg")){let Ne=se.id+"\0"+ue;if(u&&y===Ne&&u.parentElement===c)return;A(),O(),h(),c.replaceChildren();let we=n.features?.artifacts?.filePreview,Le=we?.iframeSandbox??"allow-scripts";!we?.dangerouslyAllowSameOrigin&&Le.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Le=Le.split(/\s+/).filter(yt=>yt&&yt!=="allow-same-origin").join(" "));let ot=yv(we?.loading),ie=m("div","persona-artifact-frame"),Re=m("iframe","persona-artifact-iframe");Re.setAttribute("sandbox",Le),Re.setAttribute("data-artifact-id",se.id);let xt=null;ot.enabled&&ot.injectReadySignal?(xt=vv(),Re.srcdoc=ue+xv(xt)):Re.srcdoc=ue,ie.appendChild(Re),c.appendChild(ie),ot.enabled&&(f=wv(ie,Re,xt,ot,se.id,n)),u=ie,y=Ne;return}if(h(),!ce&&Pe==="markdown"&&be==="rendered"){ye(ue);return}ge(ue,{language:Y.language,path:Y.path},se,xe);return}if(se.artifactType==="markdown"){if(be==="source"){h(),ge(se.markdown??"",void 0,se,xe);return}ye(se.markdown??"");return}h(),A(),O(),c.replaceChildren();let me=se.component?o.get(se.component):void 0;if(me){let Pe={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Oe=me(se.props??{},Pe);if(Oe){c.appendChild(Oe);return}}catch{}}c.appendChild(hv(se))};return De(e),{el:c,update(se){De(se)}}}import{Idiomorph as Av}from"idiomorph";var Ua=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Av.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,r){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return r instanceof HTMLElement&&r.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(r instanceof HTMLElement&&!r.hasAttribute("data-preserve-animation"))return;if(r instanceof HTMLElement&&r.hasAttribute("data-preserve-animation")){let a=s.textContent??"",i=r.textContent??"";if(a!==i)return}return!1}}}}})};var bu=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Ol={index:-1,draft:""};function vu(e){let{direction:t,history:n,currentValue:o,atStart:s,state:r}=e,a=r.index!==-1;if(n.length===0)return{handled:!1,state:r};if(t==="up"){if(!a&&!s)return{handled:!1,state:r};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(r.index>0){let i=r.index-1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,state:r}}if(!a)return{handled:!1,state:r};if(r.index<n.length-1){let i=r.index+1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,value:r.draft,state:{index:-1,draft:r.draft}}}function xu(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Cu(){return new Map}function wu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Au(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Su(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function za(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function In(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function mo(e,t){return In(e)-e.scrollTop<=t}function qa(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:s,userScrollThreshold:r,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<r?{action:"none",delta:c,nextLastScrollTop:n}:!t&&s&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!s?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Va(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&o?"resume":"none"}function Tu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Eu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Mu(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var ks={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Sv=["pre","code","a","script","style"],Ka=e=>({type:e?.type??ks.type,placeholder:e?.placeholder??ks.placeholder,speed:e?.speed??ks.speed,duration:e?.duration??ks.duration,buffer:e?.buffer??ks.buffer}),Lu=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Ls=new Map;for(let e of Lu)Ls.set(e.name,e);var Tv=e=>{Ls.set(e.name,e)},Ev=e=>{Lu.some(t=>t.name===e)||Ls.delete(e)},Mv=()=>Array.from(Ls.keys()),Sr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ls.get(e)??null,Ga=(e,t,n,o,s)=>{if(!s)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let r=e.search(/\s(?=\S*$)/);return r<0?"":e.slice(0,r)}if(t==="line"){let r=e.lastIndexOf(`
33
- `);return r<0?"":e.slice(0,r)}return e},kv=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${o}`,s.style.setProperty("--char-index",String(o)),s.textContent=t,s},Lv=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${o}`,s.style.setProperty("--word-index",String(o)),s.textContent=t,s},Nl=/\s/,Pv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Rv=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=0;for(;i<r.length;)if(Nl.test(r[i])){let p=i;for(;p<r.length&&Nl.test(r[p]);)p+=1;a.appendChild(o.createTextNode(r.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<r.length&&!Nl.test(r[d]);)p.appendChild(kv(o,r[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}s.replaceChild(a,e)},Iv=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=r.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(Lv(o,p,t,n.value)),n.value+=1));s.replaceChild(a,e)},Ps=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let s=document.createElement("div");s.innerHTML=e;let r=new Set((o?.skipTags??Sv).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)Pv(p,r)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Rv:Iv;for(let u of i)c(u,n,d);return s.innerHTML},Ja=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Rs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},ku=new WeakMap,Wv=(e,t)=>{if(!e.styles)return;let n=ku.get(t);if(n||(n=new Set,ku.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},Fl=new WeakMap,Hv=(e,t)=>{if(!e.onAttach)return;let n=Fl.get(t);if(n||(n=new Map,Fl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Pu=e=>{let t=Fl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Xa=(e,t)=>{Wv(e,t),Hv(e,t)};function _l(e,t=Ut){let n=e.style.position,o=e.style.zIndex,s=e.style.isolation,r=getComputedStyle(e),a=r.position==="static"||r.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=s}}var Is=0,ho=null;function $l(e=document){if(Is++,Is===1){let n=e.body,s=(e.defaultView??window).scrollY||e.documentElement.scrollTop;ho={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Is=Math.max(0,Is-1),Is===0&&ho)){let n=e.body,o=e.defaultView??window;n.style.overflow=ho.originalOverflow,n.style.position=ho.originalPosition,n.style.top=ho.originalTop,n.style.width=ho.originalWidth,o.scrollTo(0,ho.scrollY),ho=null}}}var Ws={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Bt=e=>(e?.launcher?.mountMode??"floating")==="docked",yo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",an=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ws.side,width:t?.width??Ws.width,animate:t?.animate??Ws.animate,reveal:t?.reveal??Ws.reveal,maxHeight:t?.maxHeight??Ws.maxHeight}};var An={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Bv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Qa=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Bv,buttonSize:s,iconSize:r="28px"}=t,a=e?.launcher??{},i=s??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",y=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),h=_e("button",{className:jn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Jt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ne(u,r,"currentColor",1);if(C?(C.style.display="block",h.appendChild(C)):h.textContent=y,p.appendChild(h),c&&d){let E=null,L=()=>{if(E)return;let A=h.ownerDocument,I=A.body;if(!I)return;E=kn(A,"div","persona-clear-chat-tooltip"),E.textContent=d;let _=kn(A,"div");_.className="persona-clear-chat-tooltip-arrow",E.appendChild(_);let O=h.getBoundingClientRect();E.style.position="fixed",E.style.zIndex=String(po),E.style.left=`${O.left+O.width/2}px`,E.style.top=`${O.top-8}px`,E.style.transform="translate(-50%, -100%)",I.appendChild(E)},R=()=>{E&&E.parentNode&&(E.parentNode.removeChild(E),E=null)};p.addEventListener("mouseenter",L),p.addEventListener("mouseleave",R),h.addEventListener("focus",L),h.addEventListener("blur",R),p._cleanupTooltip=()=>{R(),p.removeEventListener("mouseenter",L),p.removeEventListener("mouseleave",R),h.removeEventListener("focus",L),h.removeEventListener("blur",R)}}return{button:h,wrapper:p}},Dv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ya=(e,t={})=>{let{wrapperClassName:n=Dv,buttonSize:o,iconSize:s="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",y=a.borderColor??"",f=a.borderRadius??"",h=a.paddingX??"",C=a.paddingY??"",E=a.tooltipText??"Clear chat",L=a.showTooltip??!0,R=m("div",n),A=!!(u||y),I=_e("button",{className:jn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:d||Jt.actionIconColor,backgroundColor:c||void 0,border:A?`${u||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),_=ne(p,s,"currentColor",1);if(_&&(_.style.display="block",I.appendChild(_)),R.appendChild(I),L&&E){let O=null,w=()=>{if(O)return;let q=I.ownerDocument,Q=q.body;if(!Q)return;O=kn(q,"div","persona-clear-chat-tooltip"),O.textContent=E;let D=kn(q,"div");D.className="persona-clear-chat-tooltip-arrow",O.appendChild(D);let j=I.getBoundingClientRect();O.style.position="fixed",O.style.zIndex=String(po),O.style.left=`${j.left+j.width/2}px`,O.style.top=`${j.top-8}px`,O.style.transform="translate(-50%, -100%)",Q.appendChild(O)},U=()=>{O&&O.parentNode&&(O.parentNode.removeChild(O),O=null)};R.addEventListener("mouseenter",w),R.addEventListener("mouseleave",U),I.addEventListener("focus",w),I.addEventListener("blur",U),R._cleanupTooltip=()=>{U(),R.removeEventListener("mouseenter",w),R.removeEventListener("mouseleave",U),I.removeEventListener("focus",w),I.removeEventListener("blur",U)}}return{button:I,wrapper:R}};var Jt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},bo=e=>{let{config:t,showClose:n=!0}=e,o=_e("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=t?.launcher??{},r=s.headerIconSize??"48px",a=s.closeButtonPlacement??"inline",i=s.headerIconHidden??!1,p=s.headerIconName,d=_e("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:r,width:r,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let _=parseFloat(r)||24,O=ne(p,_*.6,"currentColor",1);O?d.replaceChildren(O):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=m("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=r,_.style.width=r,d.replaceChildren(_)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=_e("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),y=_e("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});c.append(u,y),i?o.append(c):o.append(d,c);let f=s.clearChat??{},h=f.enabled??!0,C=f.placement??"inline",E=null,L=null;if(h){let O=Ya(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=O.button,L=O.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&o.appendChild(L)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:A,wrapper:I}=Qa(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(I),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:y,closeButton:A,closeButtonWrapper:I,clearChatButton:E,clearChatButtonWrapper:L}},Tr=(e,t,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",r=o.clearChat?.placement??"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&r==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Ru=e=>{let t=bo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Ov(e,t,n){if(t?.length)for(let o of t){let s=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(s.type="button",s.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let r=ne(o.icon,14,"currentColor",2);r&&s.appendChild(r)}else o.label&&(s.textContent=o.label);if(o.menuItems?.length){let r=m("div","persona-relative");r.appendChild(s);let a=Jo({items:o.menuItems,onSelect:i=>n?.(i),anchor:r,position:"bottom-left"});r.appendChild(a.element),s.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(r)}else s.addEventListener("click",()=>n?.(o.id)),e.appendChild(s)}}var Iu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:r}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=s?.titleMenu,d,c;if(p)d=Wl({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Jt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Jt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Ov(d,s?.trailingActions,s?.onAction??r),s?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let A=s.onTitleClick;d.addEventListener("click",I=>{I.target.closest("button")||A()}),d.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),A())})}let R=s?.titleRowHover;R&&(d.style.borderRadius=R.borderRadius??"10px",d.style.padding=R.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=R.background??"",d.style.borderColor=R.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",y=m("div",""),f=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Jt.actionIconColor;let h=a.closeButtonIconName??"x",C=ne(h,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),y.appendChild(f),i.appendChild(y);let E=m("div");E.style.display="none";let L=m("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:c,headerSubtitle:L,closeButton:f,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},jl={default:Ru,minimal:Iu},Wu=e=>jl[e]??jl.default,Hs=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",r=Wu(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(r.iconHolder.style.display="none"),t.showTitle===!1&&(r.headerTitle.style.display="none"),t.showSubtitle===!1&&(r.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(r.closeButton.style.display="none"),t.showClearChat===!1&&r.clearChatButtonWrapper&&(r.clearChatButtonWrapper.style.display="none")),r};var Za=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let s=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},r=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,s());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:r}},ei=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",s=t.iconName,r=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",y=t.backgroundColor,f=t.textColor,h=m("div","persona-send-button-wrapper"),C=_e("button",{className:jn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!y&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,L=null;if(n){let _=parseFloat(u)||24,O=f?.trim()||"currentColor";s?(E=ne(s,_,O,2),E?C.appendChild(E):C.textContent=o):C.textContent=o,L=ne(r,_,O,2)}else C.textContent=p;let R=null;c&&a&&(R=m("div","persona-send-button-tooltip"),R.textContent=a,h.appendChild(R)),C.setAttribute("aria-label",a),h.appendChild(C);let A="send";return{button:C,wrapper:h,setMode:_=>{if(_===A)return;A=_;let O=_==="stop"?i:a;if(C.setAttribute("aria-label",O),R&&(R.textContent=O),n){if(E&&L){let w=_==="stop"?L:E;C.replaceChildren(w)}}else C.textContent=_==="stop"?d:p}}},ti=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),s=t.provider?.type==="runtype";if(!(o||s))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,y=m("div","persona-send-button-wrapper"),f=_e("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ne(i,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",y.appendChild(f);let E=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&E){let R=m("div","persona-send-button-tooltip");R.textContent=E,y.appendChild(R)}return{button:f,wrapper:y}},ni=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let s=m("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=(t.allowedTypes??Un).join(","),s.multiple=(t.maxFiles??4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=m("div","persona-send-button-wrapper"),c=_e("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ne(r,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",h=>{h.preventDefault(),s.click()}),d.appendChild(c);let y=t.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=y,d.appendChild(f),{button:c,wrapper:d,input:s,previewsContainer:o}},oi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let s=t.visible??!0;o.style.display=s?"":"none";let r=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=r,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=r;return o},ri=()=>_e("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Bs=e=>{let{config:t}=e,n=_e("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=ri(),s=_e("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:r,attachAutoResize:a}=Za(t);a();let i=ei(t),p=ti(t),d=ni(t),c=oi(t);d&&(d.previewsContainer.style.gap="8px",s.append(d.previewsContainer,d.input)),s.append(r);let u=_e("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&y.append(d.wrapper),p&&f.append(p.wrapper),f.append(i.wrapper),u.append(y,f),s.append(u),s.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&r.focus()}),n.append(o,s,c),{footer:n,suggestions:o,composerForm:s,textarea:r,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:y,rightActions:f,setSendButtonMode:i.setMode}};var Hu=()=>{let e=_e("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=ne("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),s=m("span","persona-pill-peek__caret"),r=ne("chevron-up",16,"currentColor",1.5);return r&&s.appendChild(r),e.append(t,o,s),{root:e,textNode:o}},Bu=e=>{let{config:t}=e,n=_e("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ri(),s=oi(t);s.style.display="none";let{textarea:r,attachAutoResize:a}=Za(t);r.style.maxHeight="100px",a();let i=ei(t),p=ti(t),d=ni(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=_e("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let y=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&y.append(p.wrapper),y.append(i.wrapper),c.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&r.focus()}),d&&c.append(d.input),c.append(u,r,y),d&&n.append(d.previewsContainer),n.append(o,c,s);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:r,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:y,setSendButtonMode:i.setMode}};var Du=e=>{let t=e?.launcher?.enabled??!0,n=Bt(e);if(yo(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Ut);let y=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",u.appendChild(y);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:u,panel:y,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return c.style.width=y,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let s=e?.launcher??{},r=s.position&&An[s.position]?An[s.position]:An["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${r} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Ut);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??gn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},Nv=(e,t)=>{let n=m("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:s}=Qa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let r=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(r){let I=Ya(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=I.button,i=I.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=_e("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=_e("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=_e("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=_e("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),y=_e("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),f=m("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(y.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(y,f);let E=_e("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),L=Bu({config:e}),{root:R,textNode:A}=Hu();return n.append(p,s,d,E),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:f,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:R,peekTextNode:A}},Ou=(e,t=!0)=>{if(yo(e))return Nv(e,t);let n=_e("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,s=e?.layout?.showHeader!==!1,r=o?Hs(e,o,{showClose:t}):bo({config:e,showClose:t}),a=_e("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=_e("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=_e("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=_e("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Bt(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=Bs({config:e}),h=e?.layout?.showFooter!==!1;s?Tr(n,r,e):(r.header.style.display="none",Tr(n,r,e)),n.append(a);let C=_e("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:p,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Ul=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
31
+ `)),n=m("span","persona-code-line")),o(s.type,r[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function du(e,t,n){let o=e.length<=Gb?Jb(t,n):null,s=o?ov(e,o):[{type:"plain",value:e}];return rv(s)}var Wt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,po=Ut+1;function Jo(e){let{items:t,onSelect:n,anchor:o,position:s="bottom-left",portal:r}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),r?(a.style.position="fixed",a.style.zIndex=String(po)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let E=te(f.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let C=document.createElement("span");C.textContent=f.label,h.appendChild(C),h.addEventListener("click",E=>{E.stopPropagation(),c(),n(f.id)}),a.appendChild(h)}let i=null;function p(){if(!r)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!a.contains(h.target)&&!o.contains(h.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function y(){c(),a.remove()}return r&&r.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:y}}function gt(e){let{icon:t,label:n,size:o,strokeWidth:s,className:r,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(r?" "+r:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=te(t,o??16,"currentColor",s??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))p.setAttribute(c,u);return p}function uo(e){let{icon:t,label:n,variant:o="default",size:s="sm",iconSize:r,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+s,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let y=te(t,r??14,"currentColor",2);y&&c.appendChild(y)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[y,f]of Object.entries(p))c.setAttribute(y,f);return c}function fo(e){let{items:t,selectedId:n,onSelect:o,className:s}=e,r=m("div","persona-toggle-group"+(s?" "+s:""));r.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=gt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),r.appendChild(u)}function d(c){a=c,p()}return{element:r,setSelected:d}}function Hl(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:s,position:r="bottom-left",portal:a,className:i,hover:p}=e,d=m("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let y=Jo({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),s(f)},anchor:d,position:r,portal:a});return a||d.appendChild(y.element),d.addEventListener("click",f=>{f.stopPropagation();let h=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),y.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),y.show()},close:()=>{d.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let f=!y.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),d.remove()}}}var $a="persona-artifact-custom-action-btn";function Ar(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let s="persona-label-btn persona-label-btn--sm "+$a+(n?" persona-artifact-doc-copy-btn":"");o=m("button",s)}else{let s="persona-icon-btn "+$a+(n?" persona-artifact-doc-icon-btn":"");o=m("button",s)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let s=e.icon();s&&o.appendChild(s)}catch{}if(e.showLabel){let s=m("span");s.textContent=e.label,o.appendChild(s)}}else e.showLabel||!e.icon?o=uo({icon:e.icon,label:e.label,className:$a+(n?" persona-artifact-doc-copy-btn":"")}):o=gt({icon:e.icon,label:e.label,className:$a+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ts(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function pu(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=n?Pn(n.path):o,r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?lo(n):i==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${s} in artifact panel`),r&&d.setAttribute("data-open-artifact",r);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let y=document.createElement("div");y.className="persona-truncate persona-text-sm persona-font-medium",y.style.color="var(--persona-text, #1f2937)",y.textContent=s;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let h=t?.config?.features?.artifacts,C={id:r,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},E=wr(C,h,"card");Go(f,E,h)}else r&&Cr(r),f.textContent=p;if(u.append(y,f),d.append(c,u),a==="complete"){let h=t?.config?.features?.artifacts?.cardActions;if(h&&h.length>0){let E={artifactId:r||null,title:s,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of h)try{if(L.visible===void 0||L.visible(E)){let R=Ar(L);R.setAttribute("data-artifact-custom-action",L.id),R.className=`${R.className} persona-flex-shrink-0`,d.append(R)}}catch{}}let C=uo({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${s}`,C.setAttribute("data-download-artifact",r),d.append(C)}return d}var ja=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>pu(e,t)});if(i)return i}return pu(e,t)};var go=new WeakMap;function Bl(e,t,n){if(t.length===0)return;let o=new Map(t.map(s=>[s.id,s]));e.querySelectorAll("[data-artifact-inline]").forEach(s=>{let r=go.get(s);if(!r)return;let a=o.get(s.getAttribute("data-artifact-inline")??"");a&&r(a,n)})}function hu(e){return go.has(e)}function sv(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let r=e.componentProps,a=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{}}}function uu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Pn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function av(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var fu=180,iv=240,lv=.8,cv=300,dv=500,pv="cubic-bezier(0.2, 0, 0, 1)",gu=240,uv=.35;function fv(e,t,n){let{swap:o,onSettled:s}=n,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(!t||!e.isConnected||r||typeof e.animate!="function"){o(),s();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:fu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of a)L.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),s();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),s();return}let d=Math.abs(t-p),c=Math.round(Math.min(dv,Math.max(cv,iv+d*lv))),u=Math.round(c*uv),y=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=y?y.animate([{opacity:0},{opacity:1}],{duration:gu,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:pv});e.style.height=`${p}px`;let C=!1,E=()=>{C||(C=!0,i(),s())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(c,u+gu)+120)},fu)}function gv(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Es="--persona-artifact-inline-body-height";function mv(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",s=320,r=320,a=t?.height;typeof a=="number"||a==="auto"?(s=a,r=a):a&&typeof a=="object"&&(s=a.streaming??320,r=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let y=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:s,completeHeight:r,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:y,completeDisplay:f}}function mu(e,t){let n=sv(e),o=t.config?.features?.artifacts,{chromeEnabled:s,showCopy:r,showExpand:a,showViewToggle:i}=gv(o),p=o?.inlineActions??[],d=mv(o),c=d.completeDisplay==="card",u=null,y=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=Y=>ja(av(Y),t),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Es),f.replaceChildren(h(Y)),go.set(f,le=>{f.replaceChildren(h(le))})};if(c&&n.status==="complete")return C(n),f;let E=Ua(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),L=m("div","persona-artifact-inline-body");L.appendChild(E.el);let R=Y=>{let le=Y.status!=="complete",Z=le?d.streamingHeight:d.completeHeight,Ce=typeof Z=="number";Ce?f.style.setProperty(Es,`${Z}px`):f.style.removeProperty(Es);let me=!!E.el.querySelector(".persona-code-pre"),pe=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",me),L.classList.toggle("persona-artifact-inline-body--sized",Ce&&pe),L.classList.toggle("persona-artifact-inline-body--cap",!le&&!pe&&typeof d.completeHeight=="number")},A=n.status,I=(Y,le)=>{A!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(Es,`${d.completeHeight}px`):f.style.removeProperty(Es),bu(L,le?.suppressTransition?"none":d.transition,Y.id,()=>{E.update(Y),R(Y)})):E.update(Y),R(Y),A=Y.status};R(n);let _=d.overflow==="clip"&&a&&!!n.id;if(_&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${uu(n).title} in panel`)),!s)return f.appendChild(L),go.set(f,I),f;let O=m("div","persona-artifact-inline-chrome");O.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),z=m("span","persona-flex persona-items-center persona-flex-shrink-0"),q=te("file-text",16,"currentColor",2);q&&z.appendChild(q);let Q=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");w.append(z,Q,D);let j=m("div","persona-artifact-inline-chrome-actions"),ge=m("span","persona-flex persona-items-center persona-gap-1"),be=()=>u??d.viewMode,Ee=i?fo({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:be(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let le=Y==="source"?"source":"rendered";le!==be()&&(u=le,E.update(y),R(y))}}):null,De=r?gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;De&&n.id&&De.setAttribute("data-copy-artifact",n.id);let ae=a?gt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ae&&n.id&&ae.setAttribute("data-expand-artifact-inline",n.id),j.appendChild(ge),Ee&&j.appendChild(Ee.element),De&&j.appendChild(De),ae&&j.appendChild(ae),O.append(w,j),f.append(O,L);let ve=Y=>{let{title:le,typeLabel:Z}=uu(Y);Q.textContent=le,Q.title=le,_&&L.setAttribute("aria-label",`Open ${le} in panel`);let Ce=Y.status!=="complete";if(Ce){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let me=wr(Y,o,"inline-chrome");Go(D,me,o)}else Cr(Y.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Z;if(De&&De.classList.toggle("persona-hidden",Ce),Ee){let me=Y.artifactType==="markdown"?Y.file:void 0,pe=!1;if(!Ce&&me&&d.viewMode!=="source"){let Pe=Ss(me);Pe==="markdown"?pe=!0:(Pe==="html"||Pe==="svg")&&(pe=o?.filePreview?.enabled!==!1)}Ee.element.classList.toggle("persona-hidden",!pe),Ee.setSelected(be())}if(ge.replaceChildren(),!Ce&&p.length>0){let me=Ts(Y);if(me)for(let pe of p)try{if(pe.visible===void 0||pe.visible(me)){let Pe=Ar(pe,{documentChrome:!0});Pe.setAttribute("data-artifact-custom-action",pe.id),Pe.classList.add("persona-flex-shrink-0"),ge.appendChild(Pe)}}catch{}}};return ve(n),go.set(f,(Y,le)=>{if(c&&A!=="complete"&&Y.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let Ce=Y,me=!1,pe=Pe=>{Ce=Pe,me=!0};go.set(f,pe),fv(f,Z,{swap:()=>{C(Ce),me=!1,go.set(f,pe)},onSettled:()=>{me?C(Ce):go.set(f,Pe=>{f.replaceChildren(h(Pe))})}});return}(Y.status!=="complete"||Y.id!==y.id)&&(u=null),y=Y,I(Y,le),ve(Y)}),f}var yu=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>mu(e,t)});if(i)return i}return mu(e,t)};var Dl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Rn=new Dl;Rn.register("PersonaArtifactCard",ja,{bubbleChrome:!1});Rn.register("PersonaArtifactInline",yu,{bubbleChrome:!1});function Ms(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Na(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Ol=!1;function hv(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function bu(e,t,n,o){let s=typeof document<"u"?document.startViewTransition:void 0,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(t!=="auto"||!e||typeof s!="function"||Ol||r){o();return}Ol=!0;let a=hv(n);e.style.setProperty("view-transition-name",a);let i=()=>{Ol=!1,e.style.removeProperty("view-transition-name")};try{s.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var yv="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",bv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function vv(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function xv(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Cv=220;function wv(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Av(e){return`
32
+ <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Sv(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let s=m("div","persona-artifact-frame-loading-indicator");s.appendChild(ou());let r=null;return n.label!==!1&&(r=m("div","persona-artifact-frame-loading-text"),r.textContent=n.label,s.appendChild(r)),o.appendChild(s),{el:o,revealLabel:()=>{r&&r.classList.add("persona-artifact-frame-loading-text--visible")}}}function Tv(e,t,n,o,s,r){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(A=>clearTimeout(A)),d.clear()},u=(A,I)=>{let _=setTimeout(()=>{d.delete(_),A()},I);d.add(_)},y=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let A=Sv(s,r,o);a=A.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},h=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(y,Cv))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",R)},E=()=>{if(p||(p=!0,C(),c(),!a))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-i));A>0?u(h,A):h()};function L(A){if(n===null)return;let I=A.data;!I||I.persona!=="artifact-preview-ready"||I.token!==n||A.source===t.contentWindow&&E()}function R(){let A=I=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>I()):setTimeout(I,0)};A(()=>A(()=>E()))}return u(f,o.delayMs),u(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",R),()=>{p=!0,c(),C(),y()}}function Ua(e,t){let{config:n}=t,o=t.registry??Rn,s=t.bodyLayout,r=n.markdown?fr(n.markdown):null,a=ss(n.sanitize),i=e,p=!1,d=ae=>{let ve=_n()!==null;r&&!ve&&!p&&(p=!0,rs(()=>De(i)));let Y=r?r(ae):$n(ae);return r&&ve&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,y=null,f=null,h=()=>{f&&(f(),f=null),u=null,y=null},C=null,E=null,L=null,R=!1,A=()=>{C=null,E=null,L=null,R=!1},I=null,_=null,O=()=>{I=null,_=null},w=40,z=0,q=ae=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ae()):setTimeout(ae,0),Q=ae=>ae.scrollHeight-ae.clientHeight-ae.scrollTop<=w,D=ae=>{if(!s)return;let ve=ae.scrollHeight-ae.clientHeight>1,Y=ae.scrollHeight-ae.clientHeight-ae.scrollTop;ae.classList.toggle("persona-artifact-fade-top",s.fadeTop&&ve&&ae.scrollTop>1),ae.classList.toggle("persona-artifact-fade-bottom",s.fadeBottom&&ve&&Y>1)},j=ae=>{z||(z=q(()=>{z=0,ae.scrollTop=ae.scrollHeight,D(ae)}))},ge=(ae,ve,Y,le)=>{let Z=!!s,Ce=Y.id+"|"+(Z?"w":"p");if(!C||L!==Ce||C.parentElement!==c){h(),O(),c.replaceChildren();let Pe=m("pre",yv+" persona-code-pre"),Oe=m("code","persona-code");if(Pe.appendChild(Oe),Z){let $e=m("div","persona-artifact-source-window");if($e.appendChild(Pe),c.appendChild($e),!(s?.overflow==="clip")&&typeof $e.addEventListener=="function"){let je=()=>$e.scrollHeight-$e.clientHeight>1;$e.addEventListener("scroll",()=>{Q($e)&&(R=!1),D($e)},{passive:!0}),$e.addEventListener("wheel",Je=>{je()&&Je.deltaY<0&&(R=!0)},{passive:!0}),$e.addEventListener("touchmove",()=>{je()&&(R=!0)},{passive:!0})}C=$e}else c.appendChild(Pe),C=Pe;E=Oe,L=Ce}let me=Z?C:null;me&&(me.classList.toggle("persona-artifact-source-window--fixed",le),me.classList.toggle("persona-artifact-source-window--clip",le&&s?.overflow==="clip"));let pe=me?Q(me):!0;if(E.replaceChildren(du(ae,ve?.language,ve?.path)),me){let Pe=Y.status!=="complete";le&&Pe&&s?.followOutput&&!R&&pe?j(me):Pe||(R=!1),D(me)}},be=ae=>{h(),A(),O(),c.replaceChildren();let ve=m("div",bv);ve.innerHTML=d(ae),c.appendChild(ve)},Ee=ae=>{let ve=ae.id,Y=n.features?.artifacts,le=wr(ae,Y,"status-body");if(I&&_===ve&&I.parentElement===c){let me=I.querySelector(".persona-artifact-status-view-text");me&&Go(me,le,Y);return}h(),A(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),Ce=m("div","persona-artifact-status-view-text");Go(Ce,le,Y),Z.appendChild(Ce),c.appendChild(Z),I=Z,_=ve},De=ae=>{i=ae;let ve=t.resolveViewMode?.(ae)??s?.viewMode??"rendered",Y=ae.artifactType==="markdown"?ae.file:void 0,le=ae.status!=="complete";le||Cr(ae.id);let Z=le?s?.streamingHeight:s?.completeHeight,Ce=!!s&&typeof Z=="number";if(s?.streamingView==="status"&&le){Ee(ae);return}if(Y){let pe=Na(ae.markdown??""),Pe=Ss(Y),Oe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ve==="rendered"&&Oe&&(Pe==="html"||Pe==="svg")){let He=ae.id+"\0"+pe;if(u&&y===He&&u.parentElement===c)return;A(),O(),h(),c.replaceChildren();let je=n.features?.artifacts?.filePreview,Je=je?.iframeSandbox??"allow-scripts";!je?.dangerouslyAllowSameOrigin&&Je.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Je=Je.split(/\s+/).filter(ht=>ht&&ht!=="allow-same-origin").join(" "));let Me=xv(je?.loading),ne=m("div","persona-artifact-frame"),Re=m("iframe","persona-artifact-iframe");Re.setAttribute("sandbox",Je),Re.setAttribute("data-artifact-id",ae.id);let xt=null;Me.enabled&&Me.injectReadySignal?(xt=wv(),Re.srcdoc=pe+Av(xt)):Re.srcdoc=pe,ne.appendChild(Re),c.appendChild(ne),Me.enabled&&(f=Tv(ne,Re,xt,Me,ae.id,n)),u=ne,y=He;return}if(h(),!le&&Pe==="markdown"&&ve==="rendered"){be(pe);return}ge(pe,{language:Y.language,path:Y.path},ae,Ce);return}if(ae.artifactType==="markdown"){if(ve==="source"){h(),ge(ae.markdown??"",void 0,ae,Ce);return}be(ae.markdown??"");return}h(),A(),O(),c.replaceChildren();let me=ae.component?o.get(ae.component):void 0;if(me){let Pe={message:{id:ae.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Oe=me(ae.props??{},Pe);if(Oe){c.appendChild(Oe);return}}catch{}}c.appendChild(vv(ae))};return De(e),{el:c,update(ae){De(ae)}}}import{Idiomorph as Ev}from"idiomorph";var za=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Ev.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,r){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return r instanceof HTMLElement&&r.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(r instanceof HTMLElement&&!r.hasAttribute("data-preserve-animation"))return;if(r instanceof HTMLElement&&r.hasAttribute("data-preserve-animation")){let a=s.textContent??"",i=r.textContent??"";if(a!==i)return}return!1}}}}})};var vu=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Nl={index:-1,draft:""};function xu(e){let{direction:t,history:n,currentValue:o,atStart:s,state:r}=e,a=r.index!==-1;if(n.length===0)return{handled:!1,state:r};if(t==="up"){if(!a&&!s)return{handled:!1,state:r};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(r.index>0){let i=r.index-1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,state:r}}if(!a)return{handled:!1,state:r};if(r.index<n.length-1){let i=r.index+1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,value:r.draft,state:{index:-1,draft:r.draft}}}function Cu(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function wu(){return new Map}function Au(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Su(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Tu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function qa(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function In(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function mo(e,t){return In(e)-e.scrollTop<=t}function Va(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:s,userScrollThreshold:r,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<r?{action:"none",delta:c,nextLastScrollTop:n}:!t&&s&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!s?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Ka(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&o?"resume":"none"}function Eu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Mu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function ku(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var ks={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Mv=["pre","code","a","script","style"],Ga=e=>({type:e?.type??ks.type,placeholder:e?.placeholder??ks.placeholder,speed:e?.speed??ks.speed,duration:e?.duration??ks.duration,buffer:e?.buffer??ks.buffer}),Pu=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Ls=new Map;for(let e of Pu)Ls.set(e.name,e);var kv=e=>{Ls.set(e.name,e)},Lv=e=>{Pu.some(t=>t.name===e)||Ls.delete(e)},Pv=()=>Array.from(Ls.keys()),Sr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ls.get(e)??null,Ja=(e,t,n,o,s)=>{if(!s)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let r=e.search(/\s(?=\S*$)/);return r<0?"":e.slice(0,r)}if(t==="line"){let r=e.lastIndexOf(`
33
+ `);return r<0?"":e.slice(0,r)}return e},Rv=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${o}`,s.style.setProperty("--char-index",String(o)),s.textContent=t,s},Iv=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${o}`,s.style.setProperty("--word-index",String(o)),s.textContent=t,s},Fl=/\s/,Wv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Hv=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=0;for(;i<r.length;)if(Fl.test(r[i])){let p=i;for(;p<r.length&&Fl.test(r[p]);)p+=1;a.appendChild(o.createTextNode(r.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<r.length&&!Fl.test(r[d]);)p.appendChild(Rv(o,r[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}s.replaceChild(a,e)},Bv=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=r.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(Iv(o,p,t,n.value)),n.value+=1));s.replaceChild(a,e)},Ps=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let s=document.createElement("div");s.innerHTML=e;let r=new Set((o?.skipTags??Mv).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)Wv(p,r)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Hv:Bv;for(let u of i)c(u,n,d);return s.innerHTML},Xa=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Rs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Lu=new WeakMap,Dv=(e,t)=>{if(!e.styles)return;let n=Lu.get(t);if(n||(n=new Set,Lu.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},_l=new WeakMap,Ov=(e,t)=>{if(!e.onAttach)return;let n=_l.get(t);if(n||(n=new Map,_l.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Ru=e=>{let t=_l.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Qa=(e,t)=>{Dv(e,t),Ov(e,t)};function $l(e,t=Ut){let n=e.style.position,o=e.style.zIndex,s=e.style.isolation,r=getComputedStyle(e),a=r.position==="static"||r.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=s}}var Is=0,ho=null;function jl(e=document){if(Is++,Is===1){let n=e.body,s=(e.defaultView??window).scrollY||e.documentElement.scrollTop;ho={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Is=Math.max(0,Is-1),Is===0&&ho)){let n=e.body,o=e.defaultView??window;n.style.overflow=ho.originalOverflow,n.style.position=ho.originalPosition,n.style.top=ho.originalTop,n.style.width=ho.originalWidth,o.scrollTo(0,ho.scrollY),ho=null}}}var Ws={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ht=e=>(e?.launcher?.mountMode??"floating")==="docked",yo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",sn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ws.side,width:t?.width??Ws.width,animate:t?.animate??Ws.animate,reveal:t?.reveal??Ws.reveal,maxHeight:t?.maxHeight??Ws.maxHeight}};var An={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Nv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ya=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Nv,buttonSize:s,iconSize:r="28px"}=t,a=e?.launcher??{},i=s??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",y=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),h=Ne("button",{className:jn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Gt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=te(u,r,"currentColor",1);if(C?(C.style.display="block",h.appendChild(C)):h.textContent=y,p.appendChild(h),c&&d){let E=null,L=()=>{if(E)return;let A=h.ownerDocument,I=A.body;if(!I)return;E=kn(A,"div","persona-clear-chat-tooltip"),E.textContent=d;let _=kn(A,"div");_.className="persona-clear-chat-tooltip-arrow",E.appendChild(_);let O=h.getBoundingClientRect();E.style.position="fixed",E.style.zIndex=String(po),E.style.left=`${O.left+O.width/2}px`,E.style.top=`${O.top-8}px`,E.style.transform="translate(-50%, -100%)",I.appendChild(E)},R=()=>{E&&E.parentNode&&(E.parentNode.removeChild(E),E=null)};p.addEventListener("mouseenter",L),p.addEventListener("mouseleave",R),h.addEventListener("focus",L),h.addEventListener("blur",R),p._cleanupTooltip=()=>{R(),p.removeEventListener("mouseenter",L),p.removeEventListener("mouseleave",R),h.removeEventListener("focus",L),h.removeEventListener("blur",R)}}return{button:h,wrapper:p}},Fv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Za=(e,t={})=>{let{wrapperClassName:n=Fv,buttonSize:o,iconSize:s="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",y=a.borderColor??"",f=a.borderRadius??"",h=a.paddingX??"",C=a.paddingY??"",E=a.tooltipText??"Clear chat",L=a.showTooltip??!0,R=m("div",n),A=!!(u||y),I=Ne("button",{className:jn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:d||Gt.actionIconColor,backgroundColor:c||void 0,border:A?`${u||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),_=te(p,s,"currentColor",1);if(_&&(_.style.display="block",I.appendChild(_)),R.appendChild(I),L&&E){let O=null,w=()=>{if(O)return;let q=I.ownerDocument,Q=q.body;if(!Q)return;O=kn(q,"div","persona-clear-chat-tooltip"),O.textContent=E;let D=kn(q,"div");D.className="persona-clear-chat-tooltip-arrow",O.appendChild(D);let j=I.getBoundingClientRect();O.style.position="fixed",O.style.zIndex=String(po),O.style.left=`${j.left+j.width/2}px`,O.style.top=`${j.top-8}px`,O.style.transform="translate(-50%, -100%)",Q.appendChild(O)},z=()=>{O&&O.parentNode&&(O.parentNode.removeChild(O),O=null)};R.addEventListener("mouseenter",w),R.addEventListener("mouseleave",z),I.addEventListener("focus",w),I.addEventListener("blur",z),R._cleanupTooltip=()=>{z(),R.removeEventListener("mouseenter",w),R.removeEventListener("mouseleave",z),I.removeEventListener("focus",w),I.removeEventListener("blur",z)}}return{button:I,wrapper:R}};var Gt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},bo=e=>{let{config:t,showClose:n=!0}=e,o=Ne("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=t?.launcher??{},r=s.headerIconSize??"48px",a=s.closeButtonPlacement??"inline",i=s.headerIconHidden??!1,p=s.headerIconName,d=Ne("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:r,width:r,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let _=parseFloat(r)||24,O=te(p,_*.6,"currentColor",1);O?d.replaceChildren(O):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=m("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=r,_.style.width=r,d.replaceChildren(_)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ne("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Gt.titleColor}}),y=Ne("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Gt.subtitleColor}});c.append(u,y),i?o.append(c):o.append(d,c);let f=s.clearChat??{},h=f.enabled??!0,C=f.placement??"inline",E=null,L=null;if(h){let O=Za(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=O.button,L=O.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&o.appendChild(L)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:A,wrapper:I}=Ya(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(I),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:y,closeButton:A,closeButtonWrapper:I,clearChatButton:E,clearChatButtonWrapper:L}},Tr=(e,t,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",r=o.clearChat?.placement??"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&r==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Iu=e=>{let t=bo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function _v(e,t,n){if(t?.length)for(let o of t){let s=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(s.type="button",s.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let r=te(o.icon,14,"currentColor",2);r&&s.appendChild(r)}else o.label&&(s.textContent=o.label);if(o.menuItems?.length){let r=m("div","persona-relative");r.appendChild(s);let a=Jo({items:o.menuItems,onSelect:i=>n?.(i),anchor:r,position:"bottom-left"});r.appendChild(a.element),s.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(r)}else s.addEventListener("click",()=>n?.(o.id)),e.appendChild(s)}}var Wu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:r}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=s?.titleMenu,d,c;if(p)d=Hl({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Gt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Gt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),_v(d,s?.trailingActions,s?.onAction??r),s?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let A=s.onTitleClick;d.addEventListener("click",I=>{I.target.closest("button")||A()}),d.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),A())})}let R=s?.titleRowHover;R&&(d.style.borderRadius=R.borderRadius??"10px",d.style.padding=R.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=R.background??"",d.style.borderColor=R.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",y=m("div",""),f=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Gt.actionIconColor;let h=a.closeButtonIconName??"x",C=te(h,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),y.appendChild(f),i.appendChild(y);let E=m("div");E.style.display="none";let L=m("span");return L.style.display="none",{header:i,iconHolder:E,headerTitle:c,headerSubtitle:L,closeButton:f,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},Ul={default:Iu,minimal:Wu},Hu=e=>Ul[e]??Ul.default,Hs=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",r=Hu(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(r.iconHolder.style.display="none"),t.showTitle===!1&&(r.headerTitle.style.display="none"),t.showSubtitle===!1&&(r.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(r.closeButton.style.display="none"),t.showClearChat===!1&&r.clearChatButtonWrapper&&(r.clearChatButtonWrapper.style.display="none")),r};var ei=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let s=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},r=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,s());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:r}},ti=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",s=t.iconName,r=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",y=t.backgroundColor,f=t.textColor,h=m("div","persona-send-button-wrapper"),C=Ne("button",{className:jn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!y&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,L=null;if(n){let _=parseFloat(u)||24,O=f?.trim()||"currentColor";s?(E=te(s,_,O,2),E?C.appendChild(E):C.textContent=o):C.textContent=o,L=te(r,_,O,2)}else C.textContent=p;let R=null;c&&a&&(R=m("div","persona-send-button-tooltip"),R.textContent=a,h.appendChild(R)),C.setAttribute("aria-label",a),h.appendChild(C);let A="send";return{button:C,wrapper:h,setMode:_=>{if(_===A)return;A=_;let O=_==="stop"?i:a;if(C.setAttribute("aria-label",O),R&&(R.textContent=O),n){if(E&&L){let w=_==="stop"?L:E;C.replaceChildren(w)}}else C.textContent=_==="stop"?d:p}}},ni=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),s=t.provider?.type==="runtype";if(!(o||s))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,y=m("div","persona-send-button-wrapper"),f=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=te(i,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",y.appendChild(f);let E=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&E){let R=m("div","persona-send-button-tooltip");R.textContent=E,y.appendChild(R)}return{button:f,wrapper:y}},oi=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let s=m("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=(t.allowedTypes??Un).join(","),s.multiple=(t.maxFiles??4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=m("div","persona-send-button-wrapper"),c=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=te(r,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",h=>{h.preventDefault(),s.click()}),d.appendChild(c);let y=t.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=y,d.appendChild(f),{button:c,wrapper:d,input:s,previewsContainer:o}},ri=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let s=t.visible??!0;o.style.display=s?"":"none";let r=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=r,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=r;return o},si=()=>Ne("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Bs=e=>{let{config:t}=e,n=Ne("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=si(),s=Ne("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:r,attachAutoResize:a}=ei(t);a();let i=ti(t),p=ni(t),d=oi(t),c=ri(t);d&&(d.previewsContainer.style.gap="8px",s.append(d.previewsContainer,d.input)),s.append(r);let u=Ne("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&y.append(d.wrapper),p&&f.append(p.wrapper),f.append(i.wrapper),u.append(y,f),s.append(u),s.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&r.focus()}),n.append(o,s,c),{footer:n,suggestions:o,composerForm:s,textarea:r,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:y,rightActions:f,setSendButtonMode:i.setMode}};var Bu=()=>{let e=Ne("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),s=m("span","persona-pill-peek__caret"),r=te("chevron-up",16,"currentColor",1.5);return r&&s.appendChild(r),e.append(t,o,s),{root:e,textNode:o}},Du=e=>{let{config:t}=e,n=Ne("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=si(),s=ri(t);s.style.display="none";let{textarea:r,attachAutoResize:a}=ei(t);r.style.maxHeight="100px",a();let i=ti(t),p=ni(t),d=oi(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ne("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let y=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&y.append(p.wrapper),y.append(i.wrapper),c.addEventListener("click",h=>{h.target!==i.button&&h.target!==i.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==d?.button&&h.target!==d?.wrapper&&r.focus()}),d&&c.append(d.input),c.append(u,r,y),d&&n.append(d.previewsContainer),n.append(o,c,s);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:r,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:y,setSendButtonMode:i.setMode}};var Ou=e=>{let t=e?.launcher?.enabled??!0,n=Ht(e);if(yo(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Ut);let y=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",u.appendChild(y);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:u,panel:y,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return c.style.width=y,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let s=e?.launcher??{},r=s.position&&An[s.position]?An[s.position]:An["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${r} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Ut);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??fn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},$v=(e,t)=>{let n=m("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:s}=Ya(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let r=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(r){let I=Za(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=I.button,i=I.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=Ne("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Ne("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),y=Ne("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),f=m("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(y.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(y,f);let E=Ne("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),L=Du({config:e}),{root:R,textNode:A}=Bu();return n.append(p,s,d,E),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:f,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:R,peekTextNode:A}},Nu=(e,t=!0)=>{if(yo(e))return $v(e,t);let n=Ne("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,s=e?.layout?.showHeader!==!1,r=o?Hs(e,o,{showClose:t}):bo({config:e,showClose:t}),a=Ne("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Ne("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Ht(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=Bs({config:e}),h=e?.layout?.showFooter!==!1;s?Tr(n,r,e):(r.header.style.display="none",Tr(n,r,e)),n.append(a);let C=Ne("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:p,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var zl=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
34
34
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
35
35
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
36
36
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -38,14 +38,14 @@ _Details: ${n.message}_`:o}var bs=e=>({isError:!0,content:[{type:"text",text:e}]
38
38
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
39
39
  </span>
40
40
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
41
- `,n.addEventListener("click",t);let o=r=>{let a=r.launcher??{},i=Bt(r),p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let A=a.subtitle??"Here to help you get answers fast";d.textContent=A,d.setAttribute("title",A)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let A=a.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let I=parseFloat(A)||24,_=ne(a.agentIconName,I*.6,"var(--persona-text-inverse, #ffffff)",2);_?(u.appendChild(_),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let A=a.agentIconSize??"40px";y.style.height=A,y.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=a.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let I=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,I=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let _=parseFloat(A)||24,O=Math.max(_-I,8),w=ne(a.callToActionIconName,O,"currentColor",2);w?f.appendChild(w):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let h=a.position&&An[a.position]?An[a.position]:An["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${C} ${h}`,i||(n.style.zIndex=String(a.zIndex??Ut));let L="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:R,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:s}};var Nu=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:s}=Du(e),r=Ou(e,t),a={wrapper:n,panel:o,pillRoot:s},i={container:r.container,body:r.body,messagesWrapper:r.messagesWrapper,composerOverlay:r.composerOverlay,introTitle:r.introTitle,introSubtitle:r.introSubtitle},p={element:r.header,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper},d={footer:r.footer,form:r.composerForm,textarea:r.textarea,sendButton:r.sendButton,sendButtonWrapper:r.sendButtonWrapper,micButton:r.micButton,micButtonWrapper:r.micButtonWrapper,statusText:r.statusText,suggestions:r.suggestions,attachmentButton:r.attachmentButton,attachmentButtonWrapper:r.attachmentButtonWrapper,attachmentInput:r.attachmentInput,attachmentPreviewsContainer:r.attachmentPreviewsContainer,actionsRow:r.actionsRow,leftActions:r.leftActions,rightActions:r.rightActions,setSendButtonMode:r.setSendButtonMode,peekBanner:r.peekBanner,peekTextNode:r.peekTextNode};return{shell:a,panelElements:r,transcript:i,header:p,composer:d,replaceHeader:y=>(p.element.replaceWith(y.header),p.element=y.header,p.iconHolder=y.iconHolder,p.headerTitle=y.headerTitle,p.headerSubtitle=y.headerSubtitle,p.closeButton=y.closeButton,p.closeButtonWrapper=y.closeButtonWrapper,p.clearChatButton=y.clearChatButton,p.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{d.footer.replaceWith(y),d.footer=y}}},zl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(r=>r.renderLauncher);if(o?.renderLauncher){let r=o.renderLauncher({config:e,defaultRenderer:()=>Ul(e,n).element,onToggle:n});if(r)return{instance:null,element:r}}let s=Ul(e,n);return{instance:s,element:s.element}};var Fv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},_v=(e,t)=>{if(!e)return null;let n=Fv(e);if(n===null)return null;let o=t?.[e],s=o!==void 0?o:n;return s||null},$v=(e,t)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},jv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ql=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Vl=320,ju=320,Uv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),zv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),qv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Vv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Kv=e=>{if(!e||e.length===0)return null;let t=_e("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=_e("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=m("span","persona-mention-chip-icon"),r=ne(n.iconName??"at-sign",13,"currentColor",2);r&&s.appendChild(r),o.appendChild(s),o.appendChild(_e("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Gv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(xs(o.ref,{readonly:!0,render:t}))}return n},Fu="\uE000",_u="\uE001",Jv=(e,t,n,o)=>{let s=Math.random().toString(36).slice(2,8),r=y=>`${Fu}${s}:${y}${_u}`,a=t.map((y,f)=>y.kind==="text"?y.text:r(f)).join(""),i=n(a);if(!t.every((y,f)=>y.kind==="text"||i.includes(r(f)))){e.replaceChildren(Gv(t,o));return}e.innerHTML=i;let d=new RegExp(`${Fu}${s}:(\\d+)${_u}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let y=c.nextNode();y;y=c.nextNode())u.push(y);for(let y of u){let f=y;for(let h=d.exec(f.data);h;h=d.exec(f.data)){let C=t[Number(h[1])],E=f.splitText(h.index);E.data=E.data.slice(h[0].length),C?.kind==="mention"&&E.parentNode?.insertBefore(xs(C.ref,{readonly:!0,render:o}),E),f=E}}},Xv=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let s=0,r=!1,a=()=>{r||(r=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=m("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Vl}px`,d.style.maxHeight=`${ju}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;s+=1,d.addEventListener("error",()=>{c||(c=!0,s=Math.max(0,s-1),d.remove(),s===0&&a())}),d.addEventListener("load",()=>{c=!0}),jv(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,s=Math.max(0,s-1),d.remove())}),s===0?(a(),null):o}catch{return n?.(),null}},Qv=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!ql(o.audio))return;let s=m("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Vl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Yv=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!ql(o.video))return;let s=m("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Vl}px`,s.style.maxHeight=`${ju}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Zv=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!ql(o.data))return;let s=m("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Er=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(s),e},Uu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Er};if(t){let s=t(o);if(s!==null)return s}return Er()},ex=(e,t)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=m("img");s.src=o,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},$u=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?o.textContent=t.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},tx=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},zu=(e,t,n)=>{let o=t.showCopy??!0,s=t.showUpvote??!0,r=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!s&&!r&&!a){let h=m("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],y=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id);let f=(h,C,E)=>{let L=mt({icon:h,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",E),L};return o&&y.appendChild(f("copy","Copy message","copy")),a&&y.appendChild(f("volume-2","Read aloud","read-aloud")),s&&y.appendChild(f("thumbs-up","Upvote","upvote")),r&&y.appendChild(f("thumbs-down","Downvote","downvote")),y},Ds=(e,t,n,o,s,r)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,y=p?.position??"left",f=d?.position??"below",h=tx(e.role,i),C=m("div",h.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Uv(e),L=e.content?.trim()??"",A=E.length>0&&L===ka,I=Ka(r?.widgetConfig?.features?.streamAnimation),_=r?.widgetConfig?.features?.streamAnimation?.plugins,O=e.role==="assistant"&&I.type!=="none"?Sr(I.type,_):null,w=e.role==="assistant"&&O?.isAnimating?.(e)===!0,U=e.role==="assistant"&&O!==null&&(!!e.streaming||w);U&&O?.bubbleClass&&C.classList.add(O.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),U&&O&&(O.containerClass&&q.classList.add(O.containerClass),q.style.setProperty("--persona-stream-step",`${I.speed}ms`),q.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let Q=U?Ga(e.content??"",I.buffer,O,e,!!e.streaming):e.content??"",D=()=>{let Z=t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent});return U&&O?.wrap==="char"?Ps(Z,"char",e.id,{skipTags:O.skipTags}):U&&O?.wrap==="word"?Ps(Z,"word",e.id,{skipTags:O.skipTags}):Z},j=null;if(A?(j=document.createElement("div"),j.innerHTML=D(),j.style.display="none",q.appendChild(j)):e.contentSegments?.length?Jv(q,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),r?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=D(),U&&O?.useCaret&&!A&&L){let Z=Ja(),xe=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),me=xe[xe.length-1];if(me?.parentNode)me.parentNode.insertBefore(Z,me.nextSibling);else{let ue=q.lastElementChild;ue?ue.appendChild(Z):q.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=$u(e,d,"span");Z.classList.add("persona-timestamp-inline");let xe=q.lastElementChild;xe?xe.appendChild(Z):q.appendChild(Z)}if(E.length>0){let Z=Xv(E,!A&&!!L,()=>{A&&j&&(j.style.display="")});Z?C.appendChild(Z):A&&j&&(j.style.display="")}let ge=zv(e);if(ge.length>0){let Z=Qv(ge);Z&&C.appendChild(Z)}let ye=qv(e);if(ye.length>0){let Z=Yv(ye);Z&&C.appendChild(Z)}let Ee=Vv(e);if(Ee.length>0){let Z=Zv(Ee);Z&&C.appendChild(Z)}let De=e.contentSegments?.length?null:Kv(e.contextMentions);if(De&&C.appendChild(De),C.appendChild(q),u&&f==="below"&&e.createdAt){let Z=$u(e,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let se=e.role==="assistant"?_v(e.stopReason,r?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(Q&&Q.trim()),xe=I.placeholder==="skeleton",me=xe&&I.buffer==="line"&&Z;if(Z)me&&C.appendChild(Rs());else if(xe)C.appendChild(Rs());else{let ue=Uu("inline",r?.loadingIndicatorRenderer,r?.widgetConfig);ue&&C.appendChild(ue)}}if(se&&e.stopReason&&!e.streaming&&(L||(q.style.display="none"),C.appendChild($v(e.stopReason,se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=zu(e,o,s);C.appendChild(Z)}if(!c||e.role==="system")return C;let Y=m("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ce=ex(p,e.role);return y==="right"||y==="left"&&e.role==="user"?Y.append(C,ce):Y.append(ce,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},nx=(e,t,n,o,s,r)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ds(e,t,n,o,s,r)};var Mr=new Set,ox=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),rx=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
- `):""},qu=(e,t)=>{let n=Mr.has(e),o=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),r=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!s)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=ne(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",r&&(r.style.display=n?"none":r.textContent||r.childNodes.length?"":"none")},Kl=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let s=t?.features?.reasoningDisplay??{},r=s.expandable!==!1,a=r&&Mr.has(e.id),i=n.status!=="complete",p=rx(e,s.previewMaxLines??3),d=m("button",r?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",r&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),C=()=>{let ye=m("span","");return ye.setAttribute("data-tool-elapsed",h),ye.textContent=Ta(n),ye},E=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:p,isActive:i,config:t??{},elapsed:Ta(n),createElapsedElement:C});typeof E=="string"&&E.trim()?(u.textContent=E,c.appendChild(u)):E instanceof HTMLElement?c.appendChild(E):(u.textContent=y,c.appendChild(u));let L=m("span","persona-text-xs persona-text-persona-primary");L.textContent=xp(n),c.appendChild(L);let R=s.loadingAnimation??"none",A=f.activeTextTemplate,I=f.completeTextTemplate,_=i?A:I,O=E instanceof HTMLElement,w=(ye,Ee)=>{u.textContent="";let De=Ea(ye,""),se=0;for(let be of De){let Y=be.styles.length>0?(()=>{let ce=m("span",be.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(ce),ce})():u;if(be.isDuration&&i)Y.appendChild(C());else{let ce=be.isDuration?Ta(n):be.text;Ee?se=co(Y,ce,se):Y.appendChild(document.createTextNode(ce))}}};if(!O&&_)if(L.style.display="none",u.style.display="",i&&R!=="none"){let ye=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),R==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),w(_,!1)):(u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),R==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w(_,!0))}else w(_,!1);else if(!O&&i&&R!=="none"){u.style.display="";let ye=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),R==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`);else{u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),R==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ee=u.textContent||y;u.textContent="",co(u,Ee,0)}n.status==="complete"&&(u.style.display="none")}else O||(n.status==="complete"?u.style.display="none":u.style.display="");let U=null;if(r){U=m("div","persona-flex persona-items-center");let Ee=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?U.appendChild(Ee):U.textContent=a?"Hide":"Show";let De=m("div","persona-flex persona-items-center persona-ml-auto");De.append(U),d.append(c,De)}else d.append(c);let q=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&p){let ye=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});ox(q,ye)||(q.textContent=p),q.style.display=""}if(!a&&i&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!r)return o.append(d,q),o;let Q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Q.style.display=a?"":"none";let D=n.chunks.join(""),j=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return j.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Q.appendChild(j),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let Ee=ne(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?U.appendChild(Ee):U.textContent=a?"Hide":"Show"}Q.style.display=a?"":"none",q.style.display=a?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(d,q,Q),o};var kr=new Set,sx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ax=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
41
+ `,n.addEventListener("click",t);let o=r=>{let a=r.launcher??{},i=Ht(r),p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let A=a.subtitle??"Here to help you get answers fast";d.textContent=A,d.setAttribute("title",A)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let A=a.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let I=parseFloat(A)||24,_=te(a.agentIconName,I*.6,"var(--persona-text-inverse, #ffffff)",2);_?(u.appendChild(_),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let A=a.agentIconSize??"40px";y.style.height=A,y.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=a.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let I=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,I=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let _=parseFloat(A)||24,O=Math.max(_-I,8),w=te(a.callToActionIconName,O,"currentColor",2);w?f.appendChild(w):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let h=a.position&&An[a.position]?An[a.position]:An["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${C} ${h}`,i||(n.style.zIndex=String(a.zIndex??Ut));let L="1px solid var(--persona-border, #e5e7eb)",R="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:R,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:s}};var Fu=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:s}=Ou(e),r=Nu(e,t),a={wrapper:n,panel:o,pillRoot:s},i={container:r.container,body:r.body,messagesWrapper:r.messagesWrapper,composerOverlay:r.composerOverlay,introTitle:r.introTitle,introSubtitle:r.introSubtitle},p={element:r.header,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper},d={footer:r.footer,form:r.composerForm,textarea:r.textarea,sendButton:r.sendButton,sendButtonWrapper:r.sendButtonWrapper,micButton:r.micButton,micButtonWrapper:r.micButtonWrapper,statusText:r.statusText,suggestions:r.suggestions,attachmentButton:r.attachmentButton,attachmentButtonWrapper:r.attachmentButtonWrapper,attachmentInput:r.attachmentInput,attachmentPreviewsContainer:r.attachmentPreviewsContainer,actionsRow:r.actionsRow,leftActions:r.leftActions,rightActions:r.rightActions,setSendButtonMode:r.setSendButtonMode,peekBanner:r.peekBanner,peekTextNode:r.peekTextNode};return{shell:a,panelElements:r,transcript:i,header:p,composer:d,replaceHeader:y=>(p.element.replaceWith(y.header),p.element=y.header,p.iconHolder=y.iconHolder,p.headerTitle=y.headerTitle,p.headerSubtitle=y.headerSubtitle,p.closeButton=y.closeButton,p.closeButtonWrapper=y.closeButtonWrapper,p.clearChatButton=y.clearChatButton,p.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{d.footer.replaceWith(y),d.footer=y}}},ql=({config:e,plugins:t,onToggle:n})=>{let o=t.find(r=>r.renderLauncher);if(o?.renderLauncher){let r=o.renderLauncher({config:e,defaultRenderer:()=>zl(e,n).element,onToggle:n});if(r)return{instance:null,element:r}}let s=zl(e,n);return{instance:s,element:s.element}};var jv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Uv=(e,t)=>{if(!e)return null;let n=jv(e);if(n===null)return null;let o=t?.[e],s=o!==void 0?o:n;return s||null},zv=(e,t)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},qv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Vl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Kl=320,Uu=320,Vv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Kv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Gv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Jv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Xv=e=>{if(!e||e.length===0)return null;let t=Ne("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ne("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),s=m("span","persona-mention-chip-icon"),r=te(n.iconName??"at-sign",13,"currentColor",2);r&&s.appendChild(r),o.appendChild(s),o.appendChild(Ne("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Qv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(xs(o.ref,{readonly:!0,render:t}))}return n},_u="\uE000",$u="\uE001",Yv=(e,t,n,o)=>{let s=Math.random().toString(36).slice(2,8),r=y=>`${_u}${s}:${y}${$u}`,a=t.map((y,f)=>y.kind==="text"?y.text:r(f)).join(""),i=n(a);if(!t.every((y,f)=>y.kind==="text"||i.includes(r(f)))){e.replaceChildren(Qv(t,o));return}e.innerHTML=i;let d=new RegExp(`${_u}${s}:(\\d+)${$u}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let y=c.nextNode();y;y=c.nextNode())u.push(y);for(let y of u){let f=y;for(let h=d.exec(f.data);h;h=d.exec(f.data)){let C=t[Number(h[1])],E=f.splitText(h.index);E.data=E.data.slice(h[0].length),C?.kind==="mention"&&E.parentNode?.insertBefore(xs(C.ref,{readonly:!0,render:o}),E),f=E}}},Zv=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let s=0,r=!1,a=()=>{r||(r=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=m("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Kl}px`,d.style.maxHeight=`${Uu}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;s+=1,d.addEventListener("error",()=>{c||(c=!0,s=Math.max(0,s-1),d.remove(),s===0&&a())}),d.addEventListener("load",()=>{c=!0}),qv(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,s=Math.max(0,s-1),d.remove())}),s===0?(a(),null):o}catch{return n?.(),null}},ex=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Vl(o.audio))return;let s=m("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Kl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},tx=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Vl(o.video))return;let s=m("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Kl}px`,s.style.maxHeight=`${Uu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},nx=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Vl(o.data))return;let s=m("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Er=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(s),e},zu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Er};if(t){let s=t(o);if(s!==null)return s}return Er()},ox=(e,t)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=m("img");s.src=o,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},ju=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?o.textContent=t.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},rx=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},qu=(e,t,n)=>{let o=t.showCopy??!0,s=t.showUpvote??!0,r=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!s&&!r&&!a){let h=m("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],y=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id);let f=(h,C,E)=>{let L=gt({icon:h,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",E),L};return o&&y.appendChild(f("copy","Copy message","copy")),a&&y.appendChild(f("volume-2","Read aloud","read-aloud")),s&&y.appendChild(f("thumbs-up","Upvote","upvote")),r&&y.appendChild(f("thumbs-down","Downvote","downvote")),y},Ds=(e,t,n,o,s,r)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,y=p?.position??"left",f=d?.position??"below",h=rx(e.role,i),C=m("div",h.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Vv(e),L=e.content?.trim()??"",A=E.length>0&&L===ka,I=Ga(r?.widgetConfig?.features?.streamAnimation),_=r?.widgetConfig?.features?.streamAnimation?.plugins,O=e.role==="assistant"&&I.type!=="none"?Sr(I.type,_):null,w=e.role==="assistant"&&O?.isAnimating?.(e)===!0,z=e.role==="assistant"&&O!==null&&(!!e.streaming||w);z&&O?.bubbleClass&&C.classList.add(O.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),z&&O&&(O.containerClass&&q.classList.add(O.containerClass),q.style.setProperty("--persona-stream-step",`${I.speed}ms`),q.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let Q=z?Ja(e.content??"",I.buffer,O,e,!!e.streaming):e.content??"",D=()=>{let Z=t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&O?.wrap==="char"?Ps(Z,"char",e.id,{skipTags:O.skipTags}):z&&O?.wrap==="word"?Ps(Z,"word",e.id,{skipTags:O.skipTags}):Z},j=null;if(A?(j=document.createElement("div"),j.innerHTML=D(),j.style.display="none",q.appendChild(j)):e.contentSegments?.length?Yv(q,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),r?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=D(),z&&O?.useCaret&&!A&&L){let Z=Xa(),Ce=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),me=Ce[Ce.length-1];if(me?.parentNode)me.parentNode.insertBefore(Z,me.nextSibling);else{let pe=q.lastElementChild;pe?pe.appendChild(Z):q.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=ju(e,d,"span");Z.classList.add("persona-timestamp-inline");let Ce=q.lastElementChild;Ce?Ce.appendChild(Z):q.appendChild(Z)}if(E.length>0){let Z=Zv(E,!A&&!!L,()=>{A&&j&&(j.style.display="")});Z?C.appendChild(Z):A&&j&&(j.style.display="")}let ge=Kv(e);if(ge.length>0){let Z=ex(ge);Z&&C.appendChild(Z)}let be=Gv(e);if(be.length>0){let Z=tx(be);Z&&C.appendChild(Z)}let Ee=Jv(e);if(Ee.length>0){let Z=nx(Ee);Z&&C.appendChild(Z)}let De=e.contentSegments?.length?null:Xv(e.contextMentions);if(De&&C.appendChild(De),C.appendChild(q),u&&f==="below"&&e.createdAt){let Z=ju(e,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let ae=e.role==="assistant"?Uv(e.stopReason,r?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(Q&&Q.trim()),Ce=I.placeholder==="skeleton",me=Ce&&I.buffer==="line"&&Z;if(Z)me&&C.appendChild(Rs());else if(Ce)C.appendChild(Rs());else{let pe=zu("inline",r?.loadingIndicatorRenderer,r?.widgetConfig);pe&&C.appendChild(pe)}}if(ae&&e.stopReason&&!e.streaming&&(L||(q.style.display="none"),C.appendChild(zv(e.stopReason,ae))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=qu(e,o,s);C.appendChild(Z)}if(!c||e.role==="system")return C;let Y=m("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=ox(p,e.role);return y==="right"||y==="left"&&e.role==="user"?Y.append(C,le):Y.append(le,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},sx=(e,t,n,o,s,r)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ds(e,t,n,o,s,r)};var Mr=new Set,ax=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ix=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
+ `):""},Vu=(e,t)=>{let n=Mr.has(e),o=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),r=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!s)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=te(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",r&&(r.style.display=n?"none":r.textContent||r.childNodes.length?"":"none")},Gl=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let s=t?.features?.reasoningDisplay??{},r=s.expandable!==!1,a=r&&Mr.has(e.id),i=n.status!=="complete",p=ix(e,s.previewMaxLines??3),d=m("button",r?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",r&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),C=()=>{let be=m("span","");return be.setAttribute("data-tool-elapsed",h),be.textContent=Ta(n),be},E=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:p,isActive:i,config:t??{},elapsed:Ta(n),createElapsedElement:C});typeof E=="string"&&E.trim()?(u.textContent=E,c.appendChild(u)):E instanceof HTMLElement?c.appendChild(E):(u.textContent=y,c.appendChild(u));let L=m("span","persona-text-xs persona-text-persona-primary");L.textContent=Cp(n),c.appendChild(L);let R=s.loadingAnimation??"none",A=f.activeTextTemplate,I=f.completeTextTemplate,_=i?A:I,O=E instanceof HTMLElement,w=(be,Ee)=>{u.textContent="";let De=Ea(be,""),ae=0;for(let ve of De){let Y=ve.styles.length>0?(()=>{let le=m("span",ve.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(le),le})():u;if(ve.isDuration&&i)Y.appendChild(C());else{let le=ve.isDuration?Ta(n):ve.text;Ee?ae=co(Y,le,ae):Y.appendChild(document.createTextNode(le))}}};if(!O&&_)if(L.style.display="none",u.style.display="",i&&R!=="none"){let be=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),R==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`),w(_,!1)):(u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`),R==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w(_,!0))}else w(_,!1);else if(!O&&i&&R!=="none"){u.style.display="";let be=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),R==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`);else{u.classList.add(`persona-tool-loading-${R}`),u.style.setProperty("--persona-tool-anim-duration",`${be}ms`),R==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ee=u.textContent||y;u.textContent="",co(u,Ee,0)}n.status==="complete"&&(u.style.display="none")}else O||(n.status==="complete"?u.style.display="none":u.style.display="");let z=null;if(r){z=m("div","persona-flex persona-items-center");let Ee=te(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?z.appendChild(Ee):z.textContent=a?"Hide":"Show";let De=m("div","persona-flex persona-items-center persona-ml-auto");De.append(z),d.append(c,De)}else d.append(c);let q=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&p){let be=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});ax(q,be)||(q.textContent=p),q.style.display=""}if(!a&&i&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!r)return o.append(d,q),o;let Q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Q.style.display=a?"":"none";let D=n.chunks.join(""),j=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return j.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Q.appendChild(j),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let Ee=te(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?z.appendChild(Ee):z.textContent=a?"Hide":"Show"}Q.style.display=a?"":"none",q.style.display=a?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(d,q,Q),o};var kr=new Set,lx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),cx=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
43
43
  `);let s=io(n.args).trim();return s?s.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).slice(0,t).join(`
44
- `):""},Gl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},ix=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",r=ax(e,o?.previewMaxLines??3),a=n?Cp(n):"";if(!n)return{summary:a,previewText:r,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return s==="tool-name"?d=n.name?.trim()||a:s==="tool-preview"&&r&&(d=r),i&&p.activeTextTemplate?d=ul(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=ul(n,p.completeTextTemplate,d)),{summary:d,previewText:r,isActive:i}},Vu=(e,t,n)=>{let o=kr.has(e),s=n?.toolCall??{},r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!r||!a)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=s.toggleTextColor||s.headerTextColor||"var(--persona-primary, #171717)",u=ne(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Jl=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},s=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),o.backgroundColor&&(s.style.backgroundColor=o.backgroundColor),o.borderColor&&(s.style.borderColor=o.borderColor),o.borderWidth&&(s.style.borderWidth=o.borderWidth),o.borderRadius&&(s.style.borderRadius=o.borderRadius),s.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let r=t?.features?.toolCallDisplay??{},a=r.expandable!==!1,i=a&&kr.has(e.id),{summary:p,previewText:d,isActive:c}=ix(e,t),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let y=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),C=()=>{let D=m("span","");return D.setAttribute("data-tool-elapsed",h),D.textContent=fs(n),D},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:r.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:fs(n),createElapsedElement:C});typeof E=="string"&&E.trim()?(f.textContent=E,y.appendChild(f)):E instanceof HTMLElement?y.appendChild(E):(f.textContent=p,y.appendChild(f));let L=r.loadingAnimation??"none",R=o.activeTextTemplate,A=o.completeTextTemplate,I=c?R:A,_=E instanceof HTMLElement,O=(D,j)=>{f.textContent="";let ge=n.name?.trim()||"tool",ye=Ea(D,ge),Ee=0;for(let De of ye){let se=De.styles.length>0?(()=>{let be=m("span",De.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(be),be})():f;if(De.isDuration&&c)se.appendChild(C());else{let be=De.isDuration?fs(n):De.text;j?Ee=co(se,be,Ee):se.appendChild(document.createTextNode(be))}}};if(!_)if(c&&L!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),I&&O(I,!1);else if(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),I)O(I,!0);else{let j=f.textContent||p;f.textContent="",co(f,j,0)}}else I&&O(I,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",j=ne(i?"chevron-up":"chevron-down",16,D,2);j?w.appendChild(j):w.textContent=i?"Hide":"Show";let ge=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ge.append(w),u.append(y,ge)}else u.append(y);let U=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&c&&r.activePreview&&d){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});sx(U,D)||(U.textContent=d),U.style.display=""}if(!i&&c&&r.activeMinHeight&&(s.style.minHeight=r.activeMinHeight),!a)return s.append(u,U),s;let q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=i?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let D=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,q.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Arguments";let ge=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Gl(ge,o),ge.textContent=io(n.args),D.append(j,ge),q.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Activity";let ge=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Gl(ge,o),ge.textContent=n.chunks.join(""),D.append(j,ge),q.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Result";let ge=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Gl(ge,o),ge.textContent=io(n.result),D.append(j,ge),q.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,q.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",j=ne(i?"chevron-up":"chevron-down",16,D,2);j?w.appendChild(j):w.textContent=i?"Hide":"Show"}q.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),s.append(u,U,q),s};var Xo=new Map,si=e=>{let n=(e.startsWith(Mn)?e.slice(Mn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ku=e=>e?.approval!==!1?e?.approval:void 0,Gu=(e,t)=>{let n=Ku(t)?.detailsDisplay??"collapsed";return Xo.get(e)??n==="expanded"},Ju=(e,t,n)=>{let o=Ku(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let r=e.querySelector("[data-approval-details-chevron]");if(r){r.innerHTML="";let a=ne(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&r.appendChild(a)}},Xu=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!o||!s)return;let r=Gu(e,n);Ju(o,r,n),s.style.display=r?"":"none"};var ai=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,s=n?.status==="pending",r=m("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",r.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",r.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ne(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),y=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",y.appendChild(f),!s){let w=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),y.appendChild(w)}u.appendChild(y);let C=n.toolType==="webmcp"||n.toolName.startsWith(Mn)?is(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,R=E||(L?n.description:`The assistant wants to use \u201C${C??si(n.toolName)}\u201D.`),A=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=R,u.appendChild(A),n.reason){let w=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let U=m("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(U),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let I=o?.detailsDisplay??"collapsed",_=!!n.description&&!L,O=_||!!n.parameters;if(I!=="hidden"&&O){let w=Gu(e.id,t),U=m("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span");q.setAttribute("data-approval-details-label","true");let Q=m("span","persona-inline-flex persona-items-center");Q.setAttribute("data-approval-details-chevron","true"),U.append(q,Q),Ju(U,w,t),u.appendChild(U);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=w?"":"none",_){let j=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,D.appendChild(j)}if(n.parameters){let j=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(j.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=io(n.parameters),D.appendChild(j)}u.appendChild(D)}if(s){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let U=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let q=ne("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",U.appendChild(q));let Q=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(Q);let D=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let j=ne("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);j&&(j.style.marginRight="4px",D.appendChild(j));let ge=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(ge),w.append(U,D),u.appendChild(w)}return a.append(i,u),r.appendChild(a),r};function lx(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Qu(e){let{anchor:t,content:n,placement:o="bottom-start",offset:s=6,matchAnchorWidth:r=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??lx(t),y=!1,f=null,h=()=>{if(!y)return;let L=t.getBoundingClientRect();n.style.position="fixed",r&&(n.style.minWidth=`${L.width}px`),a&&(n.style.maxWidth=`${L.width}px`);let R=n.getBoundingClientRect(),A=i?.()??null,I=A!=null?L.top+A:L.top,_=o==="top-start"||o==="top-end"?I-s-R.height:L.bottom+s,w=o==="bottom-end"||o==="top-end"?L.right-R.width:L.left,U=a?.()??null;if(U!=null){let q=Math.max(L.left,L.right-R.width);w=Math.min(Math.max(L.left+U,L.left),q)}n.style.top=`${_}px`,n.style.left=`${w}px`},C=()=>{y&&(y=!1,f&&(f(),f=null),n.remove())},E=()=>{if(y)return;y=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let L=(t.ownerDocument??document).defaultView??window,R=t.ownerDocument??document,A=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}h()},I=O=>{let w=typeof O.composedPath=="function"?O.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},_=L.setTimeout(()=>{R.addEventListener("pointerdown",I,!0)},0);L.addEventListener("scroll",A,!0),L.addEventListener("resize",A),f=()=>{L.clearTimeout(_),R.removeEventListener("pointerdown",I,!0),L.removeEventListener("scroll",A,!0),L.removeEventListener("resize",A)},d?.()};return{get isOpen(){return y},open:E,close:C,toggle:()=>y?C():E(),reposition:h,destroy:C}}function Yu(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var cx=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Zu=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Qo=(e,t)=>{Zu(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},dx=e=>e?.approval!==!1?e?.approval:void 0,px=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Xo.get(e)??n==="expanded"},Xl=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},ux=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let s=e.toolType==="webmcp"||e.toolName.startsWith(Mn)?is(e.toolName):void 0,r=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...s?{displayTitle:s}:{},...e.reason?{reason:e.reason}:{}});if(r)return n.textContent=r,n;let a=s??si(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},fx=e=>{let t=m("div","persona-approval-resolved"),n=ne("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?si(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},gx=(e,t,n,o,s,r,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,y=u&&px(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",y?"true":"false"),C.setAttribute("aria-label",y?h:f)):C.setAttribute("data-static","true");let E=m("span","persona-approval-logo"),L=ne("shield-check",16,"currentColor",2);L&&E.appendChild(L),C.appendChild(E);let R=ux(n,o);if(u){let U=m("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let q=ne("chevron-down",14,"currentColor",2);q&&U.appendChild(q),R.append(" "),R.appendChild(U)}C.appendChild(R),i.appendChild(C);let A=m("div","persona-approval-body");if(u){let U=m("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!y,d){let q=m("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,U.appendChild(q)}if(c){let q=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=io(n.parameters),U.appendChild(q)}A.appendChild(U)}if(n.reason){let U=m("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(q,document.createTextNode(n.reason)),A.appendChild(U)}let I=m("div","persona-approval-actions"),_=null,O=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.style.color=o.approveButtonTextColor)},w=m("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),a){let U=m("div","persona-approval-split"),q=m("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),O(q),q.append(o?.approveLabel??"Always allow",Xl("\u23CE"));let Q=m("button","persona-approval-caret");Q.type="button",Q.setAttribute("data-action","toggle-menu"),Q.setAttribute("aria-label","More options"),O(Q);let D=ne("chevron-down",15,"currentColor",2);D&&Q.appendChild(D),U.append(q,Q),I.append(U,w),w.append(Xl("Esc"));let j=m("div","persona-approval-menu"),ge=m("button","persona-approval-menu-item");ge.type="button",ge.append("Allow once",Xl("\u2318\u23CE")),j.appendChild(ge),_=Qu({anchor:U,content:j,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,_),ge.addEventListener("click",()=>{Qo(e,t.id),s()})}else{let U=m("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),O(U),U.append(o?.approveLabel??"Allow"),I.append(U,w)}return A.appendChild(I),i.appendChild(A),i.addEventListener("click",U=>{let q=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!q)return;let Q=q.getAttribute("data-action");if(Q==="toggle-params"){let D=i.querySelector('[data-role="params"]');if(D){let j=D.hidden;D.hidden=!j,C.setAttribute("aria-expanded",j?"true":"false"),C.setAttribute("aria-label",j?h:f),Xo.set(t.id,j)}return}if(Q==="toggle-menu"){_?.toggle();return}if(Q==="always"){Qo(e,t.id),s({remember:!0});return}if(Q==="allow"){Qo(e,t.id),s();return}if(Q==="deny"){Qo(e,t.id),r();return}}),i},ef=()=>{let e=cx();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:s,deny:r,config:a})=>{let i=o?.approval;if(!i)return null;let p=dx(a);if(i.status!=="pending"){if(Qo(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return fx(i)}Zu(e,o.id);let d=p?.enableAlwaysAllow===!0,c=gx(e,o,i,p,s,r,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=y=>{Yu(y)||o.id===e.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),Qo(e,o.id),y.key==="Escape"?r():y.metaKey||y.ctrlKey?s():s({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Qo(e,o);e.latestPendingApprovalId=null}}};var tf=e=>{let t=[],n=null;return{buttons:t,render:(s,r,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!s||!s.length||!c&&(i??(r?r.getMessages():[])).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),y=r?r.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(s.forEach(h=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=h,C.disabled=y,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),r.sendMessage(h))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let h=JSON.stringify(s);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var Os=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ns=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let s=o.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)o.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let r=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)o.put(s)}catch{}}};var mx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hx=new Set(["step_start","execution_start"]),yx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bx=new Set(["step_complete","agent_turn_complete"]),vx=new Set(["flow_complete","agent_complete"]),nf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),rf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ln=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Yo=(e,t)=>{let n=e[t];return rf(n)?n:void 0};function Ql(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ii(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function xx(e,t){return typeof t.type=="string"?t.type:e}function Cx(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function wx(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function of(e){let t=Yo(e,"result"),n=[Yo(e,"tokens"),Yo(e,"totalTokens"),t?Yo(t,"tokens"):void 0,Yo(e,"usage"),t?Yo(t,"usage"):void 0];for(let o of n){if(!o)continue;let s=ln(o.output)??ln(o.outputTokens)??ln(o.completionTokens);if(s!==void 0)return s}return ln(e.outputTokens)??ln(e.completionTokens)??(t?ln(t.outputTokens)??ln(t.completionTokens):void 0)}function Ax(e){let t=Yo(e,"result");return ln(e.executionTime)??ln(e.executionTimeMs)??ln(e.execution_time)??ln(e.duration)??(t?ln(t.executionTime)??ln(t.executionTimeMs):void 0)}function Sx(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Fs=class{constructor(t=Sx){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ii(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!rf(n)){nf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=xx(t,n),s=this.now();if(mx.has(o)){this.startRun(s);return}if(hx.has(o)){this.run||this.startRun(s);return}if(yx.has(o)){if(!wx(o,n))return;let r=Cx(n);if(!r)return;this.run||this.startRun(s);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=s),a.visibleCharCount+=r.length;let i=a.exactOutputTokens+Ql(a.visibleCharCount),p=s-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ii(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(bx.has(o)){if(!this.run)return;let r=this.run,a=of(n);a!==void 0&&(r.exactOutputTokens+=a,r.visibleCharCount=0);let i=r.exactOutputTokens>0,p=r.exactOutputTokens+Ql(r.visibleCharCount),d=this.resolveDuration(r,n,s);this.metric={status:"running",tokensPerSecond:ii(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(vx.has(o)){if(!this.run)return;let r=this.run,a=of(n),i=a??r.exactOutputTokens+Ql(r.visibleCharCount),p=a!==void 0||r.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(r,n,s);this.metric={status:"complete",tokensPerSecond:ii(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(nf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let s=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return s!==void 0&&s>=250?s:Ax(n)??o-t.startedAt}};function Lr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Tx={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Ex={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Mx=["flowName","stepName","reasoningText","text","name","tool","toolName"],kx=100;function Lx(e,t){let n={...Tx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Ex}function Px(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Rx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),r=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${s}.${r}`}function Ix(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let s=o.split("."),r=n;for(let a of s)if(r&&typeof r=="object"&&r!==null)r=r[a];else{r=void 0;break}if(typeof r=="string"&&r.trim())return r.trim()}}catch{}return null}function Wx(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Hx(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Bx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Dx(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Ox(e,t,n){let o,s;try{s=JSON.parse(e.payload),o=JSON.stringify(s,null,2)}catch{s=e.payload,o=e.payload}let r=t.find(i=>i.renderEventStreamPayload);if(r?.renderEventStreamPayload&&n){let i=r.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,i.appendChild(p),i}}function Yl(e,t,n,o,s,r,a,i){let p=s.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Lr(d,o.classNames?.eventRow);let c=a.find(y=>y.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let y=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>r(e.id)});if(y)return d.appendChild(y),d}return d.appendChild(u()),d;function u(){let y=m("div",""),f=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let h=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ne(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&h.appendChild(C);let E=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";E.textContent=L==="relative"?Px(e.timestamp,n):Rx(e.timestamp);let R=null;o.showSequenceNumbers!==!1&&(R=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(t+1));let A=Lx(e.type,o.badgeColors),I=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");I.style.backgroundColor=A.bg,I.style.color=A.text,I.style.borderColor=A.text+"50",I.textContent=e.type;let _=o.descriptionFields??Mx,O=Ix(e.payload,_),w=null;O&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=O);let U=m("div","persona-flex-1 persona-min-w-0"),q=m("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),Q=ne("clipboard","12px","currentColor",1.5);return Q&&q.appendChild(Q),q.addEventListener("click",async D=>{D.stopPropagation(),await Wx(Hx(e)),q.innerHTML="";let j=ne("check","12px","currentColor",1.5);j&&q.appendChild(j),setTimeout(()=>{q.innerHTML="";let ge=ne("clipboard","12px","currentColor",1.5);ge&&q.appendChild(ge)},1500)}),f.appendChild(h),f.appendChild(E),R&&f.appendChild(R),f.appendChild(I),w&&f.appendChild(w),f.appendChild(U),f.appendChild(q),y.appendChild(f),p&&y.appendChild(Ox(e,a,i)),y}}function sf(e){let{buffer:t,getFullHistory:n,onClose:o,config:s,plugins:r=[],getThroughput:a}=e,i=s?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=s?.features?.eventStream??{},y=r.find(h=>h.renderEventStreamView);if(y?.renderEventStreamView&&s){let h=y.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Lr(C,h?.panel);let E=[],L="",R="",A=null,I=[],_={},O=0,w=za(),U=0,q=0,Q=!1,D=null,j=!1,ge=0,ye=new Set,Ee=new Map,De="",se="",be=null,Y,ce,Z,xe,me=null,ue=null,Pe=null;function Oe(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),z=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Lr(z,h?.headerBar),a){ue=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ue.style.cursor="help",me=m("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),me.textContent="-- tok/s",Pe=m("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Pe.style.display="none",Pe.style.pointerEvents="none";let Qe=ue,xo=Pe,Co=()=>{if(!xo.textContent)return;let Us=Qe.getBoundingClientRect(),Qt=B.getBoundingClientRect();xo.style.left=`${Us.left-Qt.left}px`,xo.style.top=`${Us.bottom-Qt.top+4}px`,xo.style.display="block"},Ci=()=>{xo.style.display="none"};ue.addEventListener("mouseenter",Co),ue.addEventListener("mouseleave",Ci),ue.appendChild(me)}let ae=m("div","persona-flex-1");Y=m("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let tt=m("option","");tt.value="",tt.textContent="All events (0)",Y.appendChild(tt),ce=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ce.type="button",ce.title="Copy All";let ct=ne("clipboard-copy","12px","currentColor",1.5);ct&&ce.appendChild(ct);let V=m("span","persona-event-copy-all persona-text-xs");V.textContent="Copy All",ce.appendChild(V),ue&&z.appendChild(ue),z.appendChild(ae),z.appendChild(Y),z.appendChild(ce);let ze=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Lr(ze,h?.searchBar);let We=ne("search","14px","var(--persona-muted, #9ca3af)",1.5),He=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");We&&He.appendChild(We),Z=m("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Lr(Z,h?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",xe=m("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),xe.type="button",xe.style.display="none";let ke=ne("x","12px","currentColor",2);return ke&&xe.appendChild(ke),ze.appendChild(He),ze.appendChild(Z),ze.appendChild(xe),B.appendChild(z),B.appendChild(ze),Pe&&B.appendChild(Pe),B}let Ue,Ne=r.find(B=>B.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&s?Ue=Ne.renderEventStreamToolbar({config:s,defaultRenderer:()=>Oe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:z=>{L=z,Ie(),ve()},onSearchChange:z=>{R=z,Ie(),ve()}})??Oe():Ue=Oe();let we=m("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");we.style.display="none";function Le(){if(!a||!me||!ue)return;let B=a(),z=Bx(B);me.textContent=z;let ae=Dx(B);Pe&&(Pe.textContent=ae,ae||(Pe.style.display="none")),ue.setAttribute("aria-label",ae?`Throughput: ${z}, ${ae}`:`Throughput: ${z}`)}let ot=m("div","persona-flex-1 persona-min-h-0 persona-relative"),ie=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ie.style.height="100%";let Re=m("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Lr(Re,h?.scrollIndicator),Re.style.display="none",Re.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let xt=ne(d,"14px","currentColor",2);xt&&Re.appendChild(xt);let yt=m("span","");yt.textContent=c,Re.appendChild(yt);let rt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");rt.style.display="none",ot.appendChild(ie),ot.appendChild(rt),ot.appendChild(Re),C.setAttribute("tabindex","0"),C.appendChild(Ue),C.appendChild(we),C.appendChild(ot);function Me(){let B=t.getAll(),z={};for(let ze of B)z[ze.type]=(z[ze.type]||0)+1;let ae=Object.keys(z).sort(),tt=ae.length!==I.length||!ae.every((ze,We)=>ze===I[We]),Te=!tt&&ae.some(ze=>z[ze]!==_[ze]),ct=B.length!==Object.values(_).reduce((ze,We)=>ze+We,0);if(!tt&&!Te&&!ct||(I=ae,_=z,!Y))return;let V=Y.value;if(Y.options[0].textContent=`All events (${B.length})`,tt){for(;Y.options.length>1;)Y.remove(1);for(let ze of ae){let We=m("option","");We.value=ze,We.textContent=`${ze} (${z[ze]||0})`,Y.appendChild(We)}V&&ae.includes(V)?Y.value=V:V&&(Y.value="",L="")}else for(let ze=1;ze<Y.options.length;ze++){let We=Y.options[ze];We.textContent=`${We.value} (${z[We.value]||0})`}}function he(){let B=t.getAll();if(L&&(B=B.filter(z=>z.type===L)),R){let z=R.toLowerCase();B=B.filter(ae=>ae.type.toLowerCase().includes(z)||ae.payload.toLowerCase().includes(z))}return B}function lt(){return L!==""||R!==""}function Ie(){O=0,U=0,w.resume(),Re.style.display="none"}function fe(B){ye.has(B)?ye.delete(B):ye.add(B),be=B;let z=ie.scrollTop,ae=w.isFollowing();j=!0,w.pause(),ve(),ie.scrollTop=z,ae&&w.resume(),j=!1}function le(){return mo(ie,50)}function ve(){q=Date.now(),Q=!1,Le(),Me();let B=t.getEvictedCount();B>0?(we.textContent=`${B.toLocaleString()} older events truncated`,we.style.display=""):we.style.display="none",E=he();let z=E.length,ae=t.getSize()>0;z===0&&ae&&lt()?(rt.textContent=R?`No events matching '${R}'`:"No events matching filter",rt.style.display="",ie.style.display="none"):(rt.style.display="none",ie.style.display=""),ce&&(ce.title=lt()?`Copy Filtered (${z})`:"Copy All"),p&&!w.isFollowing()&&z>O&&(U+=z-O,yt.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Re.style.display=""),O=z;let tt=t.getAll(),Te=tt.length>0?tt[0].timestamp:0,ct=new Set(E.map(We=>We.id));for(let We of ye)ct.has(We)||ye.delete(We);let V=L!==De||R!==se,ze=Ee.size===0&&E.length>0;if(V||ze||E.length===0){ie.innerHTML="",Ee.clear();let We=document.createDocumentFragment();for(let He=0;He<E.length;He++){let ke=Yl(E[He],He,Te,u,ye,fe,r,s);Ee.set(E[He].id,ke),We.appendChild(ke)}ie.appendChild(We),De=L,se=R,be=null}else{if(be!==null){let He=Ee.get(be);if(He&&He.parentNode===ie){let ke=E.findIndex(Qe=>Qe.id===be);if(ke>=0){let Qe=Yl(E[ke],ke,Te,u,ye,fe,r,s);ie.insertBefore(Qe,He),He.remove(),Ee.set(be,Qe)}}be=null}let We=new Set(E.map(He=>He.id));for(let[He,ke]of Ee)We.has(He)||(ke.remove(),Ee.delete(He));for(let He=0;He<E.length;He++){let ke=E[He];if(!Ee.has(ke.id)){let Qe=Yl(ke,He,Te,u,ye,fe,r,s);Ee.set(ke.id,Qe),ie.appendChild(Qe)}}}w.isFollowing()&&(ie.scrollTop=ie.scrollHeight)}function Ct(){if(Date.now()-q>=kx){D!==null&&(cancelAnimationFrame(D),D=null),ve();return}Q||(Q=!0,D=requestAnimationFrame(()=>{D=null,ve()}))}let N=(B,z)=>{if(!ce)return;ce.innerHTML="";let ae=ne(B,"12px","currentColor",1.5);ae&&ce.appendChild(ae);let tt=m("span","persona-text-xs");tt.textContent="Copy All",ce.appendChild(tt),setTimeout(()=>{ce.innerHTML="";let Te=ne("clipboard-copy","12px","currentColor",1.5);Te&&ce.appendChild(Te);let ct=m("span","persona-text-xs");ct.textContent="Copy All",ce.appendChild(ct),ce.disabled=!1},z)},te=async()=>{if(ce){ce.disabled=!0;try{let B;lt()?B=E:n?(B=await n(),B.length===0&&(B=t.getAll())):B=t.getAll();let z=B.map(ae=>{try{return JSON.parse(ae.payload)}catch{return ae.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),N("check",1500)}catch{N("x",1500)}}},Fe=()=>{Y&&(L=Y.value,Ie(),ve())},Se=()=>{!Z||!xe||(xe.style.display=Z.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{R=Z.value,Ie(),ve()},150))},M=()=>{!Z||!xe||(Z.value="",R="",xe.style.display="none",A&&clearTimeout(A),Ie(),ve())},J=()=>{if(j)return;let B=ie.scrollTop,{action:z,nextLastScrollTop:ae}=qa({following:w.isFollowing(),currentScrollTop:B,lastScrollTop:ge,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ge=ae,z==="resume"?(w.resume(),U=0,Re.style.display="none"):z==="pause"&&(w.pause(),p&&(yt.textContent=c,Re.style.display=""))},x=B=>{let z=Va({following:w.isFollowing(),deltaY:B.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});z==="pause"?(w.pause(),p&&(yt.textContent=c,Re.style.display="")):z==="resume"&&(w.resume(),U=0,Re.style.display="none")},T=()=>{p&&(ie.scrollTop=ie.scrollHeight,w.resume(),U=0,Re.style.display="none")},k=B=>{let z=B.target;if(!z||z.closest("button"))return;let ae=z.closest("[data-event-id]");if(!ae)return;let tt=ae.getAttribute("data-event-id");tt&&fe(tt)},H=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Z?.focus(),Z?.select();return}B.key==="Escape"&&(Z&&document.activeElement===Z?(M(),Z.blur(),C.focus()):o&&o())};ce&&ce.addEventListener("click",te),Y&&Y.addEventListener("change",Fe),Z&&Z.addEventListener("input",Se),xe&&xe.addEventListener("click",M),ie.addEventListener("scroll",J),ie.addEventListener("wheel",x,{passive:!0}),ie.addEventListener("click",k),Re.addEventListener("click",T),C.addEventListener("keydown",H);function G(){A&&clearTimeout(A),D!==null&&(cancelAnimationFrame(D),D=null),Q=!1,Ee.clear(),ce&&ce.removeEventListener("click",te),Y&&Y.removeEventListener("change",Fe),Z&&Z.removeEventListener("input",Se),xe&&xe.removeEventListener("click",M),ie.removeEventListener("scroll",J),ie.removeEventListener("wheel",x),ie.removeEventListener("click",k),Re.removeEventListener("click",T),C.removeEventListener("keydown",H)}return{element:C,update:Ct,destroy:G}}}function Zl(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",s=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let r=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let y=u;return r.findIndex(f=>f===y||f.contains(y))},d=u=>{let y=p(u.target);if(y<0)return;let f=y;if(u.key===s)f=Math.min(y+1,r.length-1);else if(u.key===o)f=Math.max(y-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=r.length-1;else return;u.preventDefault(),f!==y&&t.onSelect(f)},c=u=>{let y=p(u.target);y>=0&&i(r[y])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,y){if(r=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let C=h===y;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||y<0&&h===0?0:-1}),a){let f=(y>=0?u[y]:void 0)??u[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function af(e,t){let n=e.features?.artifacts?.layout,s=(n?.toolbarPreset??"default")==="document",r=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=N=>({start:N===!1?!1:typeof N=="object"&&N?N.start!==!1:!0,end:N===!1?!1:typeof N=="object"&&N?N.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),y=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{y?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),j?.hide()};y&&y.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=m("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),s&&h.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&C.classList.add("persona-artifact-toolbar-document");let E=m("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=r;let L=mt({icon:"x",label:a});L.addEventListener("click",()=>{f(),t.onDismiss?.()});let R="rendered",A=fo({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:s?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:s?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:N=>{R=N==="source"?"source":"rendered",le()}}),I=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),_=n?.documentToolbarShowCopyLabel===!0,O=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,U=!!(O&&w&&w.length>0),q=null,Q,D=null,j=null;if(s&&(_||O)&&!U){if(Q=_?uo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O){let N=ne("chevron-down",14,"currentColor",2);N&&Q.appendChild(N)}}else s&&U?(q=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=_?uo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=mt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),q.append(Q,D)):s?Q=mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Q=mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Q.classList.add("persona-hidden"));let ge=s?mt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):mt({icon:"refresh-cw",label:"Refresh"}),ye=s?mt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):mt({icon:"x",label:a}),Ee=mt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(s?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ee.classList.add("persona-hidden");let De=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),se=e.features?.artifacts?.toolbarActions??[],be=()=>{let N=we.find(M=>M.id===Le)??we[we.length-1],te=N?.id??null,Fe=N?.artifactType==="markdown"?N.markdown??"":"",Se=N?JSON.stringify({component:N.component,props:N.props},null,2):"";return{markdown:Fe,jsonPayload:Se,id:te}},Y=async()=>{let N=we.find(te=>te.id===Le)??we[we.length-1];try{await navigator.clipboard.writeText(Ms(N))}catch{}};if(Q.addEventListener("click",async()=>{let N=n?.onDocumentToolbarCopyMenuSelect;if(N&&U){let{markdown:te,jsonPayload:Fe,id:Se}=be();try{await N({actionId:"primary",artifactId:Se,markdown:te,jsonPayload:Fe})}catch{}return}await Y()}),D&&w?.length){let N=()=>h.closest("[data-persona-root]")??document.body,te=()=>{j=Jo({items:w.map(Fe=>({id:Fe.id,label:Fe.label})),onSelect:async Fe=>{let{markdown:Se,jsonPayload:M,id:J}=be(),x=n?.onDocumentToolbarCopyMenuSelect;try{x?await x({actionId:Fe,artifactId:J,markdown:Se,jsonPayload:M}):Fe==="markdown"||Fe==="md"?await navigator.clipboard.writeText(Se):Fe==="json"||Fe==="source"?await navigator.clipboard.writeText(M):await navigator.clipboard.writeText(Se||M)}catch{}},anchor:q??D,position:"bottom-right",portal:N()})};h.isConnected?te():requestAnimationFrame(te),D.addEventListener("click",Fe=>{Fe.stopPropagation(),j?.toggle()})}ge.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}le()}),ye.addEventListener("click",()=>{f(),t.onDismiss?.()});let ce=m("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(s)C.replaceChildren(),q?I.append(q,ge,ye):I.append(Q,ge,ye),I.insertBefore(De,ye),I.insertBefore(Ee,ye),C.append(A.element,ce,I);else{let N=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");N.append(Q,De,Ee,L),C.appendChild(E),C.appendChild(N)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Z=m("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let xe=e.features?.artifacts?.renderTabBar,me=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ue=Zl(Z,{onSelect:N=>t.onSelect(we[N].id)}),Pe=N=>{let te=N.scrollWidth-N.clientWidth,Fe=te>1,Se=Math.abs(N.scrollLeft);N.classList.toggle("persona-artifact-tab-fade-start",c&&Fe&&Se>1),N.classList.toggle("persona-artifact-tab-fade-end",u&&Fe&&Se<te-1)},Oe=0,Ue=()=>{if(Oe)return;let N=()=>{Oe=0,Pe(Z)};Oe=typeof requestAnimationFrame=="function"?requestAnimationFrame(N):setTimeout(N,0)};Z.addEventListener("scroll",()=>Ue(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Pe(Z)).observe(Z);let Ne=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(i){for(let N of[Z,me])N.style.paddingLeft=i,N.style.paddingRight=i;Ne.style.padding=i}h.appendChild(C),h.appendChild(Z),h.appendChild(me),h.appendChild(Ne);let we=[],Le=null,ot=!1,ie=!0,Re=!1,xt=null,yt="",rt=null,Me=!1,he=N=>N.artifactType==="markdown"&&!!N.file||s?R:"rendered",lt=N=>{s||(N&&!Me?(C.insertBefore(A.element,E),Me=!0):!N&&Me&&(A.element.remove(),Me=!1))},Ie=()=>Le&&we.find(N=>N.id===Le)||we[we.length-1],fe=()=>{let N=Ts(Ie());if(!N){De.replaceChildren();return}let te=se.filter(Fe=>Fe.visible===void 0||Fe.visible(N)).map(Fe=>Ar(Fe,{documentChrome:s,onClick:()=>{let Se=Ts(Ie());if(Se)try{Promise.resolve(Fe.onClick(Se)).catch(()=>{})}catch{}}}));De.replaceChildren(...te)},le=()=>{fe();let N=s&&we.length<=1,te=!!xe;if(Z.classList.toggle("persona-hidden",N||te),me.classList.toggle("persona-hidden",N||!te),te&&xe){let M=we.map(J=>J.id).join("|")+" "+(Le??"");if(M!==yt){yt=M;let J=xe({records:we,selectedId:Le,onSelect:t.onSelect});me.firstElementChild!==J&&me.replaceChildren(J)}}else{ue.beforeRender(),Z.replaceChildren();let M=[],J=-1;for(let[x,T]of we.entries()){let k=m("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");k.type="button";let H=T.artifactType==="markdown"?T.file:void 0,G=H?Pn(H.path):T.title||T.id.slice(0,8),B=H?.path||T.title||G;k.textContent=G,k.title=B,k.setAttribute("aria-label",B),T.id===Le&&(k.classList.add("persona-bg-persona-container","persona-border-persona-border"),J=x),k.addEventListener("click",()=>t.onSelect(T.id)),Z.appendChild(k),M.push(k)}if(ue.render(M,J),J>=0&&Le!==xt){xt=Le;let x=M[J];typeof x.scrollIntoView=="function"&&x.scrollIntoView({block:"nearest",inline:"nearest"})}Pe(Z)}let Fe=Le&&we.find(M=>M.id===Le)||we[we.length-1];if(!Fe){Ne.replaceChildren(),rt=null,lt(!1);return}let Se=Fe.artifactType==="markdown"?Fe.file:void 0;if(lt(!!Se),s){let M=Se?lo(Se):Fe.artifactType==="markdown"?"MD":Fe.component??"Component",J=(Fe.title||"Document").trim(),x=Se?Pn(Se.path):J.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${x} \xB7 ${M}`}else E.textContent=Se?Pn(Se.path):r;rt?(rt.el.parentElement!==Ne&&Ne.replaceChildren(rt.el),rt.update(Fe)):(rt=ja(Fe,{config:e,resolveViewMode:he}),Ne.replaceChildren(rt.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},ve=()=>{let N=we.length>0;if(h.classList.toggle("persona-hidden",!N),y){let Se=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;N&&Se&&ot?(y.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},Ct=()=>{Re=!1,le(),ve()};return{element:h,backdrop:y,update(N){we=N.artifacts,Le=N.selectedId??N.artifacts[N.artifacts.length-1]?.id??null,we.length>0&&(ot=!0),Re=!0,ie&&Ct()},setMobileOpen(N){ot=N,!N&&y?(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):ve()},setExpanded(N){let te=ne(N?"minimize":"maximize",16,"currentColor",2);te&&Ee.replaceChildren(te);let Fe=N?"Collapse artifacts panel":"Expand artifacts panel";Ee.setAttribute("aria-label",Fe),Ee.title=Fe},setExpandToggleVisible(N){Ee.classList.toggle("persona-hidden",!N)},setCopyButtonVisible(N){s||Q.classList.toggle("persona-hidden",!N)},setCustomActions(N){se=N,fe()},setTabFade(N){let te=d(N);te.start===c&&te.end===u||(c=te.start,u=te.end,Pe(Z))},setRenderTabBar(N){N!==xe&&(xe=N,yt="",le())},setVisible(N){N!==ie&&(ie=N,N&&Re&&Ct())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function lf(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Nx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var cf=["panel","seamless","detached"];function ec(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&cf.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function tc(e){return!e||!Xt(e)?!1:ec(e)==="detached"}function _s(e,t){if(!Xt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Nx(e),lf(e,t);return}let n=t.features?.artifacts?.layout,o=ec(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?e.style.setProperty("--persona-artifact-pane-bg",s):e.style.removeProperty("--persona-artifact-pane-bg");let r=n?.panePadding?.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),lf(e,t)}function $s(e,t){for(let i of cf)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=ec(t);e.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let r=n?.paneShadow?.trim();r&&e.style.setProperty("--persona-artifact-pane-shadow",r);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function df(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function Fx(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function _x(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function $x(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function jx(e,t,n,o){let s=e-o-2*t-n;return Math.max(0,s)}function nc(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let r=/^([\d.]+)/.exec(o);return r?Number(r[1]):8}function pf(e,t,n,o,s,r){let a=Fx(s,200),i=jx(t,n,o,200);i=Math.max(a,i);let p=_x(r);return p!==null&&(i=Math.min(i,p)),$x(e,a,i)}var uf={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},oc=(e,t,n,o)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(r=>{if(r.dataset.enhanced==="true")return;let a=r.dataset.tvForm??"init";r.dataset.enhanced="true";let i=uf[a]??uf.init;r.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let h=m("p","persona-text-sm persona-text-persona-muted");h.textContent=i.description,p.appendChild(h)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(h=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${h.name}`;let E=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=h.label,C.appendChild(E);let L=h.type??"text",R;L==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=L),R.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",R.id=`${t.id}-${a}-${h.name}`,R.name=h.name,R.placeholder=h.placeholder??"",h.required&&(R.required=!0),C.appendChild(R),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=i.submitLabel??"Submit",u.appendChild(y),u.appendChild(f),c.appendChild(u),r.replaceChildren(p,c),c.addEventListener("submit",async h=>{h.preventDefault();let C=n.formEndpoint??"/form",E=new FormData(c),L={};E.forEach((R,A)=>{L[A]=R}),L.type=a,f.disabled=!0,y.textContent="Submitting\u2026";try{let R=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let A=await R.json();y.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(R){y.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var rc=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(r=>r.id));return[...n.filter(r=>!o.has(r.id)),...t].sort((r,a)=>(a.priority??0)-(r.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},li=new rc;var ff=()=>{let e=new Map,t=(s,r)=>(e.has(s)||e.set(s,new Set),e.get(s).add(r),()=>n(s,r)),n=(s,r)=>{e.get(s)?.delete(r)};return{on:t,off:n,emit:(s,r)=>{e.get(s)?.forEach(a=>{try{a(r)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var Ux=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},zx=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<t.length;s+=1){let r=t[s];if(r==="{"&&(o+=1),r==="}"&&(o-=1,o===0))return t.slice(n,s+1)}return null},ci=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Ux(e),n=zx(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...r}=o;return{type:String(s),payload:r,raw:o}}catch{return null}},sc=e=>typeof e=="string"?e:e==null?"":String(e),Pr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:sc(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=sc(n.element);if(o&&t.document?.querySelector){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:sc(n.text)}}},gf=e=>Array.isArray(e)?e.map(t=>String(t)):[],di=e=>{let t=new Set(gf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(gf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let r=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:r}))};return{process:r=>{if(r.streaming||r.message.role!=="assistant"||!r.text||t.has(r.message.id))return null;let a=typeof r.raw=="string"&&r.raw||typeof r.message.rawContent=="string"&&r.message.rawContent||typeof r.text=="string"&&r.text||null;!a&&typeof r.text=="string"&&r.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:r.message})||null,null):null;if(!i)return null;t.add(r.message.id),o();let p={action:i,message:r.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(i,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let y=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:y,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var qx=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Vx=e=>e.map(t=>({...t,streaming:!1})),Kx=e=>e.map(t=>({...t,status:"complete"})),ac=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?qx(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let s={...n,messages:n.messages?Vx(n.messages):void 0,artifacts:n.artifacts?Kx(n.artifacts):void 0};o.setItem(e,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as Gx,STR as Jx,OBJ as Xx}from"partial-json";function Qx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Yx(e,t){if(!Qx(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function ic(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let s=Gx(n,Jx|Xx),r=Yx(s,n);r&&(e=r)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Zx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function lc(e,t){let{config:n,message:o,onPropsUpdate:s}=t,r=Rn.get(e.component);if(!r)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{s&&s(i)}};try{return r(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function eC(){let e=ic();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function mf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function pi(e){let t=mf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function cc(e){let t=mf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var tC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function dc(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:r="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=tC}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,y=document.createElement("div");y.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,f.appendChild(C),y.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let O=1;O<=5;O++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${O} star${O>1?"s":""}: ${d[O-1]}`),w.title=d[O-1],w.dataset.rating=String(O),w.innerHTML=`
44
+ `):""},Jl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},dx=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",r=cx(e,o?.previewMaxLines??3),a=n?wp(n):"";if(!n)return{summary:a,previewText:r,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return s==="tool-name"?d=n.name?.trim()||a:s==="tool-preview"&&r&&(d=r),i&&p.activeTextTemplate?d=gl(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=gl(n,p.completeTextTemplate,d)),{summary:d,previewText:r,isActive:i}},Ku=(e,t,n)=>{let o=kr.has(e),s=n?.toolCall??{},r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!r||!a)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=s.toggleTextColor||s.headerTextColor||"var(--persona-primary, #171717)",u=te(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Xl=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},s=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),o.backgroundColor&&(s.style.backgroundColor=o.backgroundColor),o.borderColor&&(s.style.borderColor=o.borderColor),o.borderWidth&&(s.style.borderWidth=o.borderWidth),o.borderRadius&&(s.style.borderRadius=o.borderRadius),s.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let r=t?.features?.toolCallDisplay??{},a=r.expandable!==!1,i=a&&kr.has(e.id),{summary:p,previewText:d,isActive:c}=dx(e,t),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let y=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),C=()=>{let D=m("span","");return D.setAttribute("data-tool-elapsed",h),D.textContent=fs(n),D},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:r.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:fs(n),createElapsedElement:C});typeof E=="string"&&E.trim()?(f.textContent=E,y.appendChild(f)):E instanceof HTMLElement?y.appendChild(E):(f.textContent=p,y.appendChild(f));let L=r.loadingAnimation??"none",R=o.activeTextTemplate,A=o.completeTextTemplate,I=c?R:A,_=E instanceof HTMLElement,O=(D,j)=>{f.textContent="";let ge=n.name?.trim()||"tool",be=Ea(D,ge),Ee=0;for(let De of be){let ae=De.styles.length>0?(()=>{let ve=m("span",De.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(ve),ve})():f;if(De.isDuration&&c)ae.appendChild(C());else{let ve=De.isDuration?fs(n):De.text;j?Ee=co(ae,ve,Ee):ae.appendChild(document.createTextNode(ve))}}};if(!_)if(c&&L!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),I&&O(I,!1);else if(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),I)O(I,!0);else{let j=f.textContent||p;f.textContent="",co(f,j,0)}}else I&&O(I,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",j=te(i?"chevron-up":"chevron-down",16,D,2);j?w.appendChild(j):w.textContent=i?"Hide":"Show";let ge=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ge.append(w),u.append(y,ge)}else u.append(y);let z=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!i&&c&&r.activePreview&&d){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});lx(z,D)||(z.textContent=d),z.style.display=""}if(!i&&c&&r.activeMinHeight&&(s.style.minHeight=r.activeMinHeight),!a)return s.append(u,z),s;let q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=i?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let D=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,q.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Arguments";let ge=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Jl(ge,o),ge.textContent=io(n.args),D.append(j,ge),q.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Activity";let ge=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Jl(ge,o),ge.textContent=n.chunks.join(""),D.append(j,ge),q.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),j=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(j.style.color=o.labelTextColor),j.textContent="Result";let ge=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ge.style.fontSize="0.75rem",ge.style.lineHeight="1rem",Jl(ge,o),ge.textContent=io(n.result),D.append(j,ge),q.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,q.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",j=te(i?"chevron-up":"chevron-down",16,D,2);j?w.appendChild(j):w.textContent=i?"Hide":"Show"}q.style.display=i?"":"none",z.style.display=i?"none":z.textContent||z.childNodes.length?"":"none"})(),s.append(u,z,q),s};var Xo=new Map,ai=e=>{let n=(e.startsWith(Mn)?e.slice(Mn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Gu=e=>e?.approval!==!1?e?.approval:void 0,Ju=(e,t)=>{let n=Gu(t)?.detailsDisplay??"collapsed";return Xo.get(e)??n==="expanded"},Xu=(e,t,n)=>{let o=Gu(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let r=e.querySelector("[data-approval-details-chevron]");if(r){r.innerHTML="";let a=te(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&r.appendChild(a)}},Qu=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!o||!s)return;let r=Ju(e,n);Xu(o,r,n),s.style.display=r?"":"none"};var ii=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,s=n?.status==="pending",r=m("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",r.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",r.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=te(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),y=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",y.appendChild(f),!s){let w=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),y.appendChild(w)}u.appendChild(y);let C=n.toolType==="webmcp"||n.toolName.startsWith(Mn)?is(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,R=E||(L?n.description:`The assistant wants to use \u201C${C??ai(n.toolName)}\u201D.`),A=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=R,u.appendChild(A),n.reason){let w=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let z=m("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(z),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let I=o?.detailsDisplay??"collapsed",_=!!n.description&&!L,O=_||!!n.parameters;if(I!=="hidden"&&O){let w=Ju(e.id,t),z=m("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let q=m("span");q.setAttribute("data-approval-details-label","true");let Q=m("span","persona-inline-flex persona-items-center");Q.setAttribute("data-approval-details-chevron","true"),z.append(q,Q),Xu(z,w,t),u.appendChild(z);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=w?"":"none",_){let j=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,D.appendChild(j)}if(n.parameters){let j=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(j.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=io(n.parameters),D.appendChild(j)}u.appendChild(D)}if(s){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let z=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let q=te("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",z.appendChild(q));let Q=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(Q);let D=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let j=te("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);j&&(j.style.marginRight="4px",D.appendChild(j));let ge=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(ge),w.append(z,D),u.appendChild(w)}return a.append(i,u),r.appendChild(a),r};function px(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Yu(e){let{anchor:t,content:n,placement:o="bottom-start",offset:s=6,matchAnchorWidth:r=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??px(t),y=!1,f=null,h=()=>{if(!y)return;let L=t.getBoundingClientRect();n.style.position="fixed",r&&(n.style.minWidth=`${L.width}px`),a&&(n.style.maxWidth=`${L.width}px`);let R=n.getBoundingClientRect(),A=i?.()??null,I=A!=null?L.top+A:L.top,_=o==="top-start"||o==="top-end"?I-s-R.height:L.bottom+s,w=o==="bottom-end"||o==="top-end"?L.right-R.width:L.left,z=a?.()??null;if(z!=null){let q=Math.max(L.left,L.right-R.width);w=Math.min(Math.max(L.left+z,L.left),q)}n.style.top=`${_}px`,n.style.left=`${w}px`},C=()=>{y&&(y=!1,f&&(f(),f=null),n.remove())},E=()=>{if(y)return;y=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let L=(t.ownerDocument??document).defaultView??window,R=t.ownerDocument??document,A=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}h()},I=O=>{let w=typeof O.composedPath=="function"?O.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},_=L.setTimeout(()=>{R.addEventListener("pointerdown",I,!0)},0);L.addEventListener("scroll",A,!0),L.addEventListener("resize",A),f=()=>{L.clearTimeout(_),R.removeEventListener("pointerdown",I,!0),L.removeEventListener("scroll",A,!0),L.removeEventListener("resize",A)},d?.()};return{get isOpen(){return y},open:E,close:C,toggle:()=>y?C():E(),reposition:h,destroy:C}}function Zu(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var ux=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),ef=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Qo=(e,t)=>{ef(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},fx=e=>e?.approval!==!1?e?.approval:void 0,gx=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Xo.get(e)??n==="expanded"},Ql=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},mx=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let s=e.toolType==="webmcp"||e.toolName.startsWith(Mn)?is(e.toolName):void 0,r=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...s?{displayTitle:s}:{},...e.reason?{reason:e.reason}:{}});if(r)return n.textContent=r,n;let a=s??ai(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},hx=e=>{let t=m("div","persona-approval-resolved"),n=te("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?ai(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},yx=(e,t,n,o,s,r,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,y=u&&gx(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",y?"true":"false"),C.setAttribute("aria-label",y?h:f)):C.setAttribute("data-static","true");let E=m("span","persona-approval-logo"),L=te("shield-check",16,"currentColor",2);L&&E.appendChild(L),C.appendChild(E);let R=mx(n,o);if(u){let z=m("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let q=te("chevron-down",14,"currentColor",2);q&&z.appendChild(q),R.append(" "),R.appendChild(z)}C.appendChild(R),i.appendChild(C);let A=m("div","persona-approval-body");if(u){let z=m("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!y,d){let q=m("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,z.appendChild(q)}if(c){let q=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=io(n.parameters),z.appendChild(q)}A.appendChild(z)}if(n.reason){let z=m("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let q=m("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(q,document.createTextNode(n.reason)),A.appendChild(z)}let I=m("div","persona-approval-actions"),_=null,O=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},w=m("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),a){let z=m("div","persona-approval-split"),q=m("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),O(q),q.append(o?.approveLabel??"Always allow",Ql("\u23CE"));let Q=m("button","persona-approval-caret");Q.type="button",Q.setAttribute("data-action","toggle-menu"),Q.setAttribute("aria-label","More options"),O(Q);let D=te("chevron-down",15,"currentColor",2);D&&Q.appendChild(D),z.append(q,Q),I.append(z,w),w.append(Ql("Esc"));let j=m("div","persona-approval-menu"),ge=m("button","persona-approval-menu-item");ge.type="button",ge.append("Allow once",Ql("\u2318\u23CE")),j.appendChild(ge),_=Yu({anchor:z,content:j,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,_),ge.addEventListener("click",()=>{Qo(e,t.id),s()})}else{let z=m("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),O(z),z.append(o?.approveLabel??"Allow"),I.append(z,w)}return A.appendChild(I),i.appendChild(A),i.addEventListener("click",z=>{let q=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!q)return;let Q=q.getAttribute("data-action");if(Q==="toggle-params"){let D=i.querySelector('[data-role="params"]');if(D){let j=D.hidden;D.hidden=!j,C.setAttribute("aria-expanded",j?"true":"false"),C.setAttribute("aria-label",j?h:f),Xo.set(t.id,j)}return}if(Q==="toggle-menu"){_?.toggle();return}if(Q==="always"){Qo(e,t.id),s({remember:!0});return}if(Q==="allow"){Qo(e,t.id),s();return}if(Q==="deny"){Qo(e,t.id),r();return}}),i},tf=()=>{let e=ux();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:s,deny:r,config:a})=>{let i=o?.approval;if(!i)return null;let p=fx(a);if(i.status!=="pending"){if(Qo(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return hx(i)}ef(e,o.id);let d=p?.enableAlwaysAllow===!0,c=yx(e,o,i,p,s,r,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=y=>{Zu(y)||o.id===e.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),Qo(e,o.id),y.key==="Escape"?r():y.metaKey||y.ctrlKey?s():s({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Qo(e,o);e.latestPendingApprovalId=null}}};var nf=e=>{let t=[],n=null;return{buttons:t,render:(s,r,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!s||!s.length||!c&&(i??(r?r.getMessages():[])).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),y=r?r.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(s.forEach(h=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=h,C.disabled=y,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),r.sendMessage(h))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let h=JSON.stringify(s);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var Os=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ns=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let s=o.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)o.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let r=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)o.put(s)}catch{}}};var bx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),vx=new Set(["step_start","execution_start"]),xx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cx=new Set(["step_complete","agent_turn_complete"]),wx=new Set(["flow_complete","agent_complete"]),of=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),sf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Yo=(e,t)=>{let n=e[t];return sf(n)?n:void 0};function Yl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function li(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Ax(e,t){return typeof t.type=="string"?t.type:e}function Sx(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Tx(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function rf(e){let t=Yo(e,"result"),n=[Yo(e,"tokens"),Yo(e,"totalTokens"),t?Yo(t,"tokens"):void 0,Yo(e,"usage"),t?Yo(t,"usage"):void 0];for(let o of n){if(!o)continue;let s=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(s!==void 0)return s}return an(e.outputTokens)??an(e.completionTokens)??(t?an(t.outputTokens)??an(t.completionTokens):void 0)}function Ex(e){let t=Yo(e,"result");return an(e.executionTime)??an(e.executionTimeMs)??an(e.execution_time)??an(e.duration)??(t?an(t.executionTime)??an(t.executionTimeMs):void 0)}function Mx(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Fs=class{constructor(t=Mx){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:li(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!sf(n)){of.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Ax(t,n),s=this.now();if(bx.has(o)){this.startRun(s);return}if(vx.has(o)){this.run||this.startRun(s);return}if(xx.has(o)){if(!Tx(o,n))return;let r=Sx(n);if(!r)return;this.run||this.startRun(s);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=s),a.visibleCharCount+=r.length;let i=a.exactOutputTokens+Yl(a.visibleCharCount),p=s-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:li(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Cx.has(o)){if(!this.run)return;let r=this.run,a=rf(n);a!==void 0&&(r.exactOutputTokens+=a,r.visibleCharCount=0);let i=r.exactOutputTokens>0,p=r.exactOutputTokens+Yl(r.visibleCharCount),d=this.resolveDuration(r,n,s);this.metric={status:"running",tokensPerSecond:li(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(wx.has(o)){if(!this.run)return;let r=this.run,a=rf(n),i=a??r.exactOutputTokens+Yl(r.visibleCharCount),p=a!==void 0||r.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(r,n,s);this.metric={status:"complete",tokensPerSecond:li(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(of.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let s=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return s!==void 0&&s>=250?s:Ex(n)??o-t.startedAt}};function Lr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var kx={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Lx={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Px=["flowName","stepName","reasoningText","text","name","tool","toolName"],Rx=100;function Ix(e,t){let n={...kx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Lx}function Wx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Hx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),r=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${s}.${r}`}function Bx(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let s=o.split("."),r=n;for(let a of s)if(r&&typeof r=="object"&&r!==null)r=r[a];else{r=void 0;break}if(typeof r=="string"&&r.trim())return r.trim()}}catch{}return null}function Dx(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Ox(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Nx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Fx(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function _x(e,t,n){let o,s;try{s=JSON.parse(e.payload),o=JSON.stringify(s,null,2)}catch{s=e.payload,o=e.payload}let r=t.find(i=>i.renderEventStreamPayload);if(r?.renderEventStreamPayload&&n){let i=r.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,i.appendChild(p),i}}function Zl(e,t,n,o,s,r,a,i){let p=s.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Lr(d,o.classNames?.eventRow);let c=a.find(y=>y.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let y=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>r(e.id)});if(y)return d.appendChild(y),d}return d.appendChild(u()),d;function u(){let y=m("div",""),f=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let h=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=te(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&h.appendChild(C);let E=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";E.textContent=L==="relative"?Wx(e.timestamp,n):Hx(e.timestamp);let R=null;o.showSequenceNumbers!==!1&&(R=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(t+1));let A=Ix(e.type,o.badgeColors),I=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");I.style.backgroundColor=A.bg,I.style.color=A.text,I.style.borderColor=A.text+"50",I.textContent=e.type;let _=o.descriptionFields??Px,O=Bx(e.payload,_),w=null;O&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=O);let z=m("div","persona-flex-1 persona-min-w-0"),q=m("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),Q=te("clipboard","12px","currentColor",1.5);return Q&&q.appendChild(Q),q.addEventListener("click",async D=>{D.stopPropagation(),await Dx(Ox(e)),q.innerHTML="";let j=te("check","12px","currentColor",1.5);j&&q.appendChild(j),setTimeout(()=>{q.innerHTML="";let ge=te("clipboard","12px","currentColor",1.5);ge&&q.appendChild(ge)},1500)}),f.appendChild(h),f.appendChild(E),R&&f.appendChild(R),f.appendChild(I),w&&f.appendChild(w),f.appendChild(z),f.appendChild(q),y.appendChild(f),p&&y.appendChild(_x(e,a,i)),y}}function af(e){let{buffer:t,getFullHistory:n,onClose:o,config:s,plugins:r=[],getThroughput:a}=e,i=s?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=s?.features?.eventStream??{},y=r.find(h=>h.renderEventStreamView);if(y?.renderEventStreamView&&s){let h=y.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Lr(C,h?.panel);let E=[],L="",R="",A=null,I=[],_={},O=0,w=qa(),z=0,q=0,Q=!1,D=null,j=!1,ge=0,be=new Set,Ee=new Map,De="",ae="",ve=null,Y,le,Z,Ce,me=null,pe=null,Pe=null;function Oe(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),U=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Lr(U,h?.headerBar),a){pe=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),pe.style.cursor="help",me=m("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),me.textContent="-- tok/s",Pe=m("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Pe.style.display="none",Pe.style.pointerEvents="none";let et=pe,xo=Pe,Co=()=>{if(!xo.textContent)return;let Us=et.getBoundingClientRect(),Xt=B.getBoundingClientRect();xo.style.left=`${Us.left-Xt.left}px`,xo.style.top=`${Us.bottom-Xt.top+4}px`,xo.style.display="block"},Ai=()=>{xo.style.display="none"};pe.addEventListener("mouseenter",Co),pe.addEventListener("mouseleave",Ai),pe.appendChild(me)}let oe=m("div","persona-flex-1");Y=m("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Xe=m("option","");Xe.value="",Xe.textContent="All events (0)",Y.appendChild(Xe),le=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let lt=te("clipboard-copy","12px","currentColor",1.5);lt&&le.appendChild(lt);let K=m("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",le.appendChild(K),pe&&U.appendChild(pe),U.appendChild(oe),U.appendChild(Y),U.appendChild(le);let Ue=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Lr(Ue,h?.searchBar);let Te=te("search","14px","var(--persona-muted, #9ca3af)",1.5),We=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Te&&We.appendChild(Te),Z=m("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Lr(Z,h?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",Ce=m("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Ce.type="button",Ce.style.display="none";let Le=te("x","12px","currentColor",2);return Le&&Ce.appendChild(Le),Ue.appendChild(We),Ue.appendChild(Z),Ue.appendChild(Ce),B.appendChild(U),B.appendChild(Ue),Pe&&B.appendChild(Pe),B}let $e,He=r.find(B=>B.renderEventStreamToolbar);He?.renderEventStreamToolbar&&s?$e=He.renderEventStreamToolbar({config:s,defaultRenderer:()=>Oe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:U=>{L=U,ke(),xe()},onSearchChange:U=>{R=U,ke(),xe()}})??Oe():$e=Oe();let je=m("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");je.style.display="none";function Je(){if(!a||!me||!pe)return;let B=a(),U=Nx(B);me.textContent=U;let oe=Fx(B);Pe&&(Pe.textContent=oe,oe||(Pe.style.display="none")),pe.setAttribute("aria-label",oe?`Throughput: ${U}, ${oe}`:`Throughput: ${U}`)}let Me=m("div","persona-flex-1 persona-min-h-0 persona-relative"),ne=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ne.style.height="100%";let Re=m("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Lr(Re,h?.scrollIndicator),Re.style.display="none",Re.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let xt=te(d,"14px","currentColor",2);xt&&Re.appendChild(xt);let ht=m("span","");ht.textContent=c,Re.appendChild(ht);let ct=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ct.style.display="none",Me.appendChild(ne),Me.appendChild(ct),Me.appendChild(Re),C.setAttribute("tabindex","0"),C.appendChild($e),C.appendChild(je),C.appendChild(Me);function Ie(){let B=t.getAll(),U={};for(let Ue of B)U[Ue.type]=(U[Ue.type]||0)+1;let oe=Object.keys(U).sort(),Xe=oe.length!==I.length||!oe.every((Ue,Te)=>Ue===I[Te]),Se=!Xe&&oe.some(Ue=>U[Ue]!==_[Ue]),lt=B.length!==Object.values(_).reduce((Ue,Te)=>Ue+Te,0);if(!Xe&&!Se&&!lt||(I=oe,_=U,!Y))return;let K=Y.value;if(Y.options[0].textContent=`All events (${B.length})`,Xe){for(;Y.options.length>1;)Y.remove(1);for(let Ue of oe){let Te=m("option","");Te.value=Ue,Te.textContent=`${Ue} (${U[Ue]||0})`,Y.appendChild(Te)}K&&oe.includes(K)?Y.value=K:K&&(Y.value="",L="")}else for(let Ue=1;Ue<Y.options.length;Ue++){let Te=Y.options[Ue];Te.textContent=`${Te.value} (${U[Te.value]||0})`}}function he(){let B=t.getAll();if(L&&(B=B.filter(U=>U.type===L)),R){let U=R.toLowerCase();B=B.filter(oe=>oe.type.toLowerCase().includes(U)||oe.payload.toLowerCase().includes(U))}return B}function Ye(){return L!==""||R!==""}function ke(){O=0,z=0,w.resume(),Re.style.display="none"}function fe(B){be.has(B)?be.delete(B):be.add(B),ve=B;let U=ne.scrollTop,oe=w.isFollowing();j=!0,w.pause(),xe(),ne.scrollTop=U,oe&&w.resume(),j=!1}function ie(){return mo(ne,50)}function xe(){q=Date.now(),Q=!1,Je(),Ie();let B=t.getEvictedCount();B>0?(je.textContent=`${B.toLocaleString()} older events truncated`,je.style.display=""):je.style.display="none",E=he();let U=E.length,oe=t.getSize()>0;U===0&&oe&&Ye()?(ct.textContent=R?`No events matching '${R}'`:"No events matching filter",ct.style.display="",ne.style.display="none"):(ct.style.display="none",ne.style.display=""),le&&(le.title=Ye()?`Copy Filtered (${U})`:"Copy All"),p&&!w.isFollowing()&&U>O&&(z+=U-O,ht.textContent=c?`${c}${z>0?` (${z})`:""}`:"",Re.style.display=""),O=U;let Xe=t.getAll(),Se=Xe.length>0?Xe[0].timestamp:0,lt=new Set(E.map(Te=>Te.id));for(let Te of be)lt.has(Te)||be.delete(Te);let K=L!==De||R!==ae,Ue=Ee.size===0&&E.length>0;if(K||Ue||E.length===0){ne.innerHTML="",Ee.clear();let Te=document.createDocumentFragment();for(let We=0;We<E.length;We++){let Le=Zl(E[We],We,Se,u,be,fe,r,s);Ee.set(E[We].id,Le),Te.appendChild(Le)}ne.appendChild(Te),De=L,ae=R,ve=null}else{if(ve!==null){let We=Ee.get(ve);if(We&&We.parentNode===ne){let Le=E.findIndex(et=>et.id===ve);if(Le>=0){let et=Zl(E[Le],Le,Se,u,be,fe,r,s);ne.insertBefore(et,We),We.remove(),Ee.set(ve,et)}}ve=null}let Te=new Set(E.map(We=>We.id));for(let[We,Le]of Ee)Te.has(We)||(Le.remove(),Ee.delete(We));for(let We=0;We<E.length;We++){let Le=E[We];if(!Ee.has(Le.id)){let et=Zl(Le,We,Se,u,be,fe,r,s);Ee.set(Le.id,et),ne.appendChild(et)}}}w.isFollowing()&&(ne.scrollTop=ne.scrollHeight)}function Ct(){if(Date.now()-q>=Rx){D!==null&&(cancelAnimationFrame(D),D=null),xe();return}Q||(Q=!0,D=requestAnimationFrame(()=>{D=null,xe()}))}let ye=(B,U)=>{if(!le)return;le.innerHTML="";let oe=te(B,"12px","currentColor",1.5);oe&&le.appendChild(oe);let Xe=m("span","persona-text-xs");Xe.textContent="Copy All",le.appendChild(Xe),setTimeout(()=>{le.innerHTML="";let Se=te("clipboard-copy","12px","currentColor",1.5);Se&&le.appendChild(Se);let lt=m("span","persona-text-xs");lt.textContent="Copy All",le.appendChild(lt),le.disabled=!1},U)},ue=async()=>{if(le){le.disabled=!0;try{let B;Ye()?B=E:n?(B=await n(),B.length===0&&(B=t.getAll())):B=t.getAll();let U=B.map(oe=>{try{return JSON.parse(oe.payload)}catch{return oe.payload}});await navigator.clipboard.writeText(JSON.stringify(U,null,2)),ye("check",1500)}catch{ye("x",1500)}}},gn=()=>{Y&&(L=Y.value,ke(),xe())},X=()=>{!Z||!Ce||(Ce.style.display=Z.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{R=Z.value,ke(),xe()},150))},M=()=>{!Z||!Ce||(Z.value="",R="",Ce.style.display="none",A&&clearTimeout(A),ke(),xe())},N=()=>{if(j)return;let B=ne.scrollTop,{action:U,nextLastScrollTop:oe}=Va({following:w.isFollowing(),currentScrollTop:B,lastScrollTop:ge,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ge=oe,U==="resume"?(w.resume(),z=0,Re.style.display="none"):U==="pause"&&(w.pause(),p&&(ht.textContent=c,Re.style.display=""))},v=B=>{let U=Ka({following:w.isFollowing(),deltaY:B.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});U==="pause"?(w.pause(),p&&(ht.textContent=c,Re.style.display="")):U==="resume"&&(w.resume(),z=0,Re.style.display="none")},S=()=>{p&&(ne.scrollTop=ne.scrollHeight,w.resume(),z=0,Re.style.display="none")},k=B=>{let U=B.target;if(!U||U.closest("button"))return;let oe=U.closest("[data-event-id]");if(!oe)return;let Xe=oe.getAttribute("data-event-id");Xe&&fe(Xe)},H=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Z?.focus(),Z?.select();return}B.key==="Escape"&&(Z&&document.activeElement===Z?(M(),Z.blur(),C.focus()):o&&o())};le&&le.addEventListener("click",ue),Y&&Y.addEventListener("change",gn),Z&&Z.addEventListener("input",X),Ce&&Ce.addEventListener("click",M),ne.addEventListener("scroll",N),ne.addEventListener("wheel",v,{passive:!0}),ne.addEventListener("click",k),Re.addEventListener("click",S),C.addEventListener("keydown",H);function V(){A&&clearTimeout(A),D!==null&&(cancelAnimationFrame(D),D=null),Q=!1,Ee.clear(),le&&le.removeEventListener("click",ue),Y&&Y.removeEventListener("change",gn),Z&&Z.removeEventListener("input",X),Ce&&Ce.removeEventListener("click",M),ne.removeEventListener("scroll",N),ne.removeEventListener("wheel",v),ne.removeEventListener("click",k),Re.removeEventListener("click",S),C.removeEventListener("keydown",H)}return{element:C,update:Ct,destroy:V}}}function ec(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",s=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let r=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let y=u;return r.findIndex(f=>f===y||f.contains(y))},d=u=>{let y=p(u.target);if(y<0)return;let f=y;if(u.key===s)f=Math.min(y+1,r.length-1);else if(u.key===o)f=Math.max(y-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=r.length-1;else return;u.preventDefault(),f!==y&&t.onSelect(f)},c=u=>{let y=p(u.target);y>=0&&i(r[y])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,y){if(r=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let C=h===y;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||y<0&&h===0?0:-1}),a){let f=(y>=0?u[y]:void 0)??u[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function lf(e,t){let n=e.features?.artifacts?.layout,s=(n?.toolbarPreset??"default")==="document",r=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=X=>({start:X===!1?!1:typeof X=="object"&&X?X.start!==!1:!0,end:X===!1?!1:typeof X=="object"&&X?X.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),y=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{y?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),j?.hide()};y&&y.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=m("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),s&&h.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&C.classList.add("persona-artifact-toolbar-document");let E=m("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=r;let L=gt({icon:"x",label:a});L.addEventListener("click",()=>{f(),t.onDismiss?.()});let R="rendered",A=fo({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:s?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:s?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:X=>{R=X==="source"?"source":"rendered",ye()}}),I=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),_=n?.documentToolbarShowCopyLabel===!0,O=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,z=!!(O&&w&&w.length>0),q=null,Q,D=null,j=null;if(s&&(_||O)&&!z){if(Q=_?uo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O){let X=te("chevron-down",14,"currentColor",2);X&&Q.appendChild(X)}}else s&&z?(q=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=_?uo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=gt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),q.append(Q,D)):s?Q=gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Q=gt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Q.classList.add("persona-hidden"));let ge=s?gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):gt({icon:"refresh-cw",label:"Refresh"}),be=s?gt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):gt({icon:"x",label:a}),Ee=gt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(s?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ee.classList.add("persona-hidden");let De=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ae=e.features?.artifacts?.toolbarActions??[],ve=()=>{let X=Me.find(S=>S.id===ne)??Me[Me.length-1],M=X?.id??null,N=X?.artifactType==="markdown"?X.markdown??"":"",v=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:N,jsonPayload:v,id:M}},Y=async()=>{let X=Me.find(M=>M.id===ne)??Me[Me.length-1];try{await navigator.clipboard.writeText(Ms(X))}catch{}};if(Q.addEventListener("click",async()=>{let X=n?.onDocumentToolbarCopyMenuSelect;if(X&&z){let{markdown:M,jsonPayload:N,id:v}=ve();try{await X({actionId:"primary",artifactId:v,markdown:M,jsonPayload:N})}catch{}return}await Y()}),D&&w?.length){let X=()=>h.closest("[data-persona-root]")??document.body,M=()=>{j=Jo({items:w.map(N=>({id:N.id,label:N.label})),onSelect:async N=>{let{markdown:v,jsonPayload:S,id:k}=ve(),H=n?.onDocumentToolbarCopyMenuSelect;try{H?await H({actionId:N,artifactId:k,markdown:v,jsonPayload:S}):N==="markdown"||N==="md"?await navigator.clipboard.writeText(v):N==="json"||N==="source"?await navigator.clipboard.writeText(S):await navigator.clipboard.writeText(v||S)}catch{}},anchor:q??D,position:"bottom-right",portal:X()})};h.isConnected?M():requestAnimationFrame(M),D.addEventListener("click",N=>{N.stopPropagation(),j?.toggle()})}ge.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ye()}),be.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=m("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(s)C.replaceChildren(),q?I.append(q,ge,be):I.append(Q,ge,be),I.insertBefore(De,be),I.insertBefore(Ee,be),C.append(A.element,le,I);else{let X=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");X.append(Q,De,Ee,L),C.appendChild(E),C.appendChild(X)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Z=m("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let Ce=e.features?.artifacts?.renderTabBar,me=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),pe=ec(Z,{onSelect:X=>t.onSelect(Me[X].id)}),Pe=X=>{let M=X.scrollWidth-X.clientWidth,N=M>1,v=Math.abs(X.scrollLeft);X.classList.toggle("persona-artifact-tab-fade-start",c&&N&&v>1),X.classList.toggle("persona-artifact-tab-fade-end",u&&N&&v<M-1)},Oe=0,$e=()=>{if(Oe)return;let X=()=>{Oe=0,Pe(Z)};Oe=typeof requestAnimationFrame=="function"?requestAnimationFrame(X):setTimeout(X,0)};Z.addEventListener("scroll",()=>$e(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Pe(Z)).observe(Z);let He=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),je=()=>{He.scrollLeft=0},Je=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(je):setTimeout(je,0)};if(i){for(let X of[Z,me])X.style.paddingLeft=i,X.style.paddingRight=i;He.style.padding=i}h.appendChild(C),h.appendChild(Z),h.appendChild(me),h.appendChild(He);let Me=[],ne=null,Re=!1,xt=!1,ht=!0,ct=!1,Ie=null,he="",Ye=null,ke=!1,fe=X=>X.artifactType==="markdown"&&!!X.file||s?R:"rendered",ie=X=>{s||(X&&!ke?(C.insertBefore(A.element,E),ke=!0):!X&&ke&&(A.element.remove(),ke=!1))},xe=()=>ne&&Me.find(X=>X.id===ne)||Me[Me.length-1],Ct=()=>{let X=Ts(xe());if(!X){De.replaceChildren();return}let M=ae.filter(N=>N.visible===void 0||N.visible(X)).map(N=>Ar(N,{documentChrome:s,onClick:()=>{let v=Ts(xe());if(v)try{Promise.resolve(N.onClick(v)).catch(()=>{})}catch{}}}));De.replaceChildren(...M)},ye=()=>{Ct();let X=s&&Me.length<=1,M=!!Ce;if(Z.classList.toggle("persona-hidden",X||M),me.classList.toggle("persona-hidden",X||!M),M&&Ce){let S=Me.map(k=>k.id).join("|")+" "+(ne??"");if(S!==he){he=S;let k=Ce({records:Me,selectedId:ne,onSelect:t.onSelect});me.firstElementChild!==k&&me.replaceChildren(k)}}else{pe.beforeRender(),Z.replaceChildren();let S=[],k=-1;for(let[H,V]of Me.entries()){let B=m("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");B.type="button";let U=V.artifactType==="markdown"?V.file:void 0,oe=U?Pn(U.path):V.title||V.id.slice(0,8),Xe=U?.path||V.title||oe;B.textContent=oe,B.title=Xe,B.setAttribute("aria-label",Xe),V.id===ne&&(B.classList.add("persona-bg-persona-container","persona-border-persona-border"),k=H),B.addEventListener("click",()=>t.onSelect(V.id)),Z.appendChild(B),S.push(B)}if(pe.render(S,k),k>=0&&ne!==Ie){Ie=ne;let H=S[k];typeof H.scrollIntoView=="function"&&H.scrollIntoView({block:"nearest",inline:"nearest"})}Pe(Z)}let N=ne&&Me.find(S=>S.id===ne)||Me[Me.length-1];if(!N){He.replaceChildren(),Ye=null,ie(!1);return}let v=N.artifactType==="markdown"?N.file:void 0;if(ie(!!v),s){let S=v?lo(v):N.artifactType==="markdown"?"MD":N.component??"Component",k=(N.title||"Document").trim(),H=v?Pn(v.path):k.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${H} \xB7 ${S}`}else E.textContent=v?Pn(v.path):r;Ye?(Ye.el.parentElement!==He&&He.replaceChildren(Ye.el),Ye.update(N)):(Ye=Ua(N,{config:e,resolveViewMode:fe}),He.replaceChildren(Ye.el)),He.classList.toggle("persona-artifact-content-flush",!!He.querySelector(".persona-code-pre"))},ue=()=>{let X=Me.length>0;if(h.classList.toggle("persona-hidden",!X),y){let v=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;X&&v&&Re?(y.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},gn=()=>{ct=!1,ye(),ue()};return{element:h,backdrop:y,update(X){let M=X.selectedId??X.artifacts[X.artifacts.length-1]?.id??null,N=M!==ne;Me=X.artifacts,ne=M,Me.length>0&&(Re=!0),ct=!0,ht&&gn(),N&&je()},setMobileOpen(X){Re=X,!X&&y?(y.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):ue()},setExpanded(X){X!==xt&&(xt=X,Je());let M=te(X?"minimize":"maximize",16,"currentColor",2);M&&Ee.replaceChildren(M);let N=X?"Collapse artifacts panel":"Expand artifacts panel";Ee.setAttribute("aria-label",N),Ee.title=N},setExpandToggleVisible(X){Ee.classList.toggle("persona-hidden",!X)},setCopyButtonVisible(X){s||Q.classList.toggle("persona-hidden",!X)},setCustomActions(X){ae=X,Ct()},setTabFade(X){let M=d(X);M.start===c&&M.end===u||(c=M.start,u=M.end,Pe(Z))},setRenderTabBar(X){X!==Ce&&(Ce=X,he="",ye())},setVisible(X){X!==ht&&(ht=X,X&&ct&&gn())}}}function Jt(e){return e?.features?.artifacts?.enabled===!0}function cf(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function $x(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var df=["panel","seamless","detached"];function tc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&df.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function nc(e){return!e||!Jt(e)?!1:tc(e)==="detached"}function _s(e,t){if(!Jt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),$x(e),cf(e,t);return}let n=t.features?.artifacts?.layout,o=tc(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?e.style.setProperty("--persona-artifact-pane-bg",s):e.style.removeProperty("--persona-artifact-pane-bg");let r=n?.panePadding?.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),cf(e,t)}function $s(e,t){for(let i of df)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=tc(t);e.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let r=n?.paneShadow?.trim();r&&e.style.setProperty("--persona-artifact-pane-shadow",r);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function pf(e,t){return!t||!Jt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function jx(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Ux(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function zx(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function qx(e,t,n,o){let s=e-o-2*t-n;return Math.max(0,s)}function oc(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let r=/^([\d.]+)/.exec(o);return r?Number(r[1]):8}function uf(e,t,n,o,s,r){let a=jx(s,200),i=qx(t,n,o,200);i=Math.max(a,i);let p=Ux(r);return p!==null&&(i=Math.min(i,p)),zx(e,a,i)}var ff={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},rc=(e,t,n,o)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(r=>{if(r.dataset.enhanced==="true")return;let a=r.dataset.tvForm??"init";r.dataset.enhanced="true";let i=ff[a]??ff.init;r.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let h=m("p","persona-text-sm persona-text-persona-muted");h.textContent=i.description,p.appendChild(h)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(h=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${h.name}`;let E=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=h.label,C.appendChild(E);let L=h.type??"text",R;L==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=L),R.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",R.id=`${t.id}-${a}-${h.name}`,R.name=h.name,R.placeholder=h.placeholder??"",h.required&&(R.required=!0),C.appendChild(R),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=i.submitLabel??"Submit",u.appendChild(y),u.appendChild(f),c.appendChild(u),r.replaceChildren(p,c),c.addEventListener("submit",async h=>{h.preventDefault();let C=n.formEndpoint??"/form",E=new FormData(c),L={};E.forEach((R,A)=>{L[A]=R}),L.type=a,f.disabled=!0,y.textContent="Submitting\u2026";try{let R=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let A=await R.json();y.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(R){y.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var sc=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(r=>r.id));return[...n.filter(r=>!o.has(r.id)),...t].sort((r,a)=>(a.priority??0)-(r.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ci=new sc;var gf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vx=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),mf=(e,t,n)=>{if(!gf(e)||!gf(t)||Vx.has(n))return t;let o={...e};for(let s of Object.keys(t)){if(t[s]===void 0){delete o[s];continue}let r=n?`${n}.${s}`:s;o[s]=mf(e[s],t[s],r)}return o};function di(e,t){let n=mf(e,t,"");return ws(n)}var hf=()=>{let e=new Map,t=(s,r)=>(e.has(s)||e.set(s,new Set),e.get(s).add(r),()=>n(s,r)),n=(s,r)=>{e.get(s)?.delete(r)};return{on:t,off:n,emit:(s,r)=>{e.get(s)?.forEach(a=>{try{a(r)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var Kx=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Gx=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<t.length;s+=1){let r=t[s];if(r==="{"&&(o+=1),r==="}"&&(o-=1,o===0))return t.slice(n,s+1)}return null},pi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Kx(e),n=Gx(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...r}=o;return{type:String(s),payload:r,raw:o}}catch{return null}},ac=e=>typeof e=="string"?e:e==null?"":String(e),Pr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ac(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=ac(n.element);if(o&&t.document?.querySelector){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:ac(n.text)}}},yf=e=>Array.isArray(e)?e.map(t=>String(t)):[],ui=e=>{let t=new Set(yf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(yf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let r=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:r}))};return{process:r=>{if(r.streaming||r.message.role!=="assistant"||!r.text||t.has(r.message.id))return null;let a=typeof r.raw=="string"&&r.raw||typeof r.message.rawContent=="string"&&r.message.rawContent||typeof r.text=="string"&&r.text||null;!a&&typeof r.text=="string"&&r.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:r.message})||null,null):null;if(!i)return null;t.add(r.message.id),o();let p={action:i,message:r.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(i,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let y=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:y,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var Jx=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Xx=e=>e.map(t=>({...t,streaming:!1})),Qx=e=>e.map(t=>({...t,status:"complete"})),ic=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Jx(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let s={...n,messages:n.messages?Xx(n.messages):void 0,artifacts:n.artifacts?Qx(n.artifacts):void 0};o.setItem(e,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as Yx,STR as Zx,OBJ as eC}from"partial-json";function tC(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function nC(e,t){if(!tC(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function lc(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let s=Yx(n,Zx|eC),r=nC(s,n);r&&(e=r)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function oC(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function cc(e,t){let{config:n,message:o,onPropsUpdate:s}=t,r=Rn.get(e.component);if(!r)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{s&&s(i)}};try{return r(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function rC(){let e=lc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function bf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function fi(e){let t=bf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function dc(e){let t=bf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var sC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function pc(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:r="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=sC}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,y=document.createElement("div");y.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,f.appendChild(C),y.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let O=1;O<=5;O++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${O} star${O>1?"s":""}: ${d[O-1]}`),w.title=d[O-1],w.dataset.rating=String(O),w.innerHTML=`
45
45
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
46
46
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
47
47
  </svg>
48
- `,w.addEventListener("click",()=>{u=O,L.forEach((U,q)=>{let Q=q<O;U.classList.toggle("selected",Q),U.setAttribute("aria-checked",q===O-1?"true":"false")})}),L.push(w),E.appendChild(w)}y.appendChild(E);let R=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=r,R.rows=3,R.setAttribute("aria-label","Additional comments"),O.appendChild(R),y.appendChild(O)}let A=document.createElement("div");A.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{n?.(),c.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let O=R?.value.trim()||void 0;await t(u,O),c.remove()}catch(O){_.disabled=!1,_.textContent=a,console.error("[CSAT Feedback] Failed to submit:",O)}}),A.appendChild(I),A.appendChild(_),y.appendChild(A),c.appendChild(y),c}function pc(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:r="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let y=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,h.appendChild(C);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,h.appendChild(E),f.appendChild(h);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=d;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=c,R.appendChild(A),R.appendChild(I);let _=document.createElement("div");_.className="persona-feedback-numbers";let O=[];for(let D=0;D<=10;D++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${D} out of 10`),j.textContent=String(D),j.dataset.rating=String(D),D<=6?j.classList.add("persona-feedback-detractor"):D<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{y=D,O.forEach((ge,ye)=>{ge.classList.toggle("selected",ye===D),ge.setAttribute("aria-checked",ye===D?"true":"false")})}),O.push(j),_.appendChild(j)}L.appendChild(R),L.appendChild(_),f.appendChild(L);let w=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=r,w.rows=3,w.setAttribute("aria-label","Additional comments"),D.appendChild(w),f.appendChild(D)}let U=document.createElement("div");U.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=i,q.addEventListener("click",()=>{n?.(),u.remove()});let Q=document.createElement("button");return Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-submit",Q.textContent=a,Q.addEventListener("click",async()=>{if(y===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}Q.disabled=!0,Q.textContent="Submitting...";try{let D=w?.value.trim()||void 0;await t(y,D),u.remove()}catch(D){Q.disabled=!1,Q.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),U.appendChild(q),U.appendChild(Q),f.appendChild(U),u.appendChild(f),u}var Rr="persona-chat-history",nC=30*1e3,oC=641,rC={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function sC(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let s=o.getAsFile();if(!s)continue;if(s.name){t.push(s);continue}let r=rC[s.type]??"png";t.push(new File([s],`clipboard-image-${Date.now()}.${r}`,{type:s.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function ui(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function aC(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function iC(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var uc=e=>!e||typeof e!="object"?{}:{...e},hf=e=>e.map(t=>({...t,streaming:!1})),yf=(e,t,n)=>{let o=e?.markdown?fr(e.markdown):null,s=ss(e?.sanitize);return e?.postprocessMessage&&s&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),r=>{let a=r.text??"",i=r.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:r.message,streaming:r.streaming});c!==null&&(a=c.text,c.persist||(r.message.__skipPersist=!0),c.resubmit&&!r.streaming&&n&&n())}let p=_n()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...r,text:a,raw:i??r.text??""});d=s?s(c):c}else if(o){let c=r.streaming?Vd(a):a,u=o(c);d=s&&p?s(u):u}else d=$n(a);return d}};function bf(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",s=e?.iconColor??"rgba(59, 130, 246, 0.6)",r=e?.iconStrokeWidth??.5,a=ne(n,o,s,r);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var lC=(e,t)=>{let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];n[o]=r?{...r,...s}:s}return n},cC=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:lC(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),fc=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=El(t),s=li.getForInstance(o.plugins),{plugin:r,teardown:a}=ef();o.components&&Rn.registerAll(o.components);let i=ff(),d=o.persistState===!1?null:o.storageAdapter??ac(),c={},u=null,y=!1,f=l=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:v}=g;return v&&(y=!0),b}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(g=>f(g??{messages:[],metadata:{}}));else{let b=f(l??{messages:[],metadata:{}});b.metadata&&(c=uc(b.metadata)),b.messages?.length&&(o={...o,initialMessages:b.messages}),b.artifacts?.length&&(o={...o,initialArtifacts:b.artifacts,initialSelectedArtifactId:b.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=f({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let h=()=>c,C=l=>{c=l({...c})??{},Oi()},E=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ci],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pr.message,Pr.messageAndClick],R=di({parsers:E,handlers:L,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});R.syncFromMetadata();let A=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,_=o.autoFocusInput??!1,O=I,w=A,U=o.layout?.header?.layout,q=!1,Q=()=>yo(o),D=()=>A||Q(),j=Q()?!1:A?I:!0,ge=!1,ye=null,Ee=()=>{ge=!0,ye&&clearTimeout(ye),ye=setTimeout(()=>{ge&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ge=!1)},1e4)},De=yf(o,R,Ee),se=o.features?.showReasoning??!0,be=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ce=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},me=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ue=Y?new Ns(me):null,Pe=o.features?.eventStream?.maxEvents??2e3,Oe=Y?new Os(Pe,ue):null,Ue=Y?new Fs:null,Ne=null,we=!1,Le=null,ot=0;ue?.open().then(()=>Oe?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ie={onCopy:l=>{i.emit("message:copy",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(l)}},Re=o.statusIndicator??{},xt=l=>l==="idle"?Re.idleText??Ht.idle:l==="connecting"?Re.connectingText??Ht.connecting:l==="connected"?Re.connectedText??Ht.connected:l==="error"?Re.errorText??Ht.error:l==="paused"?Re.pausedText??Ht.paused:l==="resuming"?Re.resumingText??Ht.resuming:Ht[l];function yt(l,g,b,v){if(v==="idle"&&b.idleLink){l.textContent="";let S=document.createElement("a");S.href=b.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=g,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=g}let rt=Nu({config:o,showClose:D()}),{wrapper:Me,panel:he,pillRoot:lt}=rt.shell,Ie=rt.panelElements,{container:fe,body:le,messagesWrapper:ve,suggestions:Ct,textarea:N,sendButton:te,sendButtonWrapper:Fe,composerForm:Se,statusText:M,introTitle:J,introSubtitle:x,closeButton:T,iconHolder:k,headerTitle:H,headerSubtitle:G,header:B,footer:z,actionsRow:ae,rightActions:tt}=Ie,Te=Ie.leftActions,ct=Ie.setSendButtonMode,V=Ie.micButton,ze=Ie.micButtonWrapper,We=Ie.attachmentButton,He=Ie.attachmentButtonWrapper,ke=Ie.attachmentInput,Qe=Ie.attachmentPreviewsContainer;fe.classList.add("persona-relative"),le.classList.add("persona-relative");let xo=12,Co=()=>ce.label??"",Ci=()=>ce.iconName??"arrow-down",Us=()=>ce.enabled!==!1,Qt=()=>Z.mode??"anchor-top",qn=()=>Qt()==="follow"||Qt()==="anchor-top"&&_r,Sc=()=>Z.anchorTopOffset??16,eg=()=>Z.restorePosition??"bottom",Tc=()=>Z.pauseOnInteraction===!0,Ec=()=>Z.showActivityWhilePinned!==!1,Mc=()=>Z.announce===!0,It=m("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");It.type="button",It.style.display="none",It.setAttribute("data-persona-scroll-to-bottom","true");let Ir=m("span","persona-flex persona-items-center"),wi=m("span",""),wo=m("span","");wo.setAttribute("data-persona-scroll-to-bottom-count",""),wo.style.display="none",It.append(Ir,wi,wo),fe.appendChild(It);let Vn=m("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",le.appendChild(Vn);let Ao=m("div","persona-sr-only");Ao.setAttribute("aria-live","polite"),Ao.setAttribute("aria-atomic","true"),Ao.setAttribute("role","status"),Ao.setAttribute("data-persona-live-region",""),Object.assign(Ao.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),fe.appendChild(Ao);let Wr=null,zs=null,kc=l=>{!Mc()||!l||(zs=l,Wr===null&&(Wr=setTimeout(()=>{Wr=null,zs&&Mc()&&(Ao.textContent=zs),zs=null},400)))},Zo=()=>{let g=z.style.display==="none"?0:z.offsetHeight;It.style.bottom=`${g+xo}px`};Zo();let Lc=()=>{let l=!!Co();It.setAttribute("aria-label",Co()||"Jump to latest"),It.title=Co(),It.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Ir.innerHTML="";let g=ne(Ci(),"14px","currentColor",2);g?(Ir.appendChild(g),Ir.style.display=""):Ir.style.display="none",wi.textContent=Co(),wi.style.display=l?"":"none"};Lc();let kt=null,en=null,Pc=null,Rc=s.find(l=>l.renderHeader);if(Rc?.renderHeader){let l=Rc.renderHeader({config:o,defaultRenderer:()=>{let g=bo({config:o,showClose:D()});return Tr(fe,g,o),g.header},onClose:()=>ht(!1,"user")});if(l){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),B=l,rt.header.element=l)}}let Ai=()=>{if(!Oe)return;if(we=!0,!Ne&&Oe&&(Ne=sf({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Hr(),config:o,plugins:s,getThroughput:()=>Ue?.getMetric()??{status:"idle"}})),Ne&&(le.style.display="none",z.parentNode?.insertBefore(Ne.element,z),Ne.update()),at){at.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(b=>b&&at.classList.add(b))}let l=()=>{if(!we)return;let g=Date.now();g-ot>=200&&(Ne?.update(),ot=g),Le=requestAnimationFrame(l)};ot=0,Le=requestAnimationFrame(l),nn(),i.emit("eventStream:opened",{timestamp:Date.now()})},Hr=()=>{if(we){if(we=!1,Ne&&Ne.element.remove(),le.style.display="",at){at.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&at.classList.remove(g))}Le!==null&&(cancelAnimationFrame(Le),Le=null),nn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},at=null;if(Y){let l=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");at=m("button",g),at.style.width="28px",at.style.height="28px",at.style.color=Jt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let b=ne("activity","18px","currentColor",1.5);b&&at.appendChild(b);let v=Ie.clearChatButtonWrapper,S=Ie.closeButtonWrapper,P=v||S;P&&P.parentNode===B?B.insertBefore(at,P):B.appendChild(at),at.addEventListener("click",()=>{we?Hr():Ai()})}let tg=l=>{let g=o.attachments;if(!g?.enabled)return;let b=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!b){b=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.setAttribute("data-persona-composer-attachment-previews",""),b.style.display="none";let S=l.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(b,S):l.insertBefore(b,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let S=m("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(g.allowedTypes??Un).join(","),S.multiple=(g.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(S)}},Ic=s.find(l=>l.renderComposer);if(Ic?.renderComposer){let l=o.composer,g=Ic.renderComposer({config:o,defaultRenderer:()=>Bs({config:o}).footer,onSubmit:b=>{if(!$||$.isStreaming())return;let v=b.trim(),S=kt?.hasAttachments()??!1;if(!v&&!S)return;id();let P;S&&(P=[],P.push(...kt.getContentParts()),v&&P.push(Uo(v))),$.sendMessage(v,{contentParts:P}),S&&kt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ke?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:b=>{o.composer={...o.composer,selectedModelId:b},o.agent&&(o.agent={...o.agent,model:b})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Pc?.()}:void 0});g&&(rt.replaceComposer(g),z=rt.composer.footer)}let ng=l=>{let g=(...de)=>{for(let re of de){let Ce=l.querySelector(re);if(Ce)return Ce}return null},b=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),P=l.querySelector("[data-persona-composer-mic]"),X=l.querySelector("[data-persona-composer-status]");b&&(Se=b),v&&(N=v),S&&(te=S),P&&(V=P,ze=P.parentElement),X&&(M=X);let F=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Ct=F);let K=g("[data-persona-composer-attachment-button]",".persona-attachment-button");K&&(We=K,He=K.parentElement),ke=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Qe=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(ae=oe),Te=g(".persona-widget-composer__left-actions")};tg(z),ng(z);let Kn=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Kn&&(ve.style.maxWidth=Kn,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%"),Kn&&Se&&!Q()&&(Se.style.maxWidth=Kn,Se.style.marginLeft="auto",Se.style.marginRight="auto"),Kn&&Ct&&!Q()&&(Ct.style.maxWidth=Kn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Kn&&Qe&&!Q()&&(Qe.style.maxWidth=Kn,Qe.style.marginLeft="auto",Qe.style.marginRight="auto"),o.attachments?.enabled&&ke&&Qe){kt=vr.fromConfig(o.attachments),kt.setPreviewsContainer(Qe),ke.addEventListener("change",b=>{let v=b.target;kt?.handleFileSelect(v.files),v.value=""});let l=o.attachments.dropOverlay,g=bf(l);fe.appendChild(g)}let og=()=>en?.prefetch();if(o.contextMentions?.enabled&&N&&(en=qp({config:o,textarea:N,anchor:Se??N,getMessages:()=>$.getMessages(),liveRegionHost:fe}),en)){let l=N;l.parentElement?.insertBefore(en.contextRow,l);let g=en.affordanceButtons;for(let b=g.length-1;b>=0;b--){let v=g[b];Te?Te.insertBefore(v,Te.firstChild):Se?.appendChild(v)}}(()=>{let l=o.layout?.slots??{},g=v=>{switch(v){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ve;case"footer-top":return Ct;case"composer":return Se;case"footer-bottom":return M;default:return null}},b=(v,S)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")B.insertBefore(S,B.firstChild);else if(v==="header-right")B.appendChild(S);else{let P=B.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(S,P.nextSibling):B.appendChild(S)}break;case"body-top":{let P=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");P?P.replaceWith(S):le.insertBefore(S,le.firstChild);break}case"body-bottom":le.appendChild(S);break;case"footer-top":Ct.replaceWith(S);break;case"footer-bottom":M.replaceWith(S);break;default:break}};for(let[v,S]of Object.entries(l))if(S)try{let P=S({config:o,defaultContent:()=>g(v)});P&&b(v,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,P)}})();let Wc=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let v=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let S=v.getAttribute("data-message-id");if(!S)return;let P=b.getAttribute("data-bubble-type");if(P==="reasoning")Mr.has(S)?Mr.delete(S):Mr.add(S),qu(S,v);else if(P==="tool")kr.has(S)?kr.delete(S):kr.add(S),Vu(S,v,o);else if(P==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",K=Xo.get(S)??F;Xo.set(S,!K),Xu(S,v,o)}Mo.delete(S)};ve.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Wc(l))}),ve.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Wc(l))}),ve.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let b=ve.getRootNode(),v=typeof b.getSelection=="function"?b.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let S=v.toString(),P=bu(S);!P||P===S||(g.setData("text/plain",P),l.preventDefault())});let Si=new Map,Hc=null,Bc="idle",rg={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},sg=(l,g)=>{let{icon:b,label:v}=rg[g];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",g==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",g!=="idle"),l.classList.toggle("persona-message-action-loading",g==="loading");let S=ne(b,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Dc=()=>{ve.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let v=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;sg(g,v&&v===Hc?Bc:"idle")})};ve.addEventListener("click",l=>{let b=l.target.closest(".persona-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.closest("[data-actions-for]");if(!v)return;let S=v.getAttribute("data-actions-for");if(!S)return;let P=b.getAttribute("data-action");if(P==="copy"){let F=$.getMessages().find(K=>K.id===S);if(F&&ie.onCopy){let K=F.content||"";navigator.clipboard.writeText(K).then(()=>{b.classList.add("persona-message-action-success");let oe=ne("check",14,"currentColor",2);oe&&(b.innerHTML="",b.appendChild(oe)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let de=ne("copy",14,"currentColor",2);de&&(b.innerHTML="",b.appendChild(de))},2e3)}).catch(oe=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",oe)}),ie.onCopy(F)}}else if(P==="read-aloud")$.toggleReadAloud(S);else if(P==="upvote"||P==="downvote"){let F=(Si.get(S)??null)===P,K=P==="upvote"?"thumbs-up":"thumbs-down";if(F){Si.delete(S),b.classList.remove("persona-message-action-active");let oe=ne(K,14,"currentColor",2);oe&&(b.innerHTML="",b.appendChild(oe))}else{let oe=P==="upvote"?"downvote":"upvote",de=v.querySelector(`[data-action="${oe}"]`);if(de){de.classList.remove("persona-message-action-active");let it=ne(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);it&&(de.innerHTML="",de.appendChild(it))}Si.set(S,P),b.classList.add("persona-message-action-active");let re=ne(K,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(re)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Ge=$.getMessages().find(bt=>bt.id===S);Ge&&ie.onFeedback&&ie.onFeedback({type:P,messageId:Ge.id,message:Ge})}}}),ve.addEventListener("click",l=>{let b=l.target.closest("button[data-approval-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.closest(".persona-approval-bubble");if(!v)return;let S=v.getAttribute("data-message-id");if(!S)return;let P=b.getAttribute("data-approval-action");if(!P)return;let X=P==="approve"?"approved":"denied",K=$.getMessages().find(de=>de.id===S);if(!K?.approval)return;let oe=v.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),K.approval.toolType==="webmcp"?$.resolveWebMcpApproval(S,X):$.resolveApproval(K.approval,X)});let Ye=null,Br=null,Dr=()=>{},Or="none",qs=null,mn={artifacts:[],selectedId:null},Hn=!1,hn=!1,Nr=!1,er=!1,Oc=()=>er||mn.artifacts.some(l=>Fo(o.features?.artifacts,l.artifactType)==="panel"),Vs=()=>mn.artifacts.length>0&&!Hn&&Oc(),gt={current:null},Ti=(l,g)=>{let b=$.getArtifactById(g),v=b?.markdown,S=b?.title||"artifact",P=b?.file,X=b?.artifactType??"markdown";if(!v){let oe=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(oe){let re=$.getMessages().find(Ce=>Ce.id===oe);if(re?.rawContent)try{let Ce=JSON.parse(re.rawContent);v=Ce?.props?.markdown,S=Ce?.props?.title||S,Ce?.props?.file&&typeof Ce.props.file=="object"&&(P=Ce.props.file),!b&&typeof Ce?.props?.artifactType=="string"&&(X=Ce.props.artifactType)}catch{}}}return{markdown:v,title:S,file:P,artifactType:X}};ve.addEventListener("click",l=>{let b=l.target.closest("[data-download-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:P,title:X,file:F}=Ti(b,v);if(!P)return;let{filename:K,mime:oe,content:de}=tu({title:X,markdown:P,file:F}),re=new Blob([de],{type:oe}),Ce=URL.createObjectURL(re),Ge=document.createElement("a");Ge.href=Ce,Ge.download=K,Ge.click(),URL.revokeObjectURL(Ce)}),ve.addEventListener("click",l=>{let b=l.target.closest("[data-artifact-custom-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-artifact-custom-action");if(!v)return;let S=b.closest("[data-artifact-inline]"),P=S?null:b.closest("[data-open-artifact]"),X=S?S.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,K=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(bt=>bt.id===v);if(!K)return;let{markdown:oe,title:de,file:re,artifactType:Ce}=Ti(b,X??""),Ge={artifactId:X,title:de,artifactType:Ce,markdown:oe,file:re};try{Promise.resolve(K.onClick(Ge)).catch(()=>{})}catch{}}),ve.addEventListener("click",l=>{let b=l.target.closest("[data-copy-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-copy-artifact");if(!v)return;let S=$.getArtifactById(v),P="";if(S)P=Ms(S);else{let{markdown:X,file:F,artifactType:K}=Ti(b,v);K==="markdown"&&(P=Ms({id:v,artifactType:"markdown",status:"complete",markdown:X??"",...F?{file:F}:{}}))}P&&navigator.clipboard.writeText(P).then(()=>{let X=ne("check",16,"currentColor",2);X&&(b.replaceChildren(X),setTimeout(()=>{let F=ne("copy",16,"currentColor",2);F&&b.replaceChildren(F)},1500))}).catch(()=>{})}),ve.addEventListener("click",l=>{let b=l.target.closest("[data-expand-artifact-inline]");if(!b)return;l.preventDefault(),l.stopPropagation();let v=b.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Hn=!1,er=!0,hn=!0,Nr=!0,$.selectArtifact(v),Bn())}),ve.addEventListener("click",l=>{let g=l.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let b=g.closest("[data-open-artifact]");if(!b)return;let v=b.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(l.preventDefault(),l.stopPropagation(),Hn=!1,er=!0,$.selectArtifact(v),Bn())}),ve.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),g.click())});let tr=Ie.composerOverlay,nr=(l,g,b)=>{let v=g.trim();if(!v||!gt.current)return;let S=l.getAttribute("data-tool-call-id")??"",P=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:v,answers:b.structured,values:b.values??(b.source==="multi"?v.split(", "):[v]),isFreeText:P,source:b.source},bubbles:!0,composed:!0})),$o(tr,S);let X=gt.current.getMessages().find(F=>F.toolCall?.id===S);X?.agentMetadata?.awaitingLocalTool?gt.current.resolveAskUserQuestion(X,b.structured??v):gt.current.sendMessage(v)},So=l=>{let g=gt.current;if(!g)return;let b=l.getAttribute("data-tool-call-id")??"",v=g.getMessages().find(S=>S.toolCall?.id===b);v&&g.persistAskUserQuestionProgress(v,{answers:xa(l,v),currentIndex:fn(l)})},Nc=l=>Object.entries(l).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Ei=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=fn(l),b=mr(l);if(g>=b-1)return;let v=gt.current?.getMessages().find(S=>S.toolCall?.id===l.getAttribute("data-tool-call-id"));v&&(Ca(l,v,o,g+1),So(l))};tr.addEventListener("click",l=>{let b=l.target.closest("[data-ask-user-action]");if(!b)return;let v=b.closest("[data-persona-ask-sheet-for]");if(!v)return;let S=b.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let P=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),$o(tr,P);let X=gt.current?.getMessages().find(F=>F.toolCall?.id===P);X?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(X),gt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(S==="pick"){let P=b.getAttribute("data-option-label");if(!P)return;let X=v.getAttribute("data-multi-select")==="true",F=so(v);if(F&&X){let K=_o(v)[fn(v)],oe=new Set(Array.isArray(K)?K:[]);oe.has(P)?oe.delete(P):oe.add(P),ao(v,Array.from(oe)),So(v);return}if(F){ao(v,P),So(v),Ei(v);return}if(X){let K=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",K?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!K);let oe=v.querySelector('[data-ask-user-action="submit-multi"]');oe&&(oe.disabled=ll(v).length===0);return}nr(v,P,{source:"pick",values:[P]});return}if(S==="submit-multi"){let P=ll(v);if(P.length===0)return;nr(v,P.join(", "),{source:"multi",values:P});return}if(S==="open-free-text"){let P=v.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(S==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let X=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(so(v)){ao(v,X.trim()),So(v),Ei(v);return}nr(v,X,{source:"free-text"});return}if(S==="next"||S==="back"){if(!gt.current)return;let P=v.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(re=>re.toolCall?.id===P);if(!X)return;let K=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(K){let re=_o(v)[fn(v)];(typeof re!="string"||re!==K)&&ao(v,K)}let oe=S==="next"?1:-1,de=fn(v)+oe;Ca(v,X,o,de),So(v);return}if(S==="submit-all"){if(!gt.current)return;let P=v.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(re=>re.toolCall?.id===P);if(!X)return;let K=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";K&&ao(v,K);let oe=xa(v,X);gt.current.persistAskUserQuestionProgress(X,{answers:oe,currentIndex:fn(v)});let de=Nc(oe);nr(v,de||"(submitted)",{source:"submit-all",structured:oe});return}if(S==="skip"){if(!gt.current)return;let P=v.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(Ce=>Ce.toolCall?.id===P);if(!X)return;let F=so(v),K=fn(v),oe=mr(v),de=K>=oe-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),$o(tr,P),X.agentMetadata?.awaitingLocalTool&&(gt.current.markAskUserQuestionResolved(X),gt.current.resolveAskUserQuestion(X,"(dismissed)"));return}ao(v,"");let re=v.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),de){let Ce=xa(v,X),Ge=Nc(Ce);nr(v,Ge||"(skipped)",{source:"submit-all",structured:Ce});return}Ca(v,X,o,K+1),So(v);return}}),tr.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let b=l.target;if(!b.matches?.('[data-ask-free-text-input="true"]'))return;let v=b.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let S=b.value;if(S.trim()){if(so(v)){ao(v,S.trim()),So(v),Ei(v);return}nr(v,S,{source:"free-text"})}});let Fc=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let g=l.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let b=tr.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),P=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];P&&(l.preventDefault(),P.click())};document.addEventListener("keydown",Fc);let Gn=null,wt=null,Fr=null,Ks=null,Mi=()=>{},_c=!1,Gs="",Js="";function ki(){Ks?.(),Ks=null}let $c=()=>{if(!Gn||!wt)return;let l=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,b=g.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||b){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let v=Gn.firstElementChild;if(!v||v===wt)return;let S=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${S}px`,wt.style.zIndex="5";let P=nc(Gn,g),X=v.offsetWidth+P/2-S/2;wt.style.left=`${Math.max(0,X)}px`},Xs=()=>{},ag=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>b?!1:A||Bt(o)},Qs=()=>!Xt(o)||!Vs()||e.classList.contains("persona-artifact-narrow-host")||ag()||(e.ownerDocument.defaultView??window).innerWidth<oC?"none":tc(o)?"detached":"welded",Bn=()=>{if(!Ye||!Xt(o))return;_s(e,o),$s(e,o),Xs();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=he.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let b=Vs();Ye.setVisible(b),Ye.update(mn),Hn?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Nr=!1):mn.artifacts.length>0&&Oc()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Nr=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(v),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!Nr&&(hn=!1),hn!==_c){let P=Ye.element;hn?(Gs=P.style.width,Js=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(Gs&&(P.style.width=Gs),Js&&(P.style.maxWidth=Js),Gs="",Js=""),_c=hn}e.classList.toggle("persona-artifact-expanded",hn),Ye.setExpanded(hn);let S=Qs();S!==Or&&(Or=S,Dr()),Mi()};if(Xt(o)){he.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(fe),Ye=af(o,{onSelect:b=>gt.current?.selectArtifact(b),onDismiss:()=>{Hn=!0,Bn()},onToggleExpand:()=>{let b=!hn,v=mn.selectedId??mn.artifacts[mn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:b})!==!0&&(hn=b,b||(Nr=!1),Bn())}}),Ye.element.classList.add("persona-hidden"),Gn=g,g.appendChild(l),g.appendChild(Ye.element),Ye.backdrop&&he.appendChild(Ye.backdrop),he.appendChild(g),Mi=()=>{if(!Gn||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Fr?.(),Fr=null,ki(),wt&&(wt.remove(),wt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!wt){let v=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let S=e.ownerDocument,P=S.defaultView??window,X=F=>{if(!Ye||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||P.innerWidth<=640)return;F.preventDefault(),ki();let K=F.clientX,oe=Ye.element.getBoundingClientRect().width,de=o.features?.artifacts?.layout,re=Ge=>{let bt=Gn.getBoundingClientRect().width,it=e.classList.contains("persona-artifact-welded-split"),qt=nc(Gn,P),Dt=it?0:v.getBoundingClientRect().width||6,W=oe-(Ge.clientX-K),$e=pf(W,bt,qt,Dt,de?.resizableMinWidth,de?.resizableMaxWidth);Ye.element.style.width=`${$e}px`,Ye.element.style.maxWidth="none",$c()},Ce=()=>{S.removeEventListener("pointermove",re),S.removeEventListener("pointerup",Ce),S.removeEventListener("pointercancel",Ce),Ks=null;try{v.releasePointerCapture(F.pointerId)}catch{}};Ks=Ce,S.addEventListener("pointermove",re),S.addEventListener("pointerup",Ce),S.addEventListener("pointercancel",Ce);try{v.setPointerCapture(F.pointerId)}catch{}};v.addEventListener("pointerdown",X),wt=v,Gn.insertBefore(v,Ye.element),Fr=()=>{v.removeEventListener("pointerdown",X)}}if(wt){let v=Vs();wt.classList.toggle("persona-hidden",!v),$c()}},Xs=()=>{if(!A||!Ye||(o.launcher?.sidebarMode??!1)||Bt(o)&&an(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(S&&v.innerWidth<=P||!df(o,A))return;let X=o.launcher?.width??o.launcherWidth??gn,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Vs()?(he.style.width=F,he.style.maxWidth=F):(he.style.width=X,he.style.maxWidth=X)},typeof ResizeObserver<"u"&&(Br=new ResizeObserver(()=>{Bn()}),Br.observe(he))}else he.appendChild(fe);Q()&&lt&&(Ie.peekBanner&&lt.appendChild(Ie.peekBanner),lt.appendChild(z)),e.appendChild(Me),lt&&e.appendChild(lt);let Ys=()=>{if(Q()){he.style.width="100%",he.style.maxWidth="100%";let Rt=o.launcher?.composerBar??{},Yt=Me.dataset.state==="expanded",pa=Rt.expandedSize??"anchored";if(!(Yt&&pa!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let Zr=o.theme?.components?.panel,ua=Ko(o),dr=(Fn,Bo)=>Fn==null||Fn===""?Bo:Gt(ua,Fn)??Fn,es="1px solid var(--persona-border)",Zi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ho="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=dr(Zr?.border,es),fe.style.borderRadius=dr(Zr?.borderRadius,Ho),fe.style.boxShadow=dr(Zr?.shadow,Zi),fe.style.overflow="hidden";return}let l=Bt(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,X=Ko(o),F=(Rt,Yt)=>Rt==null||Rt===""?Yt:Gt(X,Rt)??Rt,K=e.ownerDocument.defaultView??window,oe=o.launcher?.mobileFullscreen??!0,de=o.launcher?.mobileBreakpoint??640,re=K.innerWidth<=de,Ce=oe&&re&&A,Ge=l&&oe&&re,bt=o.launcher?.position??"bottom-left",it=bt==="bottom-left"||bt==="top-left",qt=o.launcher?.zIndex??Ut,Dt="var(--persona-panel-border, 1px solid var(--persona-border))",W="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",$e="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ae=S&&!Ce&&!Ge;Ae?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let je=Ae?Dt:g||Ce?"none":Dt,Mt=Ae?W:Ce?"none":g?it?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":v?"none":W;l&&!Ce&&!Ae&&(Mt="none",je="none");let pt=Ae?$e:g||Ce?"0":$e,St=F(P?.border,je),vt=F(P?.shadow,Mt),$t=F(P?.borderRadius,pt),Io=Qs(),ut=Io==="detached",pe=Io==="welded";e.classList.toggle("persona-artifact-detached-split",ut),e.classList.toggle("persona-artifact-welded-split",pe);let Tt="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",st=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Xt(o)&&tc(o)&&v&&!l;e.classList.toggle("persona-artifact-chat-flush",st);let Ve=ut||st?"none":vt,Ze=ut?Dt:pe?"none":St,Pt=ut?$e:$t;st&&(Ze="none",Pt="0");let Be=P?.borderRadius!=null&&P.borderRadius!=="",et=st&&!Be?"0":$t,on=le.scrollTop;e.style.cssText="",Me.style.cssText="",he.style.cssText="",fe.style.cssText="",le.style.cssText="",z.style.cssText="",we&&(le.style.display="none");let Wo=()=>{if(on<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===on)return;let Yt=le.scrollHeight-le.clientHeight;Yt<=0||(le.scrollTop=Math.min(on,Yt))})};if(Ce){Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Me.style.cssText=`
48
+ `,w.addEventListener("click",()=>{u=O,L.forEach((z,q)=>{let Q=q<O;z.classList.toggle("selected",Q),z.setAttribute("aria-checked",q===O-1?"true":"false")})}),L.push(w),E.appendChild(w)}y.appendChild(E);let R=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=r,R.rows=3,R.setAttribute("aria-label","Additional comments"),O.appendChild(R),y.appendChild(O)}let A=document.createElement("div");A.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{n?.(),c.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let O=R?.value.trim()||void 0;await t(u,O),c.remove()}catch(O){_.disabled=!1,_.textContent=a,console.error("[CSAT Feedback] Failed to submit:",O)}}),A.appendChild(I),A.appendChild(_),y.appendChild(A),c.appendChild(y),c}function uc(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:r="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let y=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,h.appendChild(C);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,h.appendChild(E),f.appendChild(h);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=d;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=c,R.appendChild(A),R.appendChild(I);let _=document.createElement("div");_.className="persona-feedback-numbers";let O=[];for(let D=0;D<=10;D++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${D} out of 10`),j.textContent=String(D),j.dataset.rating=String(D),D<=6?j.classList.add("persona-feedback-detractor"):D<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{y=D,O.forEach((ge,be)=>{ge.classList.toggle("selected",be===D),ge.setAttribute("aria-checked",be===D?"true":"false")})}),O.push(j),_.appendChild(j)}L.appendChild(R),L.appendChild(_),f.appendChild(L);let w=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=r,w.rows=3,w.setAttribute("aria-label","Additional comments"),D.appendChild(w),f.appendChild(D)}let z=document.createElement("div");z.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=i,q.addEventListener("click",()=>{n?.(),u.remove()});let Q=document.createElement("button");return Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-submit",Q.textContent=a,Q.addEventListener("click",async()=>{if(y===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}Q.disabled=!0,Q.textContent="Submitting...";try{let D=w?.value.trim()||void 0;await t(y,D),u.remove()}catch(D){Q.disabled=!1,Q.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),z.appendChild(q),z.appendChild(Q),f.appendChild(z),u.appendChild(f),u}var Rr="persona-chat-history",aC=30*1e3,iC=641,lC={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function cC(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let s=o.getAsFile();if(!s)continue;if(s.name){t.push(s);continue}let r=lC[s.type]??"png";t.push(new File([s],`clipboard-image-${Date.now()}.${r}`,{type:s.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function gi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function dC(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function pC(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var fc=e=>!e||typeof e!="object"?{}:{...e},vf=e=>e.map(t=>({...t,streaming:!1})),xf=(e,t,n)=>{let o=e?.markdown?fr(e.markdown):null,s=ss(e?.sanitize);return e?.postprocessMessage&&s&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),r=>{let a=r.text??"",i=r.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:r.message,streaming:r.streaming});c!==null&&(a=c.text,c.persist||(r.message.__skipPersist=!0),c.resubmit&&!r.streaming&&n&&n())}let p=_n()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...r,text:a,raw:i??r.text??""});d=s?s(c):c}else if(o){let c=r.streaming?Kd(a):a,u=o(c);d=s&&p?s(u):u}else d=$n(a);return d}};function Cf(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",s=e?.iconColor??"rgba(59, 130, 246, 0.6)",r=e?.iconStrokeWidth??.5,a=te(n,o,s,r);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var uC=(e,t)=>{let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];n[o]=r?{...r,...s}:s}return n},fC=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:uC(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),gc=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=ws(t),s=ci.getForInstance(o.plugins),{plugin:r,teardown:a}=tf();o.components&&Rn.registerAll(o.components);let i=hf(),d=o.persistState===!1?null:o.storageAdapter??ic(),c={},u=null,y=!1,f=l=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:b,open:x}=g;return x&&(y=!0),b}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(g=>f(g??{messages:[],metadata:{}}));else{let b=f(l??{messages:[],metadata:{}});b.metadata&&(c=fc(b.metadata)),b.messages?.length&&(o={...o,initialMessages:b.messages}),b.artifacts?.length&&(o={...o,initialArtifacts:b.artifacts,initialSelectedArtifactId:b.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=f({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let h=()=>c,C=l=>{c=l({...c})??{},Fi()},E=o.actionParsers&&o.actionParsers.length?o.actionParsers:[pi],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pr.message,Pr.messageAndClick],R=ui({parsers:E,handlers:L,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});R.syncFromMetadata();let A=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,_=o.autoFocusInput??!1,O=I,w=A,z=o.layout?.header?.layout,q=!1,Q=()=>yo(o),D=()=>A||Q(),j=Q()?!1:A?I:!0,ge=!1,be=null,Ee=()=>{ge=!0,be&&clearTimeout(be),be=setTimeout(()=>{ge&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ge=!1)},1e4)},De=xf(o,R,Ee),ae=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,le=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},me=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,pe=Y?new Ns(me):null,Pe=o.features?.eventStream?.maxEvents??2e3,Oe=Y?new Os(Pe,pe):null,$e=Y?new Fs:null,He=null,je=!1,Je=null,Me=0;pe?.open().then(()=>Oe?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ne={onCopy:l=>{i.emit("message:copy",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),$?.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(l)}},Re=o.statusIndicator??{},xt=l=>l==="idle"?Re.idleText??Wt.idle:l==="connecting"?Re.connectingText??Wt.connecting:l==="connected"?Re.connectedText??Wt.connected:l==="error"?Re.errorText??Wt.error:l==="paused"?Re.pausedText??Wt.paused:l==="resuming"?Re.resumingText??Wt.resuming:Wt[l];function ht(l,g,b,x){if(x==="idle"&&b.idleLink){l.textContent="";let T=document.createElement("a");T.href=b.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=g,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=g}let ct=Fu({config:o,showClose:D()}),{wrapper:Ie,panel:he,pillRoot:Ye}=ct.shell,ke=ct.panelElements,{container:fe,body:ie,messagesWrapper:xe,suggestions:Ct,textarea:ye,sendButton:ue,sendButtonWrapper:gn,composerForm:X,statusText:M,introTitle:N,introSubtitle:v,closeButton:S,iconHolder:k,headerTitle:H,headerSubtitle:V,header:B,footer:U,actionsRow:oe,rightActions:Xe}=ke,Se=ke.leftActions,lt=ke.setSendButtonMode,K=ke.micButton,Ue=ke.micButtonWrapper,Te=ke.attachmentButton,We=ke.attachmentButtonWrapper,Le=ke.attachmentInput,et=ke.attachmentPreviewsContainer;fe.classList.add("persona-relative"),ie.classList.add("persona-relative");let xo=12,Co=()=>le.label??"",Ai=()=>le.iconName??"arrow-down",Us=()=>le.enabled!==!1,Xt=()=>Z.mode??"anchor-top",qn=()=>Xt()==="follow"||Xt()==="anchor-top"&&_r,Tc=()=>Z.anchorTopOffset??16,og=()=>Z.restorePosition??"bottom",Ec=()=>Z.pauseOnInteraction===!0,Mc=()=>Z.showActivityWhilePinned!==!1,kc=()=>Z.announce===!0,Rt=m("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Rt.type="button",Rt.style.display="none",Rt.setAttribute("data-persona-scroll-to-bottom","true");let Ir=m("span","persona-flex persona-items-center"),Si=m("span",""),wo=m("span","");wo.setAttribute("data-persona-scroll-to-bottom-count",""),wo.style.display="none",Rt.append(Ir,Si,wo),fe.appendChild(Rt);let Vn=m("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",ie.appendChild(Vn);let Ao=m("div","persona-sr-only");Ao.setAttribute("aria-live","polite"),Ao.setAttribute("aria-atomic","true"),Ao.setAttribute("role","status"),Ao.setAttribute("data-persona-live-region",""),Object.assign(Ao.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),fe.appendChild(Ao);let Wr=null,zs=null,Lc=l=>{!kc()||!l||(zs=l,Wr===null&&(Wr=setTimeout(()=>{Wr=null,zs&&kc()&&(Ao.textContent=zs),zs=null},400)))},Zo=()=>{let g=U.style.display==="none"?0:U.offsetHeight;Rt.style.bottom=`${g+xo}px`};Zo();let Pc=()=>{let l=!!Co();Rt.setAttribute("aria-label",Co()||"Jump to latest"),Rt.title=Co(),Rt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Ir.innerHTML="";let g=te(Ai(),"14px","currentColor",2);g?(Ir.appendChild(g),Ir.style.display=""):Ir.style.display="none",Si.textContent=Co(),Si.style.display=l?"":"none"};Pc();let Mt=null,Zt=null,Rc=null,Ic=s.find(l=>l.renderHeader);if(Ic?.renderHeader){let l=Ic.renderHeader({config:o,defaultRenderer:()=>{let g=bo({config:o,showClose:D()});return Tr(fe,g,o),g.header},onClose:()=>mt(!1,"user")});if(l){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),B=l,ct.header.element=l)}}let Ti=()=>{if(!Oe)return;if(je=!0,!He&&Oe&&(He=af({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Hr(),config:o,plugins:s,getThroughput:()=>$e?.getMetric()??{status:"idle"}})),He&&(ie.style.display="none",U.parentNode?.insertBefore(He.element,U),He.update()),at){at.style.boxShadow=`inset 0 0 0 1.5px ${Gt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(b=>b&&at.classList.add(b))}let l=()=>{if(!je)return;let g=Date.now();g-Me>=200&&(He?.update(),Me=g),Je=requestAnimationFrame(l)};Me=0,Je=requestAnimationFrame(l),tn(),i.emit("eventStream:opened",{timestamp:Date.now()})},Hr=()=>{if(je){if(je=!1,He&&He.element.remove(),ie.style.display="",at){at.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&at.classList.remove(g))}Je!==null&&(cancelAnimationFrame(Je),Je=null),tn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},at=null;if(Y){let l=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");at=m("button",g),at.style.width="28px",at.style.height="28px",at.style.color=Gt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let b=te("activity","18px","currentColor",1.5);b&&at.appendChild(b);let x=ke.clearChatButtonWrapper,T=ke.closeButtonWrapper,P=x||T;P&&P.parentNode===B?B.insertBefore(at,P):B.appendChild(at),at.addEventListener("click",()=>{je?Hr():Ti()})}let rg=l=>{let g=o.attachments;if(!g?.enabled)return;let b=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!b){b=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.setAttribute("data-persona-composer-attachment-previews",""),b.style.display="none";let T=l.querySelector("[data-persona-composer-form]");T?.parentNode?T.parentNode.insertBefore(b,T):l.insertBefore(b,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let T=m("input");T.type="file",T.setAttribute("data-persona-composer-attachment-input",""),T.accept=(g.allowedTypes??Un).join(","),T.multiple=(g.maxFiles??4)>1,T.style.display="none",T.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(T)}},Wc=s.find(l=>l.renderComposer);if(Wc?.renderComposer){let l=o.composer,g=Wc.renderComposer({config:o,defaultRenderer:()=>Bs({config:o}).footer,onSubmit:b=>{if(!$||$.isStreaming())return;let x=b.trim(),T=Mt?.hasAttachments()??!1;if(!x&&!T)return;ld();let P;T&&(P=[],P.push(...Mt.getContentParts()),x&&P.push(Uo(x))),$.sendMessage(x,{contentParts:P}),T&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Le?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:b=>{o.composer={...o.composer,selectedModelId:b},o.agent&&(o.agent={...o.agent,model:b})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Rc?.()}:void 0});g&&(ct.replaceComposer(g),U=ct.composer.footer)}let sg=l=>{let g=(...ce)=>{for(let se of ce){let we=l.querySelector(se);if(we)return we}return null},b=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),P=l.querySelector("[data-persona-composer-mic]"),J=l.querySelector("[data-persona-composer-status]");b&&(X=b),x&&(ye=x),T&&(ue=T),P&&(K=P,Ue=P.parentElement),J&&(M=J);let F=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Ct=F);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(Te=G,We=G.parentElement),Le=g("[data-persona-composer-attachment-input]",'input[type="file"]'),et=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(oe=re),Se=g(".persona-widget-composer__left-actions")};rg(U),sg(U);let Kn=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Kn&&(xe.style.maxWidth=Kn,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%"),Kn&&X&&!Q()&&(X.style.maxWidth=Kn,X.style.marginLeft="auto",X.style.marginRight="auto"),Kn&&Ct&&!Q()&&(Ct.style.maxWidth=Kn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Kn&&et&&!Q()&&(et.style.maxWidth=Kn,et.style.marginLeft="auto",et.style.marginRight="auto"),o.attachments?.enabled&&Le&&et){Mt=vr.fromConfig(o.attachments),Mt.setPreviewsContainer(et),Le.addEventListener("change",b=>{let x=b.target;Mt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,g=Cf(l);fe.appendChild(g)}let ag=()=>Zt?.prefetch();if(o.contextMentions?.enabled&&ye&&(Zt=Vp({config:o,textarea:ye,anchor:X??ye,getMessages:()=>$.getMessages(),liveRegionHost:fe}),Zt)){let l=ye;l.parentElement?.insertBefore(Zt.contextRow,l);let g=Zt.affordanceButtons;for(let b=g.length-1;b>=0;b--){let x=g[b];Se?Se.insertBefore(x,Se.firstChild):X?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return xe;case"footer-top":return Ct;case"composer":return X;case"footer-bottom":return M;default:return null}},b=(x,T)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")B.insertBefore(T,B.firstChild);else if(x==="header-right")B.appendChild(T);else{let P=B.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(T,P.nextSibling):B.appendChild(T)}break;case"body-top":{let P=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");P?P.replaceWith(T):ie.insertBefore(T,ie.firstChild);break}case"body-bottom":ie.appendChild(T);break;case"footer-top":Ct.replaceWith(T);break;case"footer-bottom":M.replaceWith(T);break;default:break}};for(let[x,T]of Object.entries(l))if(T)try{let P=T({config:o,defaultContent:()=>g(x)});P&&b(x,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,P)}})();let Hc=l=>{let b=l.target.closest('button[data-expand-header="true"]');if(!b)return;let x=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let T=x.getAttribute("data-message-id");if(!T)return;let P=b.getAttribute("data-bubble-type");if(P==="reasoning")Mr.has(T)?Mr.delete(T):Mr.add(T),Vu(T,x);else if(P==="tool")kr.has(T)?kr.delete(T):kr.add(T),Ku(T,x,o);else if(P==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Xo.get(T)??F;Xo.set(T,!G),Qu(T,x,o)}Mo.delete(T)};xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Hc(l))}),xe.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Hc(l))}),xe.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let b=xe.getRootNode(),x=typeof b.getSelection=="function"?b.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let T=x.toString(),P=vu(T);!P||P===T||(g.setData("text/plain",P),l.preventDefault())});let Ei=new Map,Bc=null,Dc="idle",ig={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},lg=(l,g)=>{let{icon:b,label:x}=ig[g];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",g==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",g!=="idle"),l.classList.toggle("persona-message-action-loading",g==="loading");let T=te(b,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},Oc=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;lg(g,x&&x===Bc?Dc:"idle")})};xe.addEventListener("click",l=>{let b=l.target.closest(".persona-message-action-btn[data-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.closest("[data-actions-for]");if(!x)return;let T=x.getAttribute("data-actions-for");if(!T)return;let P=b.getAttribute("data-action");if(P==="copy"){let F=$.getMessages().find(G=>G.id===T);if(F&&ne.onCopy){let G=F.content||"";navigator.clipboard.writeText(G).then(()=>{b.classList.add("persona-message-action-success");let re=te("check",14,"currentColor",2);re&&(b.innerHTML="",b.appendChild(re)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ce=te("copy",14,"currentColor",2);ce&&(b.innerHTML="",b.appendChild(ce))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),ne.onCopy(F)}}else if(P==="read-aloud")$.toggleReadAloud(T);else if(P==="upvote"||P==="downvote"){let F=(Ei.get(T)??null)===P,G=P==="upvote"?"thumbs-up":"thumbs-down";if(F){Ei.delete(T),b.classList.remove("persona-message-action-active");let re=te(G,14,"currentColor",2);re&&(b.innerHTML="",b.appendChild(re))}else{let re=P==="upvote"?"downvote":"upvote",ce=x.querySelector(`[data-action="${re}"]`);if(ce){ce.classList.remove("persona-message-action-active");let it=te(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);it&&(ce.innerHTML="",ce.appendChild(it))}Ei.set(T,P),b.classList.add("persona-message-action-active");let se=te(G,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(se)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let Ge=$.getMessages().find(yt=>yt.id===T);Ge&&ne.onFeedback&&ne.onFeedback({type:P,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",l=>{let b=l.target.closest("button[data-approval-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.closest(".persona-approval-bubble");if(!x)return;let T=x.getAttribute("data-message-id");if(!T)return;let P=b.getAttribute("data-approval-action");if(!P)return;let J=P==="approve"?"approved":"denied",G=$.getMessages().find(ce=>ce.id===T);if(!G?.approval)return;let re=x.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?$.resolveWebMcpApproval(T,J):$.resolveApproval(G.approval,J)});let tt=null,Br=null,Dr=()=>{},Or="none",qs=null,mn={artifacts:[],selectedId:null},Hn=!1,hn=!1,Nr=!1,er=!1,Nc=()=>er||mn.artifacts.some(l=>Fo(o.features?.artifacts,l.artifactType)==="panel"),Vs=()=>mn.artifacts.length>0&&!Hn&&Nc(),ft={current:null},Mi=(l,g)=>{let b=$.getArtifactById(g),x=b?.markdown,T=b?.title||"artifact",P=b?.file,J=b?.artifactType??"markdown";if(!x){let re=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let se=$.getMessages().find(we=>we.id===re);if(se?.rawContent)try{let we=JSON.parse(se.rawContent);x=we?.props?.markdown,T=we?.props?.title||T,we?.props?.file&&typeof we.props.file=="object"&&(P=we.props.file),!b&&typeof we?.props?.artifactType=="string"&&(J=we.props.artifactType)}catch{}}}return{markdown:x,title:T,file:P,artifactType:J}};xe.addEventListener("click",l=>{let b=l.target.closest("[data-download-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:P,title:J,file:F}=Mi(b,x);if(!P)return;let{filename:G,mime:re,content:ce}=nu({title:J,markdown:P,file:F}),se=new Blob([ce],{type:re}),we=URL.createObjectURL(se),Ge=document.createElement("a");Ge.href=we,Ge.download=G,Ge.click(),URL.revokeObjectURL(we)}),xe.addEventListener("click",l=>{let b=l.target.closest("[data-artifact-custom-action]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-artifact-custom-action");if(!x)return;let T=b.closest("[data-artifact-inline]"),P=T?null:b.closest("[data-open-artifact]"),J=T?T.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,G=(T?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(yt=>yt.id===x);if(!G)return;let{markdown:re,title:ce,file:se,artifactType:we}=Mi(b,J??""),Ge={artifactId:J,title:ce,artifactType:we,markdown:re,file:se};try{Promise.resolve(G.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",l=>{let b=l.target.closest("[data-copy-artifact]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-copy-artifact");if(!x)return;let T=$.getArtifactById(x),P="";if(T)P=Ms(T);else{let{markdown:J,file:F,artifactType:G}=Mi(b,x);G==="markdown"&&(P=Ms({id:x,artifactType:"markdown",status:"complete",markdown:J??"",...F?{file:F}:{}}))}P&&navigator.clipboard.writeText(P).then(()=>{let J=te("check",16,"currentColor",2);J&&(b.replaceChildren(J),setTimeout(()=>{let F=te("copy",16,"currentColor",2);F&&b.replaceChildren(F)},1500))}).catch(()=>{})}),xe.addEventListener("click",l=>{let b=l.target.closest("[data-expand-artifact-inline]");if(!b)return;l.preventDefault(),l.stopPropagation();let x=b.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Hn=!1,er=!0,hn=!0,Nr=!0,$.selectArtifact(x),Bn())}),xe.addEventListener("click",l=>{let g=l.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let b=g.closest("[data-open-artifact]");if(!b)return;let x=b.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),Hn=!1,er=!0,$.selectArtifact(x),Bn())}),xe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),g.click())});let tr=ke.composerOverlay,nr=(l,g,b)=>{let x=g.trim();if(!x||!ft.current)return;let T=l.getAttribute("data-tool-call-id")??"",P=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:x,answers:b.structured,values:b.values??(b.source==="multi"?x.split(", "):[x]),isFreeText:P,source:b.source},bubbles:!0,composed:!0})),$o(tr,T);let J=ft.current.getMessages().find(F=>F.toolCall?.id===T);J?.agentMetadata?.awaitingLocalTool?ft.current.resolveAskUserQuestion(J,b.structured??x):ft.current.sendMessage(x)},So=l=>{let g=ft.current;if(!g)return;let b=l.getAttribute("data-tool-call-id")??"",x=g.getMessages().find(T=>T.toolCall?.id===b);x&&g.persistAskUserQuestionProgress(x,{answers:xa(l,x),currentIndex:un(l)})},Fc=l=>Object.entries(l).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),ki=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=un(l),b=mr(l);if(g>=b-1)return;let x=ft.current?.getMessages().find(T=>T.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(Ca(l,x,o,g+1),So(l))};tr.addEventListener("click",l=>{let b=l.target.closest("[data-ask-user-action]");if(!b)return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;let T=b.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let P=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),$o(tr,P);let J=ft.current?.getMessages().find(F=>F.toolCall?.id===P);J?.agentMetadata?.awaitingLocalTool&&(ft.current?.markAskUserQuestionResolved(J),ft.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(T==="pick"){let P=b.getAttribute("data-option-label");if(!P)return;let J=x.getAttribute("data-multi-select")==="true",F=so(x);if(F&&J){let G=_o(x)[un(x)],re=new Set(Array.isArray(G)?G:[]);re.has(P)?re.delete(P):re.add(P),ao(x,Array.from(re)),So(x);return}if(F){ao(x,P),So(x),ki(x);return}if(J){let G=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",G?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!G);let re=x.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=dl(x).length===0);return}nr(x,P,{source:"pick",values:[P]});return}if(T==="submit-multi"){let P=dl(x);if(P.length===0)return;nr(x,P.join(", "),{source:"multi",values:P});return}if(T==="open-free-text"){let P=x.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(T==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(T==="submit-free-text"){let J=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(so(x)){ao(x,J.trim()),So(x),ki(x);return}nr(x,J,{source:"free-text"});return}if(T==="next"||T==="back"){if(!ft.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=ft.current.getMessages().find(se=>se.toolCall?.id===P);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let se=_o(x)[un(x)];(typeof se!="string"||se!==G)&&ao(x,G)}let re=T==="next"?1:-1,ce=un(x)+re;Ca(x,J,o,ce),So(x);return}if(T==="submit-all"){if(!ft.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=ft.current.getMessages().find(se=>se.toolCall?.id===P);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&ao(x,G);let re=xa(x,J);ft.current.persistAskUserQuestionProgress(J,{answers:re,currentIndex:un(x)});let ce=Fc(re);nr(x,ce||"(submitted)",{source:"submit-all",structured:re});return}if(T==="skip"){if(!ft.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=ft.current.getMessages().find(we=>we.toolCall?.id===P);if(!J)return;let F=so(x),G=un(x),re=mr(x),ce=G>=re-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),$o(tr,P),J.agentMetadata?.awaitingLocalTool&&(ft.current.markAskUserQuestionResolved(J),ft.current.resolveAskUserQuestion(J,"(dismissed)"));return}ao(x,"");let se=x.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),ce){let we=xa(x,J),Ge=Fc(we);nr(x,Ge||"(skipped)",{source:"submit-all",structured:we});return}Ca(x,J,o,G+1),So(x);return}}),tr.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let b=l.target;if(!b.matches?.('[data-ask-free-text-input="true"]'))return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let T=b.value;if(T.trim()){if(so(x)){ao(x,T.trim()),So(x),ki(x);return}nr(x,T,{source:"free-text"})}});let _c=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let g=l.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let b=tr.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),P=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];P&&(l.preventDefault(),P.click())};document.addEventListener("keydown",_c);let Gn=null,wt=null,Fr=null,Ks=null,Li=()=>{},$c=!1,Gs="",Js="";function Pi(){Ks?.(),Ks=null}let jc=()=>{if(!Gn||!wt)return;let l=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,b=g.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||b){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let x=Gn.firstElementChild;if(!x||x===wt)return;let T=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${T}px`,wt.style.zIndex="5";let P=oc(Gn,g),J=x.offsetWidth+P/2-T/2;wt.style.left=`${Math.max(0,J)}px`},Xs=()=>{},cg=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>b?!1:A||Ht(o)},Qs=()=>!Jt(o)||!Vs()||e.classList.contains("persona-artifact-narrow-host")||cg()||(e.ownerDocument.defaultView??window).innerWidth<iC?"none":nc(o)?"detached":"welded",Bn=()=>{if(!tt||!Jt(o))return;_s(e,o),$s(e,o),Xs();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=he.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let b=Vs();tt.setVisible(b),tt.update(mn),Hn?(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),tt.backdrop?.classList.add("persona-hidden"),hn=!1,Nr=!1):mn.artifacts.length>0&&Nc()?(tt.element.classList.remove("persona-hidden"),tt.setMobileOpen(!0)):(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),tt.backdrop?.classList.add("persona-hidden"),hn=!1,Nr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(tt.setExpandToggleVisible(x),tt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),tt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),tt.setTabFade(o.features?.artifacts?.layout?.tabFade),tt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Nr&&(hn=!1),hn!==$c){let P=tt.element;hn?(Gs=P.style.width,Js=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(Gs&&(P.style.width=Gs),Js&&(P.style.maxWidth=Js),Gs="",Js=""),$c=hn}e.classList.toggle("persona-artifact-expanded",hn),tt.setExpanded(hn);let T=Qs();T!==Or&&(Or=T,Dr()),Li()};if(Jt(o)){he.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(fe),tt=lf(o,{onSelect:b=>ft.current?.selectArtifact(b),onDismiss:()=>{Hn=!0,Bn()},onToggleExpand:()=>{let b=!hn,x=mn.selectedId??mn.artifacts[mn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:b})!==!0&&(hn=b,b||(Nr=!1),Bn())}}),tt.element.classList.add("persona-hidden"),Gn=g,g.appendChild(l),g.appendChild(tt.element),tt.backdrop&&he.appendChild(tt.backdrop),he.appendChild(g),Li=()=>{if(!Gn||!tt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Fr?.(),Fr=null,Pi(),wt&&(wt.remove(),wt=null),tt.element.style.removeProperty("width"),tt.element.style.removeProperty("maxWidth");return}if(!wt){let x=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let T=e.ownerDocument,P=T.defaultView??window,J=F=>{if(!tt||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||P.innerWidth<=640)return;F.preventDefault(),Pi();let G=F.clientX,re=tt.element.getBoundingClientRect().width,ce=o.features?.artifacts?.layout,se=Ge=>{let yt=Gn.getBoundingClientRect().width,it=e.classList.contains("persona-artifact-welded-split"),qt=oc(Gn,P),Bt=it?0:x.getBoundingClientRect().width||6,W=re-(Ge.clientX-G),Fe=uf(W,yt,qt,Bt,ce?.resizableMinWidth,ce?.resizableMaxWidth);tt.element.style.width=`${Fe}px`,tt.element.style.maxWidth="none",jc()},we=()=>{T.removeEventListener("pointermove",se),T.removeEventListener("pointerup",we),T.removeEventListener("pointercancel",we),Ks=null;try{x.releasePointerCapture(F.pointerId)}catch{}};Ks=we,T.addEventListener("pointermove",se),T.addEventListener("pointerup",we),T.addEventListener("pointercancel",we);try{x.setPointerCapture(F.pointerId)}catch{}};x.addEventListener("pointerdown",J),wt=x,Gn.insertBefore(x,tt.element),Fr=()=>{x.removeEventListener("pointerdown",J)}}if(wt){let x=Vs();wt.classList.toggle("persona-hidden",!x),jc()}},Xs=()=>{if(!A||!tt||(o.launcher?.sidebarMode??!1)||Ht(o)&&sn(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(T&&x.innerWidth<=P||!pf(o,A))return;let J=o.launcher?.width??o.launcherWidth??fn,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Vs()?(he.style.width=F,he.style.maxWidth=F):(he.style.width=J,he.style.maxWidth=J)},typeof ResizeObserver<"u"&&(Br=new ResizeObserver(()=>{Bn()}),Br.observe(he))}else he.appendChild(fe);Q()&&Ye&&(ke.peekBanner&&Ye.appendChild(ke.peekBanner),Ye.appendChild(U)),e.appendChild(Ie),Ye&&e.appendChild(Ye);let Ys=()=>{if(Q()){he.style.width="100%",he.style.maxWidth="100%";let Pt=o.launcher?.composerBar??{},Qt=Ie.dataset.state==="expanded",pa=Pt.expandedSize??"anchored";if(!(Qt&&pa!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let Zr=o.theme?.components?.panel,ua=Ko(o),dr=(Fn,Bo)=>Fn==null||Fn===""?Bo:Kt(ua,Fn)??Fn,es="1px solid var(--persona-border)",tl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ho="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=dr(Zr?.border,es),fe.style.borderRadius=dr(Zr?.borderRadius,Ho),fe.style.boxShadow=dr(Zr?.shadow,tl),fe.style.overflow="hidden";return}let l=Ht(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,T=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,J=Ko(o),F=(Pt,Qt)=>Pt==null||Pt===""?Qt:Kt(J,Pt)??Pt,G=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,ce=o.launcher?.mobileBreakpoint??640,se=G.innerWidth<=ce,we=re&&se&&A,Ge=l&&re&&se,yt=o.launcher?.position??"bottom-left",it=yt==="bottom-left"||yt==="top-left",qt=o.launcher?.zIndex??Ut,Bt="var(--persona-panel-border, 1px solid var(--persona-border))",W="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Fe="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ae=T&&!we&&!Ge;Ae?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let _e=Ae?Bt:g||we?"none":Bt,Et=Ae?W:we?"none":g?it?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":x?"none":W;l&&!we&&!Ae&&(Et="none",_e="none");let dt=Ae?Fe:g||we?"0":Fe,St=F(P?.border,_e),vt=F(P?.shadow,Et),$t=F(P?.borderRadius,dt),Io=Qs(),pt=Io==="detached",de=Io==="welded";e.classList.toggle("persona-artifact-detached-split",pt),e.classList.toggle("persona-artifact-welded-split",de);let Tt="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",rt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&nc(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",rt);let qe=pt||rt?"none":vt,nt=pt?Bt:de?"none":St,Lt=pt?Fe:$t;rt&&(nt="none",Lt="0");let Be=P?.borderRadius!=null&&P.borderRadius!=="",ot=rt&&!Be?"0":$t,nn=ie.scrollTop;e.style.cssText="",Ie.style.cssText="",he.style.cssText="",fe.style.cssText="",ie.style.cssText="",U.style.cssText="",je&&(ie.style.display="none");let Wo=()=>{if(nn<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===nn)return;let Qt=ie.scrollHeight-ie.clientHeight;Qt<=0||(ie.scrollTop=Math.min(nn,Qt))})};if(we){Ie.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ie.style.cssText=`
49
49
  position: fixed !important;
50
50
  inset: 0 !important;
51
51
  width: 100% !important;
@@ -81,11 +81,11 @@ _Details: ${n.message}_`:o}var bs=e=>({isError:!0,content:[{type:"text",text:e}]
81
81
  overflow: hidden !important;
82
82
  border-radius: 0 !important;
83
83
  border: none !important;
84
- `,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",z.style.flexShrink="0",q=!0,Wo();return}let da=o?.launcher?.width??o?.launcherWidth??gn;if(!g&&!l)v&&b?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=da,he.style.maxWidth=da);else if(l)if(an(o).reveal==="emerge"&&!S){let Yt=an(o).width;he.style.width=Yt,he.style.maxWidth=Yt}else he.style.width="100%",he.style.maxWidth="100%";if(Xs(),he.style.boxShadow=Ve,he.style.borderRadius=et,ut?he.style.border="none":pe&&(he.style.border=St),fe.style.border=Ze,fe.style.borderRadius=Pt,fe.style.boxShadow=ut&&!st?Tt:"",st&&(fe.style.background="transparent",le.style.background="transparent",z.style.background="transparent",z.style.borderTop="none"),pe){let Rt=o.features?.artifacts?.layout;qs=Rt?.unifiedSplitOuterRadius?.trim()||Rt?.paneBorderRadius?.trim()||$t}else qs=null;if(l&&!Ce&&!Ae&&!ut&&!pe&&P?.border===void 0&&(fe.style.border="none",an(o).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.style.borderRight="1px solid var(--persona-border)"),l&&!Ce&&pe&&P?.border===void 0&&(an(o).side==="right"?he.style.borderLeft="1px solid var(--persona-border)":he.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",v&&(Me.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",ut||(he.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",z.style.flexShrink="0"),v&&(Ae||ut||st)&&!l&&(st||(Me.style.padding="var(--persona-panel-inset)"),Me.style.background="var(--persona-panel-canvas-bg)"),Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!v&&!l&&(An[bt]??An["bottom-right"]).split(" ").forEach(Yt=>Me.classList.add(Yt)),g){let Rt=o.launcher?.sidebarWidth??"420px";S?Me.style.cssText=`
84
+ `,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",U.style.flexShrink="0",q=!0,Wo();return}let da=o?.launcher?.width??o?.launcherWidth??fn;if(!g&&!l)x&&b?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=da,he.style.maxWidth=da);else if(l)if(sn(o).reveal==="emerge"&&!T){let Qt=sn(o).width;he.style.width=Qt,he.style.maxWidth=Qt}else he.style.width="100%",he.style.maxWidth="100%";if(Xs(),he.style.boxShadow=qe,he.style.borderRadius=ot,pt?he.style.border="none":de&&(he.style.border=St),fe.style.border=nt,fe.style.borderRadius=Lt,fe.style.boxShadow=pt&&!rt?Tt:"",rt&&(fe.style.background="transparent",ie.style.background="transparent",U.style.background="transparent",U.style.borderTop="none"),de){let Pt=o.features?.artifacts?.layout;qs=Pt?.unifiedSplitOuterRadius?.trim()||Pt?.paneBorderRadius?.trim()||$t}else qs=null;if(l&&!we&&!Ae&&!pt&&!de&&P?.border===void 0&&(fe.style.border="none",sn(o).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.style.borderRight="1px solid var(--persona-border)"),l&&!we&&de&&P?.border===void 0&&(sn(o).side==="right"?he.style.borderLeft="1px solid var(--persona-border)":he.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),Ie.style.display="flex",Ie.style.flexDirection="column",Ie.style.flex="1 1 0%",Ie.style.minHeight="0",Ie.style.maxHeight="100%",Ie.style.height="100%",x&&(Ie.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",pt||(he.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",U.style.flexShrink="0"),x&&(Ae||pt||rt)&&!l&&(rt||(Ie.style.padding="var(--persona-panel-inset)"),Ie.style.background="var(--persona-panel-canvas-bg)"),Ie.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!x&&!l&&(An[yt]??An["bottom-right"]).split(" ").forEach(Qt=>Ie.classList.add(Qt)),g){let Pt=o.launcher?.sidebarWidth??"420px";T?Ie.style.cssText=`
85
85
  position: fixed !important;
86
86
  top: var(--persona-panel-inset) !important;
87
87
  bottom: var(--persona-panel-inset) !important;
88
- width: ${Rt} !important;
88
+ width: ${Pt} !important;
89
89
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
90
90
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
91
91
  margin: 0 !important;
@@ -94,11 +94,11 @@ _Details: ${n.message}_`:o}var bs=e=>({isError:!0,content:[{type:"text",text:e}]
94
94
  flex-direction: column !important;
95
95
  z-index: ${qt} !important;
96
96
  ${it?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
97
- `:Me.style.cssText=`
97
+ `:Ie.style.cssText=`
98
98
  position: fixed !important;
99
99
  top: 0 !important;
100
100
  bottom: 0 !important;
101
- width: ${Rt} !important;
101
+ width: ${Pt} !important;
102
102
  height: 100vh !important;
103
103
  max-height: 100vh !important;
104
104
  margin: 0 !important;
@@ -118,9 +118,9 @@ _Details: ${n.message}_`:o}var bs=e=>({isError:!0,content:[{type:"text",text:e}]
118
118
  min-height: 0 !important;
119
119
  margin: 0 !important;
120
120
  padding: 0 !important;
121
- box-shadow: ${Ve} !important;
122
- border-radius: ${et} !important;
123
- ${ut?"border: none !important;":pe?`border: ${St} !important;`:""}
121
+ box-shadow: ${qe} !important;
122
+ border-radius: ${ot} !important;
123
+ ${pt?"border: none !important;":de?`border: ${St} !important;`:""}
124
124
  `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),fe.style.cssText=`
125
125
  display: flex !important;
126
126
  flex-direction: column !important;
@@ -130,32 +130,32 @@ _Details: ${n.message}_`:o}var bs=e=>({isError:!0,content:[{type:"text",text:e}]
130
130
  min-height: 0 !important;
131
131
  max-height: 100% !important;
132
132
  overflow: hidden !important;
133
- border-radius: ${Pt} !important;
134
- border: ${Ze} !important;
135
- ${ut&&!st?`box-shadow: ${Tt} !important;`:""}
136
- ${st?"background: transparent !important;":""}
137
- `,z.style.cssText=`
133
+ border-radius: ${Lt} !important;
134
+ border: ${nt} !important;
135
+ ${pt&&!rt?`box-shadow: ${Tt} !important;`:""}
136
+ ${rt?"background: transparent !important;":""}
137
+ `,U.style.cssText=`
138
138
  flex-shrink: 0 !important;
139
139
  border-top: none !important;
140
140
  padding: 8px 16px 12px 16px !important;
141
- ${st?"background: transparent !important;":""}
142
- `}if(!v&&!l){let Rt="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",pa=g?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Me.style.cssText+=Rt+Yt+pa}Wo()};Ys(),xr(e,o),_s(e,o),$s(e,o),Dr=()=>{Ys(),xr(e,o),_s(e,o),$s(e,o),qs?e.style.setProperty("--persona-artifact-welded-outer-radius",qs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ke=[];Ke.push(()=>{document.removeEventListener("keydown",Fc)}),Ke.push(()=>{Wr!==null&&clearTimeout(Wr)});let Sn=null,Tn=null;Ke.push(()=>{Sn?.(),Sn=null,Tn?.(),Tn=null}),Br&&Ke.push(()=>{Br?.disconnect(),Br=null}),Ke.push(()=>{Fr?.(),Fr=null,ki(),wt&&(wt.remove(),wt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),Y&&Ke.push(()=>{Le!==null&&(cancelAnimationFrame(Le),Le=null),Ne?.destroy(),Ne=null,Oe?.destroy(),Oe=null,ue=null});let To=null,jc=()=>{To&&(To(),To=null),o.colorScheme==="auto"&&(To=As(()=>{xr(e,o)}))};jc(),Ke.push(()=>{To&&(To(),To=null)}),Ke.push(a);let Zs=o.features?.streamAnimation;if(Zs?.type&&Zs.type!=="none"){let l=Sr(Zs.type,Zs.plugins);l&&(Xa(l,e),Ke.push(()=>Pu(e)))}let ea=tf(Ct),Eo=null,$,Li=l=>{if(!$)return;let g=l??$.getMessages(),b=o.features?.suggestReplies?.enabled!==!1?pl(g):null;b?ea.render(b,$,N,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(v=>v.role==="user")?ea.render([],$,N,g):ea.render(o.suggestionChips,$,N,g,o.suggestionChipsConfig)},yn=!1,Mo=Cu(),or=new Map,ko=new Map,Jn=new Map,Pi=0,ig=_n()!==null,tn=za(),cn=0,Xn=null,dn=!1,ta=!1,Qn=0,bn=null,Lo=null,Ri=!1,na=!1,Ii=null,_r=!0,Wi=!1,Hi=null,lg=4,oa=24,cg=80,Bi=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Uc=o.voiceRecognition?.autoResume??!1,Dn=l=>{i.emit("voice:state",{active:Xe.active,source:l,timestamp:Date.now()})},vn=()=>{C(l=>({...l,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},dg=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=uc(c.voiceState),g=!!l.active,b=Number(l.timestamp??0);Xe.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-b<nC&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Dn("restore"),$.isVoiceActive()&&lr()}):aa("restore"))},1e3)},pg=()=>$?hf($.getMessages()).filter(l=>!l.__skipPersist):[],ra=null,zc=(l,g)=>{typeof console<"u"&&console.error(l,g)},Di=(l,g)=>{let b=()=>{try{let X=l();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(F=>{zc(g,F)})}catch(X){return zc(g,X),null}},v=ra,S=v?v.then(()=>b()??void 0):b();if(!S)return;let P=S.finally(()=>{ra===P&&(ra=null)});ra=P};function Oi(l){if(!d?.save)return;let b={messages:l?hf(l):$?pg():[],metadata:c,artifacts:mn.artifacts,selectedArtifactId:mn.selectedId};Di(()=>d.save(b),"[AgentWidget] Failed to persist state:")}let rr=null,qc=()=>Me.querySelector("#persona-scroll-container")||le,$r=()=>{rr!==null&&(cancelAnimationFrame(rr),rr=null),dn=!1},Vc=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),ta=!1,$r()},ug=()=>yn&&Fi()&&(Qt()!=="anchor-top"||Ec()),Ni=()=>{let l=Co()||"Jump to latest",g=ug();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Qn>0?(wo.textContent=String(Qn),wo.style.display="",It.setAttribute("aria-label",`${l} (${Qn} new)`)):(wo.textContent="",wo.style.display="none",It.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},Kc=()=>{Qn!==0&&(Qn=0,Ni())},Fi=()=>qn()?!tn.isFollowing():!mo(le,oa),nn=()=>{if(!Us()||we){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==fe&&fe.appendChild(It),Zo();let g=In(le)>0&&Fi();g?Ni():Kc(),It.style.display=g?"":"none"},jr=()=>{tn.pause()&&(Vc(),nn())},Yn=()=>{tn.resume(),Kc(),nn()},Zn=(l=!1)=>{qn()&&tn.isFollowing()&&(!l&&!yn||(Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),ta=!0,Xn=requestAnimationFrame(()=>{Xn=null,ta=!1,tn.isFollowing()&&fg(qc(),l?220:140)})))},Gc=(l,g,b,v=()=>!0)=>{let S=l.scrollTop,P=g(),X=P-S;if($r(),Math.abs(X)<1){dn=!0,l.scrollTop=P,cn=l.scrollTop,dn=!1;return}let F=performance.now();dn=!0;let K=de=>1-Math.pow(1-de,3),oe=de=>{if(!v()){$r();return}let re=g();re!==P&&(P=re,X=P-S);let Ce=de-F,Ge=Math.min(Ce/b,1),bt=K(Ge),it=S+X*bt;l.scrollTop=it,cn=l.scrollTop,Ge<1?rr=requestAnimationFrame(oe):(l.scrollTop=P,cn=l.scrollTop,rr=null,dn=!1)};rr=requestAnimationFrame(oe)},fg=(l,g=500)=>{let b=In(l)-l.scrollTop;if(Math.abs(b)<1){cn=l.scrollTop;return}if(Math.abs(b)>=cg){$r(),dn=!0,l.scrollTop=In(l),cn=l.scrollTop,dn=!1;return}Gc(l,()=>In(l),g,()=>tn.isFollowing())},Jc=()=>{let l=qc();dn=!0,l.scrollTop=In(l),cn=l.scrollTop,dn=!1,nn()},Xc=l=>{let g=0,b=l;for(;b&&b!==le;)g+=b.offsetTop,b=b.offsetParent;return g},Qc=()=>{if(eg()!=="last-user-turn")return!1;let l=$?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(P=>P.role==="user");if(!g)return!1;let b=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=le.querySelector(`[data-message-id="${b}"]`);if(!v)return!1;let S=Math.min(Math.max(0,Xc(v)-Sc()),In(le));return dn=!0,le.scrollTop=S,cn=le.scrollTop,dn=!1,Qt()==="follow"&&!mo(le,oa)&&tn.pause(),nn(),!0},Yc=l=>{Vn.style.height=`${Math.max(0,Math.round(l))}px`,bn&&(bn.spacerHeight=Math.max(0,l))},Ur=()=>{Lo!==null&&(cancelAnimationFrame(Lo),Lo=null),$r(),bn=null,Vn.style.height="0px"},gg=l=>{Lo!==null&&cancelAnimationFrame(Lo),Lo=requestAnimationFrame(()=>{Lo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=le.querySelector(`[data-message-id="${g}"]`);if(!b)return;let v=Xc(b),S=bn?.spacerHeight??0,P=le.scrollHeight-S,{targetScrollTop:X,spacerHeight:F}=Eu({anchorOffsetTop:v,topOffset:Sc(),viewportHeight:le.clientHeight,contentHeight:P});bn={initialSpacerHeight:F,contentHeightAtAnchor:P,spacerHeight:F},Yc(F),Gc(le,()=>X,220)})},mg=()=>{if(qn()){if(!tn.isFollowing()||mo(le,1))return;Zn(!yn);return}if(bn&&bn.initialSpacerHeight>0){let l=le.scrollHeight-bn.spacerHeight,g=Mu({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:l});g!==bn.spacerHeight&&Yc(g)}nn()},hg=l=>{let g=Qt();g==="follow"?(Yn(),Zn(!0)):g==="anchor-top"&&(_r=!1,Wi=!0,gg(l))},yg=()=>{if(Qt()==="anchor-top"){if(Wi){_r=!1;return}_r=!0,Ur(),Yn(),Zn(!0)}},bg=l=>{let g=new Map;l.forEach(b=>{let v=Bi.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!v&&b.role==="assistant"&&(i.emit("assistant:message",b),!na&&(Qt()!=="anchor-top"||Ec())&&Fi()&&(Qn+=1,Ni(),nn(),kc(Qn===1?"1 new message below.":`${Qn} new messages below.`))),b.role==="assistant"&&v?.streaming&&b.streaming===!1&&i.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(v?b.approval.status!=="pending"&&i.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):i.emit("approval:requested",{approval:b.approval,message:b}))}),Bi.clear(),g.forEach((b,v)=>{Bi.set(v,b)})},vg=(l,g,b)=>{let v=document.createElement("div"),P=(()=>{let W=s.find($e=>$e.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(W,$e)=>$e==null?!1:typeof $e=="string"?(W.textContent=$e,!0):(W.appendChild($e),!0),F=new Set,K=new Set,oe=s.some(W=>W.renderAskUserQuestion),de=[],re=[],Ce=o.enableComponentStreaming!==!1,Ge=o.approval!==!1,bt=[];if(g.forEach(W=>{F.add(W.id);let $e=oe&&oo(W),Ae=Ge&&W.variant==="approval"&&!!W.approval,je=!$e&&W.role==="assistant"&&!W.variant&&Ce&&pi(W);!Ae&&Jn.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id)),!je&&ko.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),ko.delete(W.id));let Mt=oo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=xu(W,Pi)+Mt,St=$e||Ae||je?null:wu(Mo,W.id,pt);if(St){v.appendChild(St.cloneNode(!0)),oo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(K.add(W.toolCall.id),ds(W,o,Ie.composerOverlay));return}let vt=null,$t=s.find(pe=>!!(W.variant==="reasoning"&&pe.renderReasoning||W.variant==="tool"&&pe.renderToolCall||!W.variant&&pe.renderMessage)),Io=o.layout?.messages;if(oo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){or.delete(W.id),l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(wa(W)&&o.features?.suggestReplies?.enabled!==!1)return;if(oo(W)&&o.features?.askUserQuestion?.enabled!==!1){let pe=s.find(Tt=>typeof Tt.renderAskUserQuestion=="function");if(pe&&gt.current){let Tt=or.get(W.id),Vt=Tt!==pt,Ot=null;if(Vt){let{payload:Ze,complete:Pt}=ro(W),Be=W.id,et=()=>gt.current?.getMessages().find(on=>on.id===Be);Ot=pe.renderAskUserQuestion({message:W,payload:Ze,complete:Pt,resolve:on=>{let Wo=et();Wo&&gt.current?.resolveAskUserQuestion(Wo,on)},dismiss:()=>{let on=et();on?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(on),gt.current?.resolveAskUserQuestion(on,"(dismissed)"))},config:o})}let st=Tt!=null;if(Vt&&Ot===null&&!st){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(K.add(W.toolCall.id),ds(W,o,Ie.composerOverlay));return}let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${W.id}`,Ve.setAttribute("data-wrapper-id",W.id),Ve.setAttribute("data-ask-plugin-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),v.appendChild(Ve),de.push({messageId:W.id,fingerprint:pt,bubble:Ot});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(K.add(W.toolCall.id),ds(W,o,Ie.composerOverlay));return}}else if(Ae){let pe=s.find(st=>typeof st.renderApproval=="function")??r,Vt=Jn.get(W.id)!==pt,Ot=null;if(Vt&&pe?.renderApproval){let st=W.id,Ve=(Ze,Pt)=>{let Be=gt.current?.getMessages().find(et=>et.id===st);Be?.approval&&(Be.approval.toolType==="webmcp"?gt.current?.resolveWebMcpApproval(Be.id,Ze):gt.current?.resolveApproval(Be.approval,Ze,Pt))};Ot=pe.renderApproval({message:W,defaultRenderer:()=>ai(W,o),config:o,approve:Ze=>Ve("approved",Ze),deny:Ze=>Ve("denied",Ze)})}if(Vt&&Ot===null)l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id),vt=ai(W,o);else{let st=document.createElement("div");st.className="persona-flex",st.id=`wrapper-${W.id}`,st.setAttribute("data-wrapper-id",W.id),st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),v.appendChild(st),bt.push({messageId:W.id,fingerprint:pt,bubble:Ot});return}}else if($t)if(W.variant==="reasoning"&&W.reasoning&&$t.renderReasoning){if(!se)return;vt=$t.renderReasoning({message:W,defaultRenderer:()=>Kl(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&$t.renderToolCall){if(!be)return;vt=$t.renderToolCall({message:W,defaultRenderer:()=>Jl(W,o),config:o})}else $t.renderMessage&&(vt=$t.renderMessage({message:W,defaultRenderer:()=>{let pe=Ds(W,b,Io,o.messageActions,ie,{loadingIndicatorRenderer:P,widgetConfig:o});return W.role!=="user"&&oc(pe,W,o,$),pe},config:o}));if(!vt&&je){let pe=cc(W);if(pe){let Tt=ko.get(W.id),Vt=Tt!==pt,Ot=o.wrapComponentDirectiveInBubble!==!1&&Rn.getOptions(pe.component)?.bubbleChrome!==!1,st=null;if(Vt){let Ve=lc(pe,{config:o,message:W,transform:b});if(Ve&&pe.component==="PersonaArtifactInline"){let Ze=Ve.hasAttribute("data-artifact-inline")?Ve:Ve.querySelector("[data-artifact-inline]"),Pt=Ze?.getAttribute("data-artifact-inline")??"",Be=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Pt):Pt,et=Pt?l.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${Be}"]`)??null:null;Ze&&et&&et!==Ze&&mu(et)&&(Ze===Ve?Ve=et:Ze.replaceWith(et))}if(Ve)if(Ot){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${W.id}`,Ze.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Pt=document.createElement("div");Pt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Pt.innerHTML=b({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(Pt)}Ze.appendChild(Ve),st=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${W.id}`,Ze.setAttribute("data-message-id",W.id),Ze.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Pt=document.createElement("div");Pt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Pt.innerHTML=b({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(Pt)}Ze.appendChild(Ve),st=Ze}}if(st||Tt!=null){let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${W.id}`,Ve.setAttribute("data-wrapper-id",W.id),Ve.setAttribute("data-component-directive-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),Ot||Ve.classList.add("persona-w-full"),v.appendChild(Ve),re.push({messageId:W.id,fingerprint:pt,bubble:st});return}}}if(!vt)if(W.variant==="reasoning"&&W.reasoning){if(!se)return;vt=Kl(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!be)return;vt=Jl(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;vt=ai(W,o)}else{let pe=o.layout?.messages;pe?.renderUserMessage&&W.role==="user"?vt=pe.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):pe?.renderAssistantMessage&&W.role==="assistant"?vt=pe.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):vt=Ds(W,b,pe,o.messageActions,ie,{loadingIndicatorRenderer:P,widgetConfig:o}),W.role!=="user"&&vt&&oc(vt,W,o,$)}let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${W.id}`,ut.setAttribute("data-wrapper-id",W.id),W.role==="user"&&ut.classList.add("persona-justify-end"),vt?.getAttribute("data-persona-component-directive")==="true"&&ut.classList.add("persona-w-full"),ut.appendChild(vt),Au(Mo,W.id,pt,ut),v.appendChild(ut)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach($e=>{let Ae=$e.getAttribute("data-persona-ask-sheet-for");Ae&&!K.has(Ae)&&$o(Ie.composerOverlay,Ae)}),o.features?.toolCallDisplay?.grouped){let W=[],$e=[];g.forEach(Ae=>{if(Ae.variant==="tool"&&Ae.toolCall&&be){$e.push(Ae);return}Ae.variant==="reasoning"&&!se||($e.length>1&&W.push($e),$e=[])}),$e.length>1&&W.push($e),W.forEach((Ae,je)=>{let Mt=Ae.map(Tt=>Array.from(v.children).find(Vt=>Vt instanceof HTMLElement&&Vt.getAttribute("data-wrapper-id")===Tt.id)).filter(Tt=>!!Tt);if(Mt.length<2)return;let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-tool-group-${je}-${Ae[0].id}`,pt.setAttribute("data-wrapper-id",`tool-group-${je}-${Ae[0].id}`);let St=document.createElement("div");St.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",St.setAttribute("data-persona-tool-group","true");let vt=document.createElement("div");vt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let $t=`Called ${Ae.length} tools`,Io=o.toolCall?.renderGroupedSummary?.({messages:Ae,toolCalls:Ae.map(Tt=>Tt.toolCall).filter(Tt=>!!Tt),defaultSummary:$t,config:o});X(vt,Io)||(vt.textContent=$t);let ut=document.createElement("div");ut.className="persona-tool-group-stack persona-flex persona-flex-col";let pe=o.features?.toolCallDisplay?.groupedMode==="summary";St.appendChild(vt),pe||St.appendChild(ut),pt.appendChild(St),Mt[0].before(pt),Mt.forEach((Tt,Vt)=>{if(pe){Tt.remove();return}let Ot=document.createElement("div");Ot.className="persona-tool-group-item persona-relative",Ot.setAttribute("data-persona-tool-group-item","true"),Vt<Mt.length-1&&Ot.setAttribute("data-persona-tool-group-connector","true"),Ot.appendChild(Tt),ut.appendChild(Ot)})})}Su(Mo,F);let it=g.some(W=>W.role==="assistant"&&W.streaming),qt=g[g.length-1],Dt=qt?.role==="assistant"&&!qt.streaming&&qt.variant!=="approval";if(yn&&g.some(W=>W.role==="user")&&!it&&!Dt){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:Er},$e=s.find(je=>je.renderLoadingIndicator),Ae=null;if($e?.renderLoadingIndicator&&(Ae=$e.renderLoadingIndicator(W)),Ae===null&&o.loadingIndicator?.render&&(Ae=o.loadingIndicator.render(W)),Ae===null&&(Ae=Er()),Ae){let je=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;je.className=Mt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),je.setAttribute("data-typing-indicator","true"),je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",je.appendChild(Ae);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-typing-indicator",pt.setAttribute("data-wrapper-id","typing-indicator"),pt.appendChild(je),v.appendChild(pt)}}if(!yn&&g.length>0){let W=g[g.length-1],$e={config:o,lastMessage:W,messageCount:g.length},Ae=s.find(Mt=>Mt.renderIdleIndicator),je=null;if(Ae?.renderIdleIndicator&&(je=Ae.renderIdleIndicator($e)),je===null&&o.loadingIndicator?.renderIdle&&(je=o.loadingIndicator.renderIdle($e)),je){let Mt=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;Mt.className=pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(je);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-idle-indicator",St.setAttribute("data-wrapper-id","idle-indicator"),St.appendChild(Mt),v.appendChild(St)}}if(Ua(l,v),de.length>0)for(let{messageId:W,fingerprint:$e,bubble:Ae}of de){let je=l.querySelector(`#wrapper-${W}`);je&&Ae!==null&&(je.replaceChildren(Ae),je.setAttribute("data-bubble-fp",$e),or.set(W,$e))}if(or.size>0)for(let W of or.keys())F.has(W)||or.delete(W);if(re.length>0)for(let{messageId:W,fingerprint:$e,bubble:Ae}of re){let je=l.querySelector(`#wrapper-${W}`);je&&Ae!==null&&(je.replaceChildren(Ae),je.setAttribute("data-bubble-fp",$e),ko.set(W,$e))}if(ko.size>0)for(let W of ko.keys())F.has(W)||ko.delete(W);if(bt.length>0)for(let{messageId:W,fingerprint:$e,bubble:Ae}of bt){let je=l.querySelector(`#wrapper-${W}`);je&&Ae!==null&&(je.replaceChildren(Ae),je.setAttribute("data-bubble-fp",$e),Jn.set(W,$e))}if(Jn.size>0)for(let W of Jn.keys())F.has(W)||Jn.delete(W)},zr=(l,g,b)=>{vg(l,g,b),Dc()},qr=null,xg=()=>{if(qr)return;let l=b=>{let v=b.composedPath();v.includes(Me)||lt&&v.includes(lt)||ht(!1,"user")};qr=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},Zc=()=>{if(!qr)return;(e.ownerDocument??document).removeEventListener("pointerdown",qr,!0),qr=null};Ke.push(()=>Zc());let Vr=null,Cg=()=>{if(Vr)return;let l=b=>{b.key==="Escape"&&(b.isComposing||ht(!1,"user"))};Vr=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},ed=()=>{if(!Vr)return;(e.ownerDocument??document).removeEventListener("keydown",Vr,!0),Vr=null};Ke.push(()=>ed());let Kr=!1,td=new Set,wg=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},sr=()=>{if(!Q())return;let l=Ie.peekBanner,g=Ie.peekTextNode;if(!l||!g)return;if(j){l.classList.remove("persona-pill-peek--visible");return}let b=$?.getMessages()??[],v;for(let Dt=b.length-1;Dt>=0;Dt--){let W=b[Dt];if(W.role==="assistant"&&W.content){v=W;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let S=v.content,P=!!v.streaming,X=wg(),F=Ka(X),K=F.type!=="none"?Sr(F.type,X?.plugins):null,oe=K?.isAnimating?.(v)===!0,de=K!==null&&(P||oe);de&&K&&!td.has(K.name)&&(Xa(K,e),td.add(K.name));let re=de&&K?.containerClass?K.containerClass:null,Ce=g.dataset.personaPeekStreamClass??null;Ce&&Ce!==re&&(g.classList.remove(Ce),delete g.dataset.personaPeekStreamClass),re&&Ce!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),de?(g.style.setProperty("--persona-stream-step",`${F.speed}ms`),g.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ge=de?Ga(S,F.buffer,K,v,P):S;if(de&&F.placeholder==="skeleton"&&P&&(!Ge||!Ge.trim())){let Dt=document.createElement("div"),W=Rs();W.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(W),Ua(g,Dt)}else{let Dt=Math.max(0,Ge.length-100),W=Ge.length>100?Ge.slice(-100):Ge,$e=$n(W);if(!de||!K){let Ae=Ge.length>100?`\u2026${W}`:W;g.textContent!==Ae&&(g.textContent=Ae)}else{let Ae=$e;(K.wrap==="char"||K.wrap==="word")&&(Ae=Ps($e,K.wrap,`peek-${v.id}`,{skipTags:K.skipTags,startIndex:Dt}));let je=document.createElement("div");if(je.innerHTML=Ae,K.useCaret&&W.length>0){let Mt=Ja(),pt=je.querySelectorAll(".persona-stream-char, .persona-stream-word"),St=pt[pt.length-1];St?.parentNode?St.parentNode.insertBefore(Mt,St.nextSibling):je.appendChild(Mt)}Ua(g,je),K.onAfterRender?.({container:g,bubble:l,messageId:v.id,message:v,speed:F.speed,duration:F.duration})}}let qt=yn||Kr;l.classList.toggle("persona-pill-peek--visible",qt)};if(Q()){let l=Ie.peekBanner;if(l){let v=S=>{S.preventDefault(),S.stopPropagation(),ht(!0,"user")};l.addEventListener("pointerdown",v),Ke.push(()=>{l.removeEventListener("pointerdown",v)})}let g=()=>{Kr||(Kr=!0,sr())},b=()=>{Kr&&(Kr=!1,sr())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",b),Ke.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",b)}),lt&&(lt.addEventListener("pointerenter",g),lt.addEventListener("pointerleave",b),Ke.push(()=>{lt.removeEventListener("pointerenter",g),lt.removeEventListener("pointerleave",b)}))}let Ag=l=>{let g=o.launcher?.composerBar??{},b=g.expandedSize??"anchored",v=g.bottomOffset??"16px",S=g.collapsedMaxWidth,P=g.expandedMaxWidth??"880px",X=g.expandedTopOffset??"5vh",F=g.modalMaxWidth??"880px",K=g.modalMaxHeight??"min(90vh, 800px)",oe="calc(100vw - 32px)",de="var(--persona-pill-area-height, 80px)",re=Me.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",lt){let Ce=lt.style;Ce.bottom=v,Ce.width=S??""}if(l&&b!=="fullscreen"){if(b==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=F,re.maxWidth=oe,re.maxHeight=K,re.height=K;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${v} + ${de})`,re.top=X,re.width=P,re.maxWidth=oe}},Gr=()=>{if(!D())return;if(Q()){let oe=(o.launcher?.composerBar??{}).expandedSize??"anchored",de=j?"expanded":"collapsed";Me.dataset.state=de,Me.dataset.expandedSize=oe,lt&&(lt.dataset.state=de,lt.dataset.expandedSize=oe),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ag(j),fe.style.display=j?"flex":"none",Ys(),j?(xg(),Cg()):(Zc(),ed()),sr();return}let l=Bt(o),g=e.ownerDocument.defaultView??window,b=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,S=g.innerWidth<=b,P=v&&S&&A,X=an(o).reveal;j?(Me.style.removeProperty("display"),Me.style.display=l?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),_t?_t.element.style.display="none":zt&&(zt.style.display="none")):(l?l&&(X==="overlay"||X==="push")&&!P?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),_t?_t.element.style.display=l?"none":"":zt&&(zt.style.display=l?"none":""))},ht=(l,g="user")=>{if(!D()||j===l)return;let b=j;j=l,Gr();let v=(()=>{let P=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,K=o.launcher?.mobileBreakpoint??640,oe=X.innerWidth<=K,de=Bt(o)&&F&&oe,re=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||F&&oe&&A||de||re})();if(j&&v){if(!Sn){let P=e.getRootNode(),X=P instanceof ShadowRoot?P.host:e.closest(".persona-host");X&&(Sn=_l(X,o.launcher?.zIndex??Ut))}Tn||(Tn=$l(e.ownerDocument))}else j||(Sn?.(),Sn=null,Tn?.(),Tn=null);j&&(Qr(),Qc()||(Qt()==="follow"?Zn(!0):Jc()));let S={open:j,source:g,timestamp:Date.now()};j&&!b?i.emit("widget:opened",S):!j&&b&&i.emit("widget:closed",S),i.emit("widget:state",{open:j,launcherEnabled:A,voiceActive:Xe.active,streaming:$.isStreaming()})},_i=l=>{ct(l?"stop":"send"),V&&(V.disabled=l),ea.buttons.forEach(g=>{g.disabled=l}),z.dataset.personaComposerStreaming=l?"true":"false",z.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},$i=()=>{Xe.active||N&&N.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>$i(),200)});let nd=()=>{J.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",x.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",N.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=le.querySelector("[data-persona-intro-card]");if(l){let b=o.copy?.showWelcomeCard!==!1;l.style.display=b?"":"none",b?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(te.textContent=o.copy?.sendButtonLabel??"Send"),N.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',N.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{C(g=>({...g,sessionId:l}))}});let Po=null,Sg=()=>{Po==null&&(Po=setInterval(()=>{let l=ve.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Po),Po=null;return}let g=Date.now();l.forEach(b=>{let v=Number(b.getAttribute("data-tool-elapsed"));v&&(b.textContent=Sa(g-v))})},100))},ji=(l,g)=>{if(Object.is(l,g))return!0;if(l===null||g===null||typeof l!="object"||typeof g!="object")return!1;if(Array.isArray(l)||Array.isArray(g))return!Array.isArray(l)||!Array.isArray(g)||l.length!==g.length?!1:l.every((X,F)=>ji(X,g[F]));let b=l,v=g,S=Object.keys(b),P=Object.keys(v);return S.length===P.length&&S.every(X=>Object.prototype.hasOwnProperty.call(v,X)&&ji(b[X],v[X]))},od=l=>{let{content:g,rawContent:b,llmContent:v,...S}=l;return S},Ui=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!pi(l),Tg=(l,g,b)=>{if(l.length!==g.length)return!1;let v=l[b.index],S=g[b.index];return!v||!S||v.id!==b.id||S.id!==b.id?!1:(!Object.is(v.content,S.content)||!Object.is(v.rawContent,S.rawContent)||!Object.is(v.llmContent,S.llmContent))&&Ui(v)&&Ui(S)&&ji(od(v),od(S))},rd=null,ar=null,Ro=null,On=null,sa=l=>{rd=l;let g,b;ar=null;for(let S=l.length-1;S>=0;S-=1){let P=l[S];if(!g&&P.role==="user"&&(g=P),!b&&P.role==="assistant"&&(b=P),!ar&&Ui(P)&&(ar={index:S,id:P.id}),g&&b&&ar)break}zr(ve,l,De),Hl(ve,mn.artifacts,{suppressTransition:yn}),Sg(),Li(l),Zn(!yn),bg(l),l.length===0&&(Ur(),_r=!0,Wi=!1),!Ri||na?(Ri=!0,Ii=g?.id??null,Hi=b?.id??null):g&&g.id!==Ii?(Ii=g.id,hg(g.id)):b&&b.id!==Hi&&yg(),b&&(Hi=b.id);let v=Xe.lastUserMessageId;g&&g.id!==v&&(Xe.lastUserMessageId=g.id,i.emit("user:message",g)),Xe.lastUserMessageWasVoice=!!g?.viaVoice,Oi(l),sr()},zi=()=>{On!==null&&(cancelAnimationFrame(On),On=null);let l=Ro;Ro=null,l&&sa(l)},sd=()=>{On!==null&&cancelAnimationFrame(On),On=null,Ro=null},Eg=l=>{let g=Ro??rd;if(yn&&g&&ar&&Tg(g,l,ar)){Ro=l,On===null&&(On=requestAnimationFrame(()=>{On=null;let b=Ro;Ro=null,b&&sa(b)}));return}if(l.length===0){sd(),sa(l);return}zi(),sa(l)};$=new vs(o,{onMessagesChanged(l){Eg(l)},onStatusChanged(l){let g=o.statusIndicator??{};yt(M,(v=>v==="idle"?g.idleText??Ht.idle:v==="connecting"?g.connectingText??Ht.connecting:v==="connected"?g.connectedText??Ht.connected:v==="error"?g.errorText??Ht.error:v==="paused"?g.pausedText??Ht.paused:v==="resuming"?g.resumingText??Ht.resuming:Ht[v])(l),g,l)},onStreamingChanged(l){l||($?.getMessages().length===0?sd():zi()),yn=l,_i(l),$&&zr(ve,$.getMessages(),De),l||Zn(!0),nn(),kc(l?"Responding\u2026":"Response complete."),sr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Nn(),lr();break;case"processing":Nn(),Og();break;case"speaking":Nn(),Ng();break;default:l==="idle"&&$.isBargeInActive()?(Nn(),lr(),V?.setAttribute("aria-label","End voice session")):(Xe.active=!1,Nn(),Dn("system"),vn());break}},onArtifactsState(l){mn=l,l.artifacts.length===0&&(er=!1),Hl(ve,l.artifacts,{suppressTransition:yn}),Bn(),Oi()},onReconnect(l){let{executionId:g,lastEventId:b}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:g,after:b}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:g,after:b,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:g,after:b})}}),gt.current=$,Ke.push(()=>$.cancel());let qi=null;if($.onReadAloudChange((l,g)=>{Hc=l,Bc=g,Dc();let b=l??qi;l&&(qi=l);let v=b?$.getMessages().find(S=>S.id===b)??null:null;i.emit("message:read-aloud",{messageId:b,message:v,state:g,timestamp:Date.now()}),g==="idle"&&(qi=null)}),Ri=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&$.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Oe||o.onSSEEvent)&&$.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),Ue?.processEvent(l,g),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let ad=()=>{o.resume&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=uc(l.metadata),R.syncFromMetadata()),l.messages?.length){na=!0;try{$.hydrateMessages(l.messages)}finally{na=!1}}l.artifacts?.length&&$.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>ad()):ad();let id=()=>{!Q()||j||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ht(!0,"auto")},Mg=(l,g)=>l?g?{refs:[...l.refs,...g.refs],finalize:async()=>{let[b,v]=await Promise.allSettled([l.finalize(),g.finalize()]),S=[];return b.status==="fulfilled"?S.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),v.status==="fulfilled"?S.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),cC(S)}}:l:g,kg=()=>{let g=N.getInlineMessageFields?.();return g&&g.contentSegments.some(v=>v.kind==="mention")?g.contentSegments:void 0},Jr=!1,Lg=async l=>{let g=N.value.trim(),b=kt?.hasAttachments()??!1,v=g?await(en?.takeInlineCommand(g)??Promise.resolve(null)):null;if(v?.kind==="action"){N.value="",N.style.height="auto",Xr(),en?.clear();return}let S=en?.collectForSubmit()??null,P=v?.kind==="server"?v.mentions:null,X=Mg(S,P),F=v?.kind==="prompt"?v.sendText:g,K=!!S&&S.refs.length>0;if(!F&&!b&&!K&&!P)return;id();let oe;b&&(oe=[],oe.push(...kt.getContentParts()),F&&oe.push(Uo(F)));let de=v?.kind==="prompt"?void 0:kg();N.value="",N.style.height="auto",Xr(),$.sendMessage(F,{contentParts:oe,mentions:X??void 0,contentSegments:de,viaVoice:l?.viaVoice}),b&&kt.clearAttachments(),S&&en?.clear()},Vi=async l=>{if(!Jr){Jr=!0;try{await Lg(l)}finally{Jr=!1}}},ld=l=>{if(l.preventDefault(),$.isStreaming()){$.cancel(),Ue?.reset(),Ne?.update();return}Jr||Vi()},Pg=()=>o.features?.composerHistory!==!1,Ki={...Ol},Gi=!1,Xr=()=>{Ki={...Ol}},Rg=()=>$.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),Ig=l=>{if(!N)return;Gi=!0,N.value=l,N.dispatchEvent(new Event("input",{bubbles:!0})),Gi=!1;let g=N.value.length;N.setSelectionRange(g,g)},Wg=l=>{Gi||(l.isComposing||en?.handleInput(l.inputType??void 0),Xr())},Hg=l=>{if(N&&!(!l.isComposing&&en?.handleKeydown(l))){if(Pg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=N.selectionStart===0&&N.selectionEnd===0,b=vu({direction:l.key==="ArrowUp"?"up":"down",history:Rg(),currentValue:N.value,atStart:g,state:Ki});if(Ki=b.state,b.handled){l.preventDefault(),b.value!==void 0&&Ig(b.value);return}}if(l.key==="Enter"&&!l.shiftKey){if($.isStreaming()){l.preventDefault();return}if(Jr){l.preventDefault();return}Xr(),l.preventDefault(),te.click()}}},cd=l=>{l.key!=="Escape"||l.isComposing||$.isStreaming()&&l.composedPath().includes(fe)&&($.cancel(),Ue?.reset(),Ne?.update(),Xr(),l.preventDefault(),l.stopImmediatePropagation())},Bg=async l=>{if(o.attachments?.enabled!==!0||!kt)return;let g=sC(l.clipboardData);g.length!==0&&(l.preventDefault(),await kt.handleFiles(g))},pn=null,En=!1,ir=null,At=null,dd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,aa=(l="user")=>{if(En||$.isStreaming())return;let g=dd();if(!g)return;pn=new g;let v=(o.voiceRecognition??{}).pauseDuration??2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let S=N.value;pn.onresult=P=>{let X="",F="";for(let oe=0;oe<P.results.length;oe++){let de=P.results[oe],re=de[0].transcript;de.isFinal?X+=re+" ":F=re}let K=S+X+F;N.value=K,ir&&clearTimeout(ir),(X||F)&&(ir=window.setTimeout(()=>{N.value.trim()&&pn&&En&&(eo(),Vi({viaVoice:!0}))},v))},pn.onerror=P=>{P.error!=="no-speech"&&eo()},pn.onend=()=>{if(En){let P=N.value.trim();P&&P!==S.trim()&&Vi({viaVoice:!0}),eo()}};try{if(pn.start(),En=!0,Xe.active=!0,l!=="system"&&(Xe.manuallyDeactivated=!1),Dn(l),vn(),V){let P=o.voiceRecognition??{};At={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??o.sendButton?.size??"40")||24};let X=P.recordingBackgroundColor,F=P.recordingIconColor,K=P.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let oe=V.querySelector("svg");oe&&oe.setAttribute("stroke",F)}K&&(V.style.borderColor=K),V.setAttribute("aria-label","Stop voice recognition")}}catch{eo("system")}},eo=(l="user")=>{if(En){if(En=!1,ir&&(clearTimeout(ir),ir=null),pn){try{pn.stop()}catch{}pn=null}if(Xe.active=!1,Dn(l),vn(),V){if(V.classList.remove("persona-voice-recording"),At){V.style.backgroundColor=At.backgroundColor,V.style.color=At.color,V.style.borderColor=At.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",At.color||"currentColor"),At=null}V.setAttribute("aria-label","Start voice recognition")}}},Dg=(l,g)=>{let b=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=l?.provider?.type==="runtype",S=l?.provider?.type==="custom";if(!(b||v||S))return null;let X=m("div","persona-send-button-wrapper"),F=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let K=l?.iconName??"mic",oe=g?.size??"40px",de=l?.iconSize??oe,re=parseFloat(de)||24,Ce=l?.backgroundColor??g?.backgroundColor,Ge=l?.iconColor??g?.textColor;F.style.width=de,F.style.height=de,F.style.minWidth=de,F.style.minHeight=de,F.style.fontSize="18px",F.style.lineHeight="1",Ge?F.style.color=Ge:F.style.color="var(--persona-text, #111827)";let it=ne(K,re,Ge||"currentColor",1.5);it?F.appendChild(it):F.textContent="\u{1F3A4}",Ce?F.style.backgroundColor=Ce:F.style.backgroundColor="",l?.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l?.borderColor&&(F.style.borderColor=l.borderColor),l?.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l?.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),X.appendChild(F);let qt=l?.tooltipText??"Start voice recognition";if((l?.showTooltip??!1)&&qt){let W=m("div","persona-send-button-tooltip");W.textContent=qt,X.appendChild(W)}return{micButton:F,micButtonWrapper:X}},Ji=()=>{if(!V||At)return;let l=o.voiceRecognition??{};At={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Xi=(l,g)=>{if(!V)return;let b=V.querySelector("svg");b&&b.remove();let v=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=ne(l,v,g,1.5);S&&V.appendChild(S)},ia=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},lr=()=>{if(!V)return;Ji();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,b=l.recordingIconColor,v=l.recordingBorderColor;if(ia(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=b??"var(--persona-voice-recording-indicator, #ffffff)",b){let S=V.querySelector("svg");S&&S.setAttribute("stroke",b)}v&&(V.style.borderColor=v),V.setAttribute("aria-label","Stop voice recognition")},Og=()=>{if(!V)return;Ji();let l=o.voiceRecognition??{},g=$.getVoiceInterruptionMode(),b=l.processingIconName??"loader",v=l.processingIconColor??At?.color??"",S=l.processingBackgroundColor??At?.backgroundColor??"",P=l.processingBorderColor??At?.borderColor??"";ia(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=S,V.style.borderColor=P;let X=v||"currentColor";V.style.color=X,Xi(b,X),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},Ng=()=>{if(!V)return;Ji();let l=o.voiceRecognition??{},g=$.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",v=l.speakingIconName??b,S=l.speakingIconColor??(g==="barge-in"?l.recordingIconColor??At?.color??"":At?.color??""),P=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),X=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":At?.borderColor??"");ia(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=P,V.style.borderColor=X;let F=S||"currentColor";V.style.color=F,Xi(v,F);let K=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",K),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},Nn=()=>{V&&(ia(),At&&(V.style.backgroundColor=At.backgroundColor??"",V.style.color=At.color??"",V.style.borderColor=At.borderColor??"",Xi(At.iconName,At.color||"currentColor"),At=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},la=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=$.getVoiceStatus(),g=$.getVoiceInterruptionMode();if(g==="none"&&(l==="processing"||l==="speaking"))return;if(g==="cancel"&&(l==="processing"||l==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,vn(),Dn("user"),Nn()});return}$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Xe.manuallyDeactivated=!$.isVoiceActive(),vn(),Dn("user"),$.isVoiceActive()?lr():Nn()});return}if(En){let l=N.value.trim();Xe.manuallyDeactivated=!0,vn(),eo("user"),l&&(N.value="",N.style.height="auto",$.sendMessage(l))}else Xe.manuallyDeactivated=!1,vn(),aa("user")};Pc=la,V&&(V.addEventListener("click",la),Ke.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Nn()):eo("system"),V&&V.removeEventListener("click",la)}));let Fg=i.on("assistant:complete",()=>{Uc&&(Xe.active||Xe.manuallyDeactivated||Uc==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Dn("auto"),$.isVoiceActive()&&lr()}):aa("auto"))},600))});Ke.push(Fg);let _g=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Ke.push(_g);let pd=()=>{ht(!j,"user")},_t=null,zt=null;if(A&&!Q()){let{instance:l,element:g}=zl({config:o,plugins:s,onToggle:pd});_t=l,l||(zt=g)}_t?e.appendChild(_t.element):zt&&e.appendChild(zt),Gr(),Li(),nd(),_i($.isStreaming()),Qc()||(Qt()==="follow"?Zn(!0):Jc()),dg(),_&&(!A||Q()?setTimeout(()=>$i(),0):j&&setTimeout(()=>$i(),200));let Qr=()=>{if(Q()){Zo(),Gr();return}let l=Bt(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640,X=v.innerWidth<=P,F=S&&X&&A;try{if(F){Dr(),Or=Qs();return}let K=!1;q&&(q=!1,Dr(),K=!0);let oe=Qs();if(!K&&oe!==Or&&(Dr(),K=!0),Or=oe,K&&Mi(),!A&&!l){he.style.height="",he.style.width="";return}if(!g&&!l){let re=o?.launcher?.width??o?.launcherWidth??gn;he.style.width=re,he.style.maxWidth=re}if(Xs(),!b){let de=v.innerHeight,re=64,Ce=o.launcher?.heightOffset??0,Ge=Math.max(200,de-re),bt=Math.min(640,Ge),it=Math.max(200,bt-Ce);he.style.height=`${it}px`}}finally{if(Zo(),Gr(),j&&A){let oe=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),de=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,Ce=Bt(o)&&re&&oe,Ge=de||re&&oe&&A||Ce;if(Ge&&!Tn){let bt=e.getRootNode(),it=bt instanceof ShadowRoot?bt.host:e.closest(".persona-host");it&&!Sn&&(Sn=_l(it,o.launcher?.zIndex??Ut)),Tn=$l(e.ownerDocument)}else Ge||(Sn?.(),Sn=null,Tn?.(),Tn=null)}}};Qr();let ud=e.ownerDocument.defaultView??window;if(ud.addEventListener("resize",Qr),Ke.push(()=>ud.removeEventListener("resize",Qr)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Zo()});l.observe(z),Ke.push(()=>l.disconnect())}cn=le.scrollTop;let fd=In(le),$g=()=>{let l=le.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??le.ownerDocument.getSelection()},Qi=()=>Tu($g(),le),gd=()=>{let l=le.scrollTop,g=In(le),b=g<fd;if(fd=g,!qn()){cn=l,nn();return}let{action:v,nextLastScrollTop:S}=qa({following:tn.isFollowing(),currentScrollTop:l,lastScrollTop:cn,nearBottom:mo(le,oa),userScrollThreshold:lg,isAutoScrolling:dn||ta||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(cn=S,v==="resume"){Qi()||Yn();return}v==="pause"&&jr()};if(le.addEventListener("scroll",gd,{passive:!0}),Ke.push(()=>le.removeEventListener("scroll",gd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{mg()});l.observe(ve),l.observe(le),Ke.push(()=>l.disconnect())}let md=()=>{qn()&&tn.isFollowing()&&Qi()&&jr()},hd=le.ownerDocument;hd.addEventListener("selectionchange",md),Ke.push(()=>{hd.removeEventListener("selectionchange",md)});let jg=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),yd=l=>{Tc()&&qn()&&tn.isFollowing()&&jg.has(l.key)&&jr()},bd=l=>{if(!Tc()||!qn()||!tn.isFollowing())return;let g=l.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&jr()};le.addEventListener("keydown",yd),le.addEventListener("focusin",bd),Ke.push(()=>{le.removeEventListener("keydown",yd),le.removeEventListener("focusin",bd)});let vd=l=>{if(!qn())return;let g=Va({following:tn.isFollowing(),deltaY:l.deltaY,nearBottom:mo(le,oa),resumeWhenNearBottom:!0});g==="pause"?jr():g==="resume"&&!Qi()&&Yn()};le.addEventListener("wheel",vd,{passive:!0}),Ke.push(()=>le.removeEventListener("wheel",vd)),It.addEventListener("click",()=>{Ur(),le.scrollTop=le.scrollHeight,cn=le.scrollTop,Yn(),Zn(!0),nn()}),Ke.push(()=>It.remove()),Ke.push(()=>{Vc(),Ur()});let xd=()=>{T&&(Eo&&(T.removeEventListener("click",Eo),Eo=null),D()?(T.style.display="",Eo=()=>{ht(!1,"user")},T.addEventListener("click",Eo)):T.style.display="none")};xd(),(()=>{let{clearChatButton:l}=Ie;l&&l.addEventListener("click",()=>{$.clearMessages(),Mo.clear(),Yn(),$o(Ie.composerOverlay);try{localStorage.removeItem(Rr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Rr}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Rr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&Di(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},R.syncFromMetadata(),Oe?.clear(),Ue?.reset(),Ne?.update()})})(),Se&&Se.addEventListener("submit",ld);let Cd=[["keydown",Hg],["input",Wg],["paste",Bg],["focus",og]],wd=l=>{if(l)for(let[g,b]of Cd)l.addEventListener(g,b)},Ad=l=>{if(l)for(let[g,b]of Cd)l.removeEventListener(g,b)};wd(N),en?.onComposerSwap((l,g)=>{Ad(g),N=l,wd(l)});let Sd=e.ownerDocument??document;Sd.addEventListener("keydown",cd,!0);let Td="persona-attachment-drop-active",Yr=0,Yi=()=>{Yr=0,fe.classList.remove(Td)},cr=()=>o.attachments?.enabled===!0&&kt!==null,Ed=l=>{!ui(l.dataTransfer)||!cr()||(Yr++,Yr===1&&fe.classList.add(Td))},Md=l=>{!ui(l.dataTransfer)||!cr()||(Yr--,Yr<=0&&Yi())},kd=l=>{!ui(l.dataTransfer)||!cr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Ld=l=>{if(!ui(l.dataTransfer)||!cr())return;l.preventDefault(),l.stopPropagation(),Yi();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&kt.handleFiles(g)},to=!0;fe.addEventListener("dragenter",Ed,to),fe.addEventListener("dragleave",Md,to),e.addEventListener("dragover",kd,to),e.addEventListener("drop",Ld,to);let ca=e.ownerDocument,Pd=l=>{cr()&&l.preventDefault()},Rd=l=>{cr()&&l.preventDefault()};ca.addEventListener("dragover",Pd),ca.addEventListener("drop",Rd),Ke.push(()=>{Se&&Se.removeEventListener("submit",ld),Ad(N),Sd.removeEventListener("keydown",cd,!0),en?.destroy()}),Ke.push(()=>{fe.removeEventListener("dragenter",Ed,to),fe.removeEventListener("dragleave",Md,to),e.removeEventListener("dragover",kd,to),e.removeEventListener("drop",Ld,to),ca.removeEventListener("dragover",Pd),ca.removeEventListener("drop",Rd),Yi()}),Ke.push(()=>{$.cancel()}),_t?Ke.push(()=>{_t?.destroy()}):zt&&Ke.push(()=>{zt?.remove()});let Wt={update(l){let g=o.toolCall,b=o.messageActions,v=o.layout?.messages,S=o.colorScheme,P=o.loadingIndicator,X=o.iterationDisplay,F=o.features?.showReasoning,K=o.features?.showToolCalls,oe=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o={...o,...l},Ys(),xr(e,o),_s(e,o),$s(e,o),Bn(),o.colorScheme!==S&&jc();let Ce=li.getForInstance(o.plugins);s.length=0,s.push(...Ce),A=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,se=o.features?.showReasoning??!0,be=o.features?.showToolCalls??!0,ce=o.features?.scrollToBottom??{};let Ge=Qt();Z=o.features?.scrollBehavior??{},Ge!==Qt()&&(Ur(),Yn()),Lc(),nn();let bt=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!bt){if(Oe||(ue=new Ns(me),Oe=new Os(Pe,ue),Ue=Ue??new Fs,ue.open().then(()=>Oe?.restore()).catch(()=>{}),$.setSSEEventCallback((ee,nt)=>{o.onSSEEvent?.(ee,nt),Ue?.processEvent(ee,nt),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(nt)})})),!at&&B){let ee=o.features?.eventStream?.classNames,nt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");at=m("button",nt),at.style.width="28px",at.style.height="28px",at.style.color=Jt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let Et=ne("activity","18px","currentColor",1.5);Et&&at.appendChild(Et);let Je=Ie.clearChatButtonWrapper,dt=Ie.closeButtonWrapper,jt=Je||dt;jt&&jt.parentNode===B?B.insertBefore(at,jt):B.appendChild(at),at.addEventListener("click",()=>{we?Hr():Ai()})}}else!Y&&bt&&(Hr(),at&&(at.remove(),at=null),Oe?.clear(),ue?.destroy(),Oe=null,ue=null,Ue?.reset(),Ue=null);if(o.launcher?.enabled===!1&&_t&&(_t.destroy(),_t=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!_t&&!zt){let{instance:ee,element:nt}=zl({config:o,plugins:s,onToggle:pd});_t=ee,ee||(zt=nt),e.appendChild(nt)}_t&&_t.update(o),H&&o.launcher?.title!==void 0&&(H.textContent=o.launcher.title),G&&o.launcher?.subtitle!==void 0&&(G.textContent=o.launcher.subtitle);let it=o.layout?.header;if(it?.layout!==U&&B){let ee=it?Hs(o,it,{showClose:D(),onClose:()=>ht(!1,"user")}):bo({config:o,showClose:D(),onClose:()=>ht(!1,"user")});rt.replaceHeader(ee),B=rt.header.element,k=rt.header.iconHolder,H=rt.header.headerTitle,G=rt.header.headerSubtitle,T=rt.header.closeButton,U=it?.layout}else if(it&&(k&&(k.style.display=it.showIcon===!1?"none":""),H&&(H.style.display=it.showTitle===!1?"none":""),G&&(G.style.display=it.showSubtitle===!1?"none":""),T&&(T.style.display=it.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let ee=it.showClearChat;if(ee!==void 0){Ie.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:nt}=Ie;nt&&!nt.classList.contains("persona-absolute")&&(ee?nt.classList.remove("persona-ml-auto"):nt.classList.add("persona-ml-auto"))}}let Dt=o.layout?.showHeader!==!1;B&&(B.style.display=Dt?"":"none");let W=o.layout?.showFooter!==!1;z&&(z.style.display=W?"":"none"),Zo(),nn(),A!==w?A?ht(I,"auto"):(j=!0,Gr()):I!==O&&ht(I,"auto"),O=I,w=A,Qr(),xd();let je=JSON.stringify(l.toolCall)!==JSON.stringify(g),Mt=JSON.stringify(o.messageActions)!==JSON.stringify(b),pt=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),St=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,vt=o.iterationDisplay!==X,$t=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(K??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);(je||Mt||pt||St||vt||$t)&&$&&(Pi++,zr(ve,$.getMessages(),De));let ut=o.features?.streamAnimation?.type;if(ut!==re&&ut&&ut!=="none"){let ee=Sr(ut,o.features?.streamAnimation?.plugins);ee&&Xa(ee,e)}let pe=o.launcher??{},Tt=pe.headerIconHidden??!1,Vt=o.layout?.header?.showIcon,Ot=Tt||Vt===!1,st=pe.headerIconName,Ve=pe.headerIconSize??"48px";if(k){let ee=fe.querySelector(".persona-border-b-persona-divider"),nt=ee?.querySelector(".persona-flex-col");if(Ot)k.style.display="none",ee&&nt&&!ee.contains(nt)&&ee.insertBefore(nt,ee.firstChild);else{if(k.style.display="",k.style.height=Ve,k.style.width=Ve,ee&&nt&&(ee.contains(k)?k.nextSibling!==nt&&(k.remove(),ee.insertBefore(k,nt)):ee.insertBefore(k,nt)),st){let Je=parseFloat(Ve)||24,dt=ne(st,Je*.6,"currentColor",1);dt?k.replaceChildren(dt):k.textContent=pe.agentIconText??"\u{1F4AC}"}else if(pe.iconUrl){let Je=k.querySelector("img");if(Je)Je.src=pe.iconUrl,Je.style.height=Ve,Je.style.width=Ve;else{let dt=document.createElement("img");dt.src=pe.iconUrl,dt.alt="",dt.className="persona-rounded-xl persona-object-cover",dt.style.height=Ve,dt.style.width=Ve,k.replaceChildren(dt)}}else{let Je=k.querySelector("svg"),dt=k.querySelector("img");(Je||dt)&&k.replaceChildren(),k.textContent=pe.agentIconText??"\u{1F4AC}"}let Et=k.querySelector("img");Et&&(Et.style.height=Ve,Et.style.width=Ve)}}let Ze=o.layout?.header?.showTitle,Pt=o.layout?.header?.showSubtitle;if(H&&(H.style.display=Ze===!1?"none":""),G&&(G.style.display=Pt===!1?"none":""),T){o.layout?.header?.showCloseButton===!1?T.style.display="none":T.style.display="";let nt=pe.closeButtonSize??"32px",Et=pe.closeButtonPlacement??"inline";T.style.height=nt,T.style.width=nt;let{closeButtonWrapper:Je}=Ie,dt=Et==="top-right",jt=Je?.classList.contains("persona-absolute");if(Je&&dt!==jt)if(Je.remove(),dt)Je.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(Je);else{let qe=pe.clearChat?.placement??"inline",Ft=pe.clearChat?.enabled??!0;Je.className=Ft&&qe==="inline"?"":"persona-ml-auto";let Zt=fe.querySelector(".persona-border-b-persona-divider");Zt&&Zt.appendChild(Je)}if(T.style.color=pe.closeButtonColor||Jt.actionIconColor,pe.closeButtonBackgroundColor?(T.style.backgroundColor=pe.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let qe=pe.closeButtonBorderWidth||"0px",Ft=pe.closeButtonBorderColor||"transparent";T.style.border=`${qe} solid ${Ft}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");pe.closeButtonBorderRadius?(T.style.borderRadius=pe.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(T.style.paddingLeft=pe.closeButtonPaddingX,T.style.paddingRight=pe.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),pe.closeButtonPaddingY?(T.style.paddingTop=pe.closeButtonPaddingY,T.style.paddingBottom=pe.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let rn=pe.closeButtonIconName??"x",xn=pe.closeButtonIconText??"\xD7";T.innerHTML="";let Kt=ne(rn,"28px","currentColor",1);Kt?T.appendChild(Kt):T.textContent=xn;let Lt=pe.closeButtonTooltipText??"Close chat",sn=pe.closeButtonShowTooltip??!0;if(T.setAttribute("aria-label",Lt),Je&&(Je._cleanupTooltip&&(Je._cleanupTooltip(),delete Je._cleanupTooltip),sn&&Lt)){let qe=null,Ft=()=>{if(qe||!T)return;let Do=T.ownerDocument,ns=Do.body;if(!ns)return;qe=kn(Do,"div","persona-clear-chat-tooltip"),qe.textContent=Lt;let os=kn(Do,"div");os.className="persona-clear-chat-tooltip-arrow",qe.appendChild(os);let Oo=T.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(po),qe.style.left=`${Oo.left+Oo.width/2}px`,qe.style.top=`${Oo.top-8}px`,qe.style.transform="translate(-50%, -100%)",ns.appendChild(qe)},Zt=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};Je.addEventListener("mouseenter",Ft),Je.addEventListener("mouseleave",Zt),T.addEventListener("focus",Ft),T.addEventListener("blur",Zt),Je._cleanupTooltip=()=>{Zt(),Je&&(Je.removeEventListener("mouseenter",Ft),Je.removeEventListener("mouseleave",Zt)),T&&(T.removeEventListener("focus",Ft),T.removeEventListener("blur",Zt))}}}let{clearChatButton:Be,clearChatButtonWrapper:et}=Ie;if(Be){let ee=pe.clearChat??{},nt=ee.enabled??!0,Et=o.layout?.header?.showClearChat,Je=Et!==void 0?Et:nt,dt=ee.placement??"inline";if(et){et.style.display=Je?"":"none";let{closeButtonWrapper:jt}=Ie;!Q()&&jt&&!jt.classList.contains("persona-absolute")&&(Je?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let rn=dt==="top-right",xn=et.classList.contains("persona-absolute");if(!Q()&&rn!==xn&&Je){if(et.remove(),rn)et.className="persona-absolute persona-top-4 persona-z-50",et.style.right="48px",fe.style.position="relative",fe.appendChild(et);else{et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",et.style.right="";let Lt=fe.querySelector(".persona-border-b-persona-divider"),sn=Ie.closeButtonWrapper;Lt&&sn&&sn.parentElement===Lt?Lt.insertBefore(et,sn):Lt&&Lt.appendChild(et)}let Kt=Ie.closeButtonWrapper;Kt&&!Kt.classList.contains("persona-absolute")&&(rn?Kt.classList.add("persona-ml-auto"):Kt.classList.remove("persona-ml-auto"))}}if(Je){if(!Q()){let qe=ee.size??"32px";Be.style.height=qe,Be.style.width=qe}let jt=ee.iconName??"refresh-cw",rn=ee.iconColor??"";Be.style.color=rn||Jt.actionIconColor,Be.innerHTML="";let xn=Q()?"14px":"20px",Kt=ne(jt,xn,"currentColor",2);if(Kt&&Be.appendChild(Kt),ee.backgroundColor?(Be.style.backgroundColor=ee.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let qe=ee.borderWidth||"0px",Ft=ee.borderColor||"transparent";Be.style.border=`${qe} solid ${Ft}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");ee.borderRadius?(Be.style.borderRadius=ee.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),ee.paddingX?(Be.style.paddingLeft=ee.paddingX,Be.style.paddingRight=ee.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),ee.paddingY?(Be.style.paddingTop=ee.paddingY,Be.style.paddingBottom=ee.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let Lt=ee.tooltipText??"Clear chat",sn=ee.showTooltip??!0;if(Be.setAttribute("aria-label",Lt),et&&(et._cleanupTooltip&&(et._cleanupTooltip(),delete et._cleanupTooltip),sn&&Lt)){let qe=null,Ft=()=>{if(qe||!Be)return;let Do=Be.ownerDocument,ns=Do.body;if(!ns)return;qe=kn(Do,"div","persona-clear-chat-tooltip"),qe.textContent=Lt;let os=kn(Do,"div");os.className="persona-clear-chat-tooltip-arrow",qe.appendChild(os);let Oo=Be.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(po),qe.style.left=`${Oo.left+Oo.width/2}px`,qe.style.top=`${Oo.top-8}px`,qe.style.transform="translate(-50%, -100%)",ns.appendChild(qe)},Zt=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};et.addEventListener("mouseenter",Ft),et.addEventListener("mouseleave",Zt),Be.addEventListener("focus",Ft),Be.addEventListener("blur",Zt),et._cleanupTooltip=()=>{Zt(),et&&(et.removeEventListener("mouseenter",Ft),et.removeEventListener("mouseleave",Zt)),Be&&(Be.removeEventListener("focus",Ft),Be.removeEventListener("blur",Zt))}}}}let on=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ci],Wo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pr.message,Pr.messageAndClick];R=di({parsers:on,handlers:Wo,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),De=yf(o,R,Ee),$.updateConfig(o),zr(ve,$.getMessages(),De),Li(),nd(),_i($.isStreaming());let Id=o.voiceRecognition?.enabled===!0,da=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rt=o.voiceRecognition?.provider?.type==="runtype";if(Id&&(da||Rt))if(!V||!ze){let ee=Dg(o.voiceRecognition,o.sendButton);ee&&(V=ee.micButton,ze=ee.micButtonWrapper,tt.insertBefore(ze,Fe),V.addEventListener("click",la),V.disabled=$.isStreaming())}else{let ee=o.voiceRecognition??{},nt=o.sendButton??{},Et=ee.iconName??"mic",Je=nt.size??"40px",dt=ee.iconSize??Je,jt=parseFloat(dt)||24;V.style.width=dt,V.style.height=dt,V.style.minWidth=dt,V.style.minHeight=dt;let rn=ee.iconColor??nt.textColor??"currentColor";V.innerHTML="";let xn=ne(Et,jt,rn,2);xn?V.appendChild(xn):V.textContent="\u{1F3A4}";let Kt=ee.backgroundColor??nt.backgroundColor;Kt?V.style.backgroundColor=Kt:V.style.backgroundColor="",rn?V.style.color=rn:V.style.color="var(--persona-text, #111827)",ee.borderWidth?(V.style.borderWidth=ee.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ee.borderColor?V.style.borderColor=ee.borderColor:V.style.borderColor="",ee.paddingX?(V.style.paddingLeft=ee.paddingX,V.style.paddingRight=ee.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ee.paddingY?(V.style.paddingTop=ee.paddingY,V.style.paddingBottom=ee.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Lt=ze?.querySelector(".persona-send-button-tooltip"),sn=ee.tooltipText??"Start voice recognition";if((ee.showTooltip??!1)&&sn)if(Lt)Lt.textContent=sn,Lt.style.display="";else{let Ft=document.createElement("div");Ft.className="persona-send-button-tooltip",Ft.textContent=sn,ze?.insertBefore(Ft,V)}else Lt&&(Lt.style.display="none");ze.style.display="",V.disabled=$.isStreaming()}else V&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():En&&eo());if(o.attachments?.enabled===!0)if(!He||!We){let ee=o.attachments??{},Et=(o.sendButton??{}).size??"40px";Qe||(Qe=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Qe.style.display="none",Se.insertBefore(Qe,N)),ke||(ke=document.createElement("input"),ke.type="file",ke.accept=(ee.allowedTypes??Un).join(","),ke.multiple=(ee.maxFiles??4)>1,ke.style.display="none",ke.setAttribute("aria-label","Attach files"),Se.insertBefore(ke,N)),He=m("div","persona-send-button-wrapper"),We=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),We.type="button",We.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Je=ee.buttonIconName??"paperclip",dt=Et,jt=parseFloat(dt)||40,rn=Math.round(jt*.6);We.style.width=dt,We.style.height=dt,We.style.minWidth=dt,We.style.minHeight=dt,We.style.fontSize="18px",We.style.lineHeight="1";let xn=ne(Je,rn,"currentColor",1.5);xn?We.appendChild(xn):We.textContent="\u{1F4CE}",We.addEventListener("click",sn=>{sn.preventDefault(),ke?.click()}),He.appendChild(We);let Kt=ee.buttonTooltipText??"Attach file",Lt=m("div","persona-send-button-tooltip");Lt.textContent=Kt,He.appendChild(Lt),Te?Te.append(He):Se.appendChild(He),!kt&&ke&&Qe&&(kt=vr.fromConfig(ee),kt.setPreviewsContainer(Qe),ke.addEventListener("change",async()=>{kt&&ke?.files&&(await kt.handleFileSelect(ke.files),ke.value="")})),fe.querySelector(".persona-attachment-drop-overlay")||fe.appendChild(bf(ee.dropOverlay))}else{He.style.display="";let ee=o.attachments??{};ke&&(ke.accept=(ee.allowedTypes??Un).join(","),ke.multiple=(ee.maxFiles??4)>1),kt&&kt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else He&&(He.style.display="none"),kt&&kt.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Nt=o.sendButton??{},Zr=Nt.useIcon??!1,ua=Nt.iconText??"\u2191",dr=Nt.iconName,es=Nt.tooltipText??"Send message",Zi=Nt.showTooltip??!1,Ho=Nt.size??"40px",Fn=Nt.backgroundColor,Bo=Nt.textColor;if(Zr){if(te.style.width=Ho,te.style.height=Ho,te.style.minWidth=Ho,te.style.minHeight=Ho,te.style.fontSize="18px",te.style.lineHeight="1",te.innerHTML="",Bo?te.style.color=Bo:te.style.color="var(--persona-button-primary-fg, #ffffff)",dr){let ee=parseFloat(Ho)||24,nt=Bo?.trim()||"currentColor",Et=ne(dr,ee,nt,2);Et?te.appendChild(Et):te.textContent=ua}else te.textContent=ua;te.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fn?(te.style.backgroundColor=Fn,te.classList.remove("persona-bg-persona-primary")):(te.style.backgroundColor="",te.classList.add("persona-bg-persona-primary"))}else te.textContent=o.copy?.sendButtonLabel??"Send",te.style.width="",te.style.height="",te.style.minWidth="",te.style.minHeight="",te.style.fontSize="",te.style.lineHeight="",te.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Fn?(te.style.backgroundColor=Fn,te.classList.remove("persona-bg-persona-accent")):te.classList.add("persona-bg-persona-accent"),Bo?te.style.color=Bo:te.classList.add("persona-text-white");Nt.borderWidth?(te.style.borderWidth=Nt.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),Nt.borderColor?te.style.borderColor=Nt.borderColor:te.style.borderColor="",Nt.paddingX?(te.style.paddingLeft=Nt.paddingX,te.style.paddingRight=Nt.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),Nt.paddingY?(te.style.paddingTop=Nt.paddingY,te.style.paddingBottom=Nt.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let ts=Fe?.querySelector(".persona-send-button-tooltip");if(Zi&&es)if(ts)ts.textContent=es,ts.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=es,Fe?.insertBefore(ee,te)}else ts&&(ts.style.display="none");let fa=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);fa?(ve.style.maxWidth=fa,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%",Se&&(Se.style.maxWidth=fa,Se.style.marginLeft="auto",Se.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=fa,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(ve.style.maxWidth="",ve.style.marginLeft="",ve.style.marginRight="",ve.style.width="",Se&&(Se.style.maxWidth="",Se.style.marginLeft="",Se.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let no=o.statusIndicator??{},Ug=no.visible??!0;if(M.style.display=Ug?"":"none",$){let ee=$.getStatus();yt(M,(Et=>Et==="idle"?no.idleText??Ht.idle:Et==="connecting"?no.connectingText??Ht.connecting:Et==="connected"?no.connectedText??Ht.connected:Et==="error"?no.errorText??Ht.error:Ht[Et])(ee),no,ee)}M.classList.remove("persona-text-left","persona-text-center","persona-text-right");let zg=no.align==="left"?"persona-text-left":no.align==="center"?"persona-text-center":"persona-text-right";M.classList.add(zg)},open(){D()&&ht(!0,"api")},close(){D()&&ht(!1,"api")},toggle(){D()&&ht(!j,"api")},reconnect(){$.reconnectNow()},clearChat(){Hn=!1,$.clearMessages(),Mo.clear(),Yn();try{localStorage.removeItem(Rr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Rr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Rr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&Di(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},R.syncFromMetadata(),Oe?.clear(),Ue?.reset(),Ne?.update()},setMessage(l){return!N||$.isStreaming()?!1:(!j&&D()&&ht(!0,"system"),N.value=l,N.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let g=l?.trim()||N.value.trim();return g?(!j&&D()&&ht(!0,"system"),N.value="",N.style.height="auto",$.sendMessage(g),!0):!1},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!j&&D()&&ht(!0,"system"),Xe.manuallyDeactivated=!1,vn(),$.toggleVoice().then(()=>{Xe.active=$.isVoiceActive(),Dn("user"),$.isVoiceActive()&&lr()})),!0):En?!0:dd()?(!j&&D()&&ht(!0,"system"),Xe.manuallyDeactivated=!1,vn(),aa("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,vn(),Dn("user"),Nn()}),!0):!1:En?(Xe.manuallyDeactivated=!0,vn(),eo("user"),!0):!1},injectMessage(l){return!j&&D()&&ht(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!j&&D()&&ht(!0,"system");let g=$.injectAssistantMessage(l);return ge&&(ge=!1,ye&&(clearTimeout(ye),ye=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),g},injectUserMessage(l){return!j&&D()&&ht(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!j&&D()&&ht(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!j&&D()&&ht(!0,"system"),$.injectMessageBatch(l)},injectComponentDirective(l){return!j&&D()&&ht(!0,"system"),$.injectComponentDirective(l)},injectTestMessage(l){!j&&D()&&ht(!0,"system"),$.injectTestEvent(l)},async connectStream(l,g){return $.connectStream(l,g)},__pushEventStreamEvent(l){Oe&&(Ue?.processEvent(l.type,l.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Y||!Oe||Ai()},hideEventStream(){we&&Hr()},isEventStreamVisible(){return we},showArtifacts(){Xt(o)&&(Hn=!1,er=!0,Bn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Hn=!0,Bn())},upsertArtifact(l){return Xt(o)?(Fo(o.features?.artifacts,l.artifactType)==="panel"&&(Hn=!1,er=!0),$.upsertArtifact(l)):null},selectArtifact(l){Xt(o)&&$.selectArtifact(l)},clearArtifacts(){Xt(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return A&&!j&&!Q()||!N?!1:(N.focus(),!0)},async resolveApproval(l,g,b){let S=$.getMessages().find(P=>P.variant==="approval"&&P.approval?.id===l);if(!S?.approval)throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){$.resolveWebMcpApproval(S.id,g);return}return $.resolveApproval(S.approval,g,b)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,g){return i.on(l,g)},off(l,g){i.off(l,g)},isOpen(){return D()&&j},isVoiceActive(){return Xe.active},toggleReadAloud(l){$.toggleReadAloud(l)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(l){return $.getReadAloudState(l)},onReadAloudChange(l){return $.onReadAloudChange(l)},getState(){return{open:D()&&j,launcherEnabled:A,voiceActive:Xe.active,streaming:$.isStreaming()}},showCSATFeedback(l){!j&&D()&&ht(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let b=dc({onSubmit:async(v,S)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(v,S),l?.onSubmit?.(v,S)},onDismiss:l?.onDismiss,...l});ve.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!j&&D()&&ht(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let b=pc({onSubmit:async(v,S)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(v,S),l?.onSubmit?.(v,S)},onDismiss:l?.onDismiss,...l});ve.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return $.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return $.submitNPSFeedback(l,g)},destroy(){zi(),Po!=null&&(clearInterval(Po),Po=null),Ke.forEach(l=>l()),Me.remove(),lt?.remove(),_t?.destroy(),zt?.remove(),Eo&&T.removeEventListener("click",Eo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:Wt,getMessages:Wt.getMessages,getStatus:Wt.getStatus,getMetadata:Wt.getPersistentMetadata,updateMetadata:Wt.updatePersistentMetadata,clearHistory:()=>Wt.clearChat(),setVoiceActive:b=>b?Wt.startVoiceRecognition():Wt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ke.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=F=>{let K=F.detail;(!K?.instanceId||K.instanceId===l)&&Wt.focusInput()};if(window.addEventListener("persona:focusInput",g),Ke.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let F=oe=>{let de=oe.detail;(!de?.instanceId||de.instanceId===l)&&Wt.showEventStream()},K=oe=>{let de=oe.detail;(!de?.instanceId||de.instanceId===l)&&Wt.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",K),Ke.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",K)})}let b=F=>{let K=F.detail;(!K?.instanceId||K.instanceId===l)&&Wt.showArtifacts()},v=F=>{let K=F.detail;(!K?.instanceId||K.instanceId===l)&&Wt.hideArtifacts()},S=F=>{let K=F.detail;K?.instanceId&&K.instanceId!==l||K?.artifact&&Wt.upsertArtifact(K.artifact)},P=F=>{let K=F.detail;K?.instanceId&&K.instanceId!==l||typeof K?.id=="string"&&Wt.selectArtifact(K.id)},X=F=>{let K=F.detail;(!K?.instanceId||K.instanceId===l)&&Wt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",X),Ke.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",X)})}let un=aC(o.persistState);if(un&&D()){let l=iC(un.storage),g=`${un.keyPrefix}widget-open`,b=`${un.keyPrefix}widget-voice`,v=`${un.keyPrefix}widget-voice-mode`;if(l){let S=un.persist?.openState&&l.getItem(g)==="true",P=un.persist?.voiceState&&l.getItem(b)==="true",X=un.persist?.voiceState&&l.getItem(v)==="true";if(S&&setTimeout(()=>{Wt.open(),setTimeout(()=>{if(P||X)Wt.startVoiceRecognition();else if(un.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),un.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(g,"true")}),i.on("widget:closed",()=>{l.setItem(g,"false")})),un.persist?.voiceState&&(i.on("voice:state",F=>{l.setItem(b,F.active?"true":"false")}),i.on("user:message",F=>{l.setItem(v,F.viaVoice?"true":"false")})),un.clearOnChatClear){let F=()=>{l.removeItem(g),l.removeItem(b),l.removeItem(v)},K=()=>F();window.addEventListener("persona:clear-chat",K),Ke.push(()=>{window.removeEventListener("persona:clear-chat",K)})}}}if(y&&D()&&setTimeout(()=>{Wt.open()},0),sr(),!ig){let l=rs(()=>{$&&(Pi++,Mo.clear(),zr(ve,$.getMessages(),De))});Ke.push(l)}return Wt};var vf=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},dC=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},pC=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},uC=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let s=o.offsetHeight>0;o.style.height="100%";let r=o.offsetHeight>0;o.remove(),!(!s||r)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},xf=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},yc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Cf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",yc(e)},gc=e=>{e.style.transition=""},mc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},hc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},fi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},fC=(e,t,n,o,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},gC=(e,t,n,o,s,r)=>{let a=r?t:e;s==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},mC=e=>{let t=Ko(e),n=t.components?.panel,o=(s,r)=>s==null||s===""?r:Gt(t,s)??s;return{inset:o(n?.inset,Ha),canvasBackground:o(n?.canvasBackground,Ba)}},wf=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},hC=(e,t,n,o,s,r,a,i)=>{let p=an(r),d=p.reveal==="push",c=i!=null,u=i?.inset??"",y=i?.canvasBackground??"";fC(e,t,n,o,d),gC(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=r?.launcher?.mobileFullscreen??!0,C=r?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=C:!1;if(h&&E&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),mc(t),gc(o),Cf(o),hc(n),fi(s,o),wf(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(r?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Cf(o),dC(o,p.maxHeight),wf(o,c&&a,u,y),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",mc(t),gc(o),hc(n),fi(s,o);let R=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",I=a?"translateX(0)":A;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=R,o.style.transform=I,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",gc(o),yc(o),fi(s,o);let R=vf(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),I=p.animate?"margin-left 180ms ease":"none",_=p.side==="right"?a?-R:0:a?0:-R;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${A+R}px`,t.style.transition=I,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",mc(t),yc(o),hc(n),fi(s,o);let R=p.reveal==="emerge";R?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=a?p.width:"0px",I=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",_=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",pC(o,p.maxHeight),o.style.overflow=R||_?"hidden":"visible",o.style.transition=I,R){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let O=c?`calc(${vf(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;s.style.width=O,s.style.minWidth=O,s.style.maxWidth=O,s.style.boxSizing="border-box"}}},yC=(e,t)=>{let n=e.ownerDocument.createElement("div");return xf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){xf(n,o)},destroy(){n.remove()}}},bC=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let r=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let y=null,f=()=>{y?.disconnect(),y=null},h=null,C=()=>{h=t?.launcher?.detachedPanel===!0?mC(t):null};C();let E=()=>{hC(a,i,p,d,c,t,u,h)},L=null,R=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=As(()=>{C(),E()}))},A=()=>{f(),an(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{E()}),y.observe(a)))},I=!1,_=()=>{E(),A(),u&&!I&&a.dataset.personaDockMobileFullscreen!=="true"&&(I=!0,uC(a,an(t)))},O=a.ownerDocument.defaultView,w=()=>{_()};return O?.addEventListener("resize",w),an(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),_(),R(),{mode:"docked",host:c,shell:a,syncWidgetState(U){let q=U.launcherEnabled?U.open:!0;u!==q&&(u=q,_())},updateConfig(U){t=U,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),_(),R()},destroy(){O?.removeEventListener("resize",w),L?.(),L=null,f(),o.isConnected&&(r&&r.parentNode===o?o.insertBefore(e,r):o.appendChild(e)),a.remove()}}},gi=(e,t)=>Bt(t)?bC(e,t):yC(e,t);var vC=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Af=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Sf=e=>{let t=vC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,s=e.config,r=gi(t,s),a,i=[],p=(E,L)=>{let A=!(L?.launcher?.enabled??!0)||Bt(L),I=o.createElement("div");if(I.setAttribute("data-persona-root","true"),A&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let _=E.attachShadow({mode:"open"});_.appendChild(I),Af(_,o)}else E.appendChild(I),Af(E,o);return t.id&&I.setAttribute("data-persona-instance",t.id),I},d=()=>{r.syncWidgetState(a.getState())},c=()=>{i.forEach(E=>E()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let E=p(r.host,s);a=fc(E,s,{debugTools:e.debugTools}),c()},y=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),e.onChatReady?.();let f=E=>{y(),r.destroy(),r=gi(t,E),s=E,u()},h={update(E){let L={...s,...E,launcher:{...s?.launcher??{},...E?.launcher??{},dock:{...s?.launcher?.dock??{},...E?.launcher?.dock??{}}}},R=Bt(s),A=Bt(L),I=yo(s),_=yo(L);if(R!==A||I!==_){f(L);return}s=L,r.updateConfig(s),a.update(E),d()},destroy(){y(),r.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(h,{get(E,L,R){if(L==="host")return r.host;if(L in E)return Reflect.get(E,L,R);let A=a[L];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function xC(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function CC(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(r=>r.toLowerCase().startsWith(o))?1:xC(o,n)?2:3}function Tf(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function bc(e,t){let n=t.trim();if(!n)return[...e].sort(Tf);let o=[];for(let s of e){let r=CC(s.label,n);r!==3&&o.push({item:s,tier:r})}return o.sort((s,r)=>s.tier!==r.tier?s.tier-r.tier:Tf(s.item,r.item)),o.map(s=>s.item)}function wC(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function AC(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>bc(e.items,t),resolve:e.resolve}}function SC(e){let t=e.commands.map(s=>({id:s.name,label:s.name,description:s.description,iconName:s.iconName,command:s.kind??"prompt",insertMode:s.insertMode,submitOnSelect:s.submitOnSelect,action:s.action,commandArgsPlaceholder:s.argsPlaceholder})),n=new Map(e.commands.map(s=>[s.name,s])),o=new Map(t.map(s=>[s.id,s]));return{id:e.id,label:e.label,matchCommand:s=>o.get(s),resolveOn:"submit",search:s=>bc(t,wC(s).name),resolve:(s,r)=>{let a=n.get(s.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(r.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(r.args):a.prompt??""}:{}}}}var Pf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),TC=new Set(["button","a","input","select","textarea","details","summary"]),EC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),vc=/\b(product|card|item|listing|result)\b/i,Cc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,MC=3e3,kC=100;function Rf(e){let t=typeof e.className=="string"?e.className:"";if(vc.test(t)||e.id&&vc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&vc.test(o.value))return!0}return!1}function If(e){return Cc.test((e.textContent??"").trim())}function Wf(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function LC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ef(e){let t=e.match(Cc);return t?t[0]:null}function Mf(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function PC(e){let t=[],n=o=>{let s=o.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var RC="commerce-card",IC="result-card";function kf(e){return!Rf(e)||!If(e)||!Wf(e)&&!LC(e)?0:5200}function Lf(e){return!Rf(e)||If(e)||!Wf(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Hf=[{id:RC,scoreElement(e){return kf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Cc.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(kf(e)===0)return null;let{title:n,href:o}=Mf(e),s=Ef((e.textContent??"").trim())??Ef(t.text)??"",r=PC(e);return[o&&n?`[${n}](${o})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,r.length?`actions: ${r.join(", ")}`:""].filter(Boolean).join(`
143
- `)}},{id:IC,scoreElement(e){return Lf(e)},formatSummary(e,t){if(Lf(e)===0)return null;let{title:n,href:o}=Mf(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
- `)}}];function WC(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function HC(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",s=t.maxTextLength??e.maxTextLength??200,r=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??Hf;return i==="simple"&&e.rules&&e.rules.length>0?(WC(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:s,visibleOnly:r,root:a,rules:d}}function xc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var BC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function DC(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||TC.has(t)||n&&EC.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Bf(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function OC(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let r=e.getAttribute("type");r&&(t.type=r);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function Df(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${xc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of BC){let r=e.getAttribute(s);if(r){let a=`${t}[${s}="${xc(r)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>xc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let r=e.parentElement;if(r){let i=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function NC(e){return e==="static"?kC:MC}function Of(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Df(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:DC(e),attributes:OC(e)}}function FC(e,t,n,o){let s=NC(t.interactivity),r=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(s+=i,a.formatSummary&&!r&&(r=a))}return{score:s,formattingRule:r}}function _C(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function $C(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,s=[],r=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(Pf.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Bf(d)){i=a.nextNode();continue}let u=Of(d,e.maxTextLength),y=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!y&&!f){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:h,formattingRule:C}=FC(d,u,e.rules,n);s.push({el:d,domIndex:r,enriched:u,score:h,formattingRule:C}),r+=1}i=a.nextNode()}s.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of s){if(p.length>=e.maxElements)break;_C(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let y=d.formattingRule.formatSummary(d.el,d.enriched,n);y&&(c=y)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function jC(e,t){let n=[],o=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),r=s.currentNode;for(;r&&n.length<e.maxElements;){if(r.nodeType===Node.ELEMENT_NODE){let p=r,d=p.tagName.toLowerCase();if(Pf.has(d)){r=s.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){r=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Bf(p)){r=s.nextNode();continue}let c=Of(p,e.maxTextLength),u=c.text.length>0,y=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!y){r=s.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}r=s.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function UC(e={}){let t=HC(e),n=t.root??document.body;return n?t.mode==="simple"?jC(t,n):$C(t,n):[]}var mi=100;function zC(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let r=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);r.length>0&&o.push(`Structured summaries:
141
+ ${rt?"background: transparent !important;":""}
142
+ `}if(!x&&!l){let Pt="max-height: -moz-available !important; max-height: stretch !important;",Qt=g?"":"padding-top: 1.25em !important;",pa=g?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Ie.style.cssText+=Pt+Qt+pa}Wo()};Ys(),xr(e,o),_s(e,o),$s(e,o),Dr=()=>{Ys(),xr(e,o),_s(e,o),$s(e,o),qs?e.style.setProperty("--persona-artifact-welded-outer-radius",qs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ke=[];Ke.push(()=>{document.removeEventListener("keydown",_c)}),Ke.push(()=>{Wr!==null&&clearTimeout(Wr)});let Sn=null,Tn=null;Ke.push(()=>{Sn?.(),Sn=null,Tn?.(),Tn=null}),Br&&Ke.push(()=>{Br?.disconnect(),Br=null}),Ke.push(()=>{Fr?.(),Fr=null,Pi(),wt&&(wt.remove(),wt=null),tt?.element.style.removeProperty("width"),tt?.element.style.removeProperty("maxWidth")}),Y&&Ke.push(()=>{Je!==null&&(cancelAnimationFrame(Je),Je=null),He?.destroy(),He=null,Oe?.destroy(),Oe=null,pe=null});let To=null,Uc=()=>{To&&(To(),To=null),o.colorScheme==="auto"&&(To=As(()=>{xr(e,o)}))};Uc(),Ke.push(()=>{To&&(To(),To=null)}),Ke.push(a);let Zs=o.features?.streamAnimation;if(Zs?.type&&Zs.type!=="none"){let l=Sr(Zs.type,Zs.plugins);l&&(Qa(l,e),Ke.push(()=>Ru(e)))}let ea=nf(Ct),Eo=null,$,Ri=l=>{if(!$)return;let g=l??$.getMessages(),b=o.features?.suggestReplies?.enabled!==!1?fl(g):null;b?ea.render(b,$,ye,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(x=>x.role==="user")?ea.render([],$,ye,g):ea.render(o.suggestionChips,$,ye,g,o.suggestionChipsConfig)},yn=!1,Mo=wu(),or=new Map,ko=new Map,Jn=new Map,Ii=0,dg=_n()!==null,en=qa(),ln=0,Xn=null,cn=!1,ta=!1,Qn=0,bn=null,Lo=null,Wi=!1,na=!1,Hi=null,_r=!0,Bi=!1,Di=null,pg=4,oa=24,ug=80,Oi=new Map,Ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},zc=o.voiceRecognition?.autoResume??!1,Dn=l=>{i.emit("voice:state",{active:Ze.active,source:l,timestamp:Date.now()})},vn=()=>{C(l=>({...l,voiceState:{active:Ze.active,timestamp:Date.now(),manuallyDeactivated:Ze.manuallyDeactivated}}))},fg=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=fc(c.voiceState),g=!!l.active,b=Number(l.timestamp??0);Ze.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-b<aC&&setTimeout(()=>{Ze.active||(Ze.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ze.active=$.isVoiceActive(),Dn("restore"),$.isVoiceActive()&&lr()}):aa("restore"))},1e3)},gg=()=>$?vf($.getMessages()).filter(l=>!l.__skipPersist):[],ra=null,qc=(l,g)=>{typeof console<"u"&&console.error(l,g)},Ni=(l,g)=>{let b=()=>{try{let J=l();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(F=>{qc(g,F)})}catch(J){return qc(g,J),null}},x=ra,T=x?x.then(()=>b()??void 0):b();if(!T)return;let P=T.finally(()=>{ra===P&&(ra=null)});ra=P};function Fi(l){if(!d?.save)return;let b={messages:l?vf(l):$?gg():[],metadata:c,artifacts:mn.artifacts,selectedArtifactId:mn.selectedId};Ni(()=>d.save(b),"[AgentWidget] Failed to persist state:")}let rr=null,Vc=()=>Ie.querySelector("#persona-scroll-container")||ie,$r=()=>{rr!==null&&(cancelAnimationFrame(rr),rr=null),cn=!1},Kc=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),ta=!1,$r()},mg=()=>yn&&$i()&&(Xt()!=="anchor-top"||Mc()),_i=()=>{let l=Co()||"Jump to latest",g=mg();Rt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Qn>0?(wo.textContent=String(Qn),wo.style.display="",Rt.setAttribute("aria-label",`${l} (${Qn} new)`)):(wo.textContent="",wo.style.display="none",Rt.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},Gc=()=>{Qn!==0&&(Qn=0,_i())},$i=()=>qn()?!en.isFollowing():!mo(ie,oa),tn=()=>{if(!Us()||je){Rt.parentNode&&Rt.remove(),Rt.style.display="none";return}Rt.parentNode!==fe&&fe.appendChild(Rt),Zo();let g=In(ie)>0&&$i();g?_i():Gc(),Rt.style.display=g?"":"none"},jr=()=>{en.pause()&&(Kc(),tn())},Yn=()=>{en.resume(),Gc(),tn()},Zn=(l=!1)=>{qn()&&en.isFollowing()&&(!l&&!yn||(Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),ta=!0,Xn=requestAnimationFrame(()=>{Xn=null,ta=!1,en.isFollowing()&&hg(Vc(),l?220:140)})))},Jc=(l,g,b,x=()=>!0)=>{let T=l.scrollTop,P=g(),J=P-T;if($r(),Math.abs(J)<1){cn=!0,l.scrollTop=P,ln=l.scrollTop,cn=!1;return}let F=performance.now();cn=!0;let G=ce=>1-Math.pow(1-ce,3),re=ce=>{if(!x()){$r();return}let se=g();se!==P&&(P=se,J=P-T);let we=ce-F,Ge=Math.min(we/b,1),yt=G(Ge),it=T+J*yt;l.scrollTop=it,ln=l.scrollTop,Ge<1?rr=requestAnimationFrame(re):(l.scrollTop=P,ln=l.scrollTop,rr=null,cn=!1)};rr=requestAnimationFrame(re)},hg=(l,g=500)=>{let b=In(l)-l.scrollTop;if(Math.abs(b)<1){ln=l.scrollTop;return}if(Math.abs(b)>=ug){$r(),cn=!0,l.scrollTop=In(l),ln=l.scrollTop,cn=!1;return}Jc(l,()=>In(l),g,()=>en.isFollowing())},Xc=()=>{let l=Vc();cn=!0,l.scrollTop=In(l),ln=l.scrollTop,cn=!1,tn()},Qc=l=>{let g=0,b=l;for(;b&&b!==ie;)g+=b.offsetTop,b=b.offsetParent;return g},Yc=()=>{if(og()!=="last-user-turn")return!1;let l=$?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(P=>P.role==="user");if(!g)return!1;let b=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ie.querySelector(`[data-message-id="${b}"]`);if(!x)return!1;let T=Math.min(Math.max(0,Qc(x)-Tc()),In(ie));return cn=!0,ie.scrollTop=T,ln=ie.scrollTop,cn=!1,Xt()==="follow"&&!mo(ie,oa)&&en.pause(),tn(),!0},Zc=l=>{Vn.style.height=`${Math.max(0,Math.round(l))}px`,bn&&(bn.spacerHeight=Math.max(0,l))},Ur=()=>{Lo!==null&&(cancelAnimationFrame(Lo),Lo=null),$r(),bn=null,Vn.style.height="0px"},yg=l=>{Lo!==null&&cancelAnimationFrame(Lo),Lo=requestAnimationFrame(()=>{Lo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ie.querySelector(`[data-message-id="${g}"]`);if(!b)return;let x=Qc(b),T=bn?.spacerHeight??0,P=ie.scrollHeight-T,{targetScrollTop:J,spacerHeight:F}=Mu({anchorOffsetTop:x,topOffset:Tc(),viewportHeight:ie.clientHeight,contentHeight:P});bn={initialSpacerHeight:F,contentHeightAtAnchor:P,spacerHeight:F},Zc(F),Jc(ie,()=>J,220)})},bg=()=>{if(qn()){if(!en.isFollowing()||mo(ie,1))return;Zn(!yn);return}if(bn&&bn.initialSpacerHeight>0){let l=ie.scrollHeight-bn.spacerHeight,g=ku({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:l});g!==bn.spacerHeight&&Zc(g)}tn()},vg=l=>{let g=Xt();g==="follow"?(Yn(),Zn(!0)):g==="anchor-top"&&(_r=!1,Bi=!0,yg(l))},xg=()=>{if(Xt()==="anchor-top"){if(Bi){_r=!1;return}_r=!0,Ur(),Yn(),Zn(!0)}},Cg=l=>{let g=new Map;l.forEach(b=>{let x=Oi.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(i.emit("assistant:message",b),!na&&(Xt()!=="anchor-top"||Mc())&&$i()&&(Qn+=1,_i(),tn(),Lc(Qn===1?"1 new message below.":`${Qn} new messages below.`))),b.role==="assistant"&&x?.streaming&&b.streaming===!1&&i.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&i.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):i.emit("approval:requested",{approval:b.approval,message:b}))}),Oi.clear(),g.forEach((b,x)=>{Oi.set(x,b)})},wg=(l,g,b)=>{let x=document.createElement("div"),P=(()=>{let W=s.find(Fe=>Fe.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(W,Fe)=>Fe==null?!1:typeof Fe=="string"?(W.textContent=Fe,!0):(W.appendChild(Fe),!0),F=new Set,G=new Set,re=s.some(W=>W.renderAskUserQuestion),ce=[],se=[],we=o.enableComponentStreaming!==!1,Ge=o.approval!==!1,yt=[];if(g.forEach(W=>{F.add(W.id);let Fe=re&&oo(W),Ae=Ge&&W.variant==="approval"&&!!W.approval,_e=!Fe&&W.role==="assistant"&&!W.variant&&we&&fi(W);!Ae&&Jn.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id)),!_e&&ko.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),ko.delete(W.id));let Et=oo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=Cu(W,Ii)+Et,St=Fe||Ae||_e?null:Au(Mo,W.id,dt);if(St){x.appendChild(St.cloneNode(!0)),oo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(G.add(W.toolCall.id),ds(W,o,ke.composerOverlay));return}let vt=null,$t=s.find(de=>!!(W.variant==="reasoning"&&de.renderReasoning||W.variant==="tool"&&de.renderToolCall||!W.variant&&de.renderMessage)),Io=o.layout?.messages;if(oo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){or.delete(W.id),l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(wa(W)&&o.features?.suggestReplies?.enabled!==!1)return;if(oo(W)&&o.features?.askUserQuestion?.enabled!==!1){let de=s.find(Tt=>typeof Tt.renderAskUserQuestion=="function");if(de&&ft.current){let Tt=or.get(W.id),Vt=Tt!==dt,Dt=null;if(Vt){let{payload:nt,complete:Lt}=ro(W),Be=W.id,ot=()=>ft.current?.getMessages().find(nn=>nn.id===Be);Dt=de.renderAskUserQuestion({message:W,payload:nt,complete:Lt,resolve:nn=>{let Wo=ot();Wo&&ft.current?.resolveAskUserQuestion(Wo,nn)},dismiss:()=>{let nn=ot();nn?.agentMetadata?.awaitingLocalTool&&(ft.current?.markAskUserQuestionResolved(nn),ft.current?.resolveAskUserQuestion(nn,"(dismissed)"))},config:o})}let rt=Tt!=null;if(Vt&&Dt===null&&!rt){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(G.add(W.toolCall.id),ds(W,o,ke.composerOverlay));return}let qe=document.createElement("div");qe.className="persona-flex",qe.id=`wrapper-${W.id}`,qe.setAttribute("data-wrapper-id",W.id),qe.setAttribute("data-ask-plugin-stub","true"),qe.setAttribute("data-preserve-runtime","true"),x.appendChild(qe),ce.push({messageId:W.id,fingerprint:dt,bubble:Dt});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(G.add(W.toolCall.id),ds(W,o,ke.composerOverlay));return}}else if(Ae){let de=s.find(rt=>typeof rt.renderApproval=="function")??r,Vt=Jn.get(W.id)!==dt,Dt=null;if(Vt&&de?.renderApproval){let rt=W.id,qe=(nt,Lt)=>{let Be=ft.current?.getMessages().find(ot=>ot.id===rt);Be?.approval&&(Be.approval.toolType==="webmcp"?ft.current?.resolveWebMcpApproval(Be.id,nt):ft.current?.resolveApproval(Be.approval,nt,Lt))};Dt=de.renderApproval({message:W,defaultRenderer:()=>ii(W,o),config:o,approve:nt=>qe("approved",nt),deny:nt=>qe("denied",nt)})}if(Vt&&Dt===null)l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id),vt=ii(W,o);else{let rt=document.createElement("div");rt.className="persona-flex",rt.id=`wrapper-${W.id}`,rt.setAttribute("data-wrapper-id",W.id),rt.setAttribute("data-approval-plugin-stub","true"),rt.setAttribute("data-preserve-runtime","true"),x.appendChild(rt),yt.push({messageId:W.id,fingerprint:dt,bubble:Dt});return}}else if($t)if(W.variant==="reasoning"&&W.reasoning&&$t.renderReasoning){if(!ae)return;vt=$t.renderReasoning({message:W,defaultRenderer:()=>Gl(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&$t.renderToolCall){if(!ve)return;vt=$t.renderToolCall({message:W,defaultRenderer:()=>Xl(W,o),config:o})}else $t.renderMessage&&(vt=$t.renderMessage({message:W,defaultRenderer:()=>{let de=Ds(W,b,Io,o.messageActions,ne,{loadingIndicatorRenderer:P,widgetConfig:o});return W.role!=="user"&&rc(de,W,o,$),de},config:o}));if(!vt&&_e){let de=dc(W);if(de){let Tt=ko.get(W.id),Vt=Tt!==dt,Dt=o.wrapComponentDirectiveInBubble!==!1&&Rn.getOptions(de.component)?.bubbleChrome!==!1,rt=null;if(Vt){let qe=cc(de,{config:o,message:W,transform:b});if(qe&&de.component==="PersonaArtifactInline"){let nt=qe.hasAttribute("data-artifact-inline")?qe:qe.querySelector("[data-artifact-inline]"),Lt=nt?.getAttribute("data-artifact-inline")??"",Be=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Lt):Lt,ot=Lt?l.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${Be}"]`)??null:null;nt&&ot&&ot!==nt&&hu(ot)&&(nt===qe?qe=ot:nt.replaceWith(ot))}if(qe)if(Dt){let nt=document.createElement("div");if(nt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),nt.id=`bubble-${W.id}`,nt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Lt=document.createElement("div");Lt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Lt.innerHTML=b({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),nt.appendChild(Lt)}nt.appendChild(qe),rt=nt}else{let nt=document.createElement("div");if(nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",nt.id=`bubble-${W.id}`,nt.setAttribute("data-message-id",W.id),nt.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Lt=document.createElement("div");Lt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Lt.innerHTML=b({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),nt.appendChild(Lt)}nt.appendChild(qe),rt=nt}}if(rt||Tt!=null){let qe=document.createElement("div");qe.className="persona-flex",qe.id=`wrapper-${W.id}`,qe.setAttribute("data-wrapper-id",W.id),qe.setAttribute("data-component-directive-stub","true"),qe.setAttribute("data-preserve-runtime","true"),Dt||qe.classList.add("persona-w-full"),x.appendChild(qe),se.push({messageId:W.id,fingerprint:dt,bubble:rt});return}}}if(!vt)if(W.variant==="reasoning"&&W.reasoning){if(!ae)return;vt=Gl(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!ve)return;vt=Xl(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;vt=ii(W,o)}else{let de=o.layout?.messages;de?.renderUserMessage&&W.role==="user"?vt=de.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):de?.renderAssistantMessage&&W.role==="assistant"?vt=de.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):vt=Ds(W,b,de,o.messageActions,ne,{loadingIndicatorRenderer:P,widgetConfig:o}),W.role!=="user"&&vt&&rc(vt,W,o,$)}let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-${W.id}`,pt.setAttribute("data-wrapper-id",W.id),W.role==="user"&&pt.classList.add("persona-justify-end"),vt?.getAttribute("data-persona-component-directive")==="true"&&pt.classList.add("persona-w-full"),pt.appendChild(vt),Su(Mo,W.id,dt,pt),x.appendChild(pt)}),ke.composerOverlay&&ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let Ae=Fe.getAttribute("data-persona-ask-sheet-for");Ae&&!G.has(Ae)&&$o(ke.composerOverlay,Ae)}),o.features?.toolCallDisplay?.grouped){let W=[],Fe=[];g.forEach(Ae=>{if(Ae.variant==="tool"&&Ae.toolCall&&ve){Fe.push(Ae);return}Ae.variant==="reasoning"&&!ae||(Fe.length>1&&W.push(Fe),Fe=[])}),Fe.length>1&&W.push(Fe),W.forEach((Ae,_e)=>{let Et=Ae.map(Tt=>Array.from(x.children).find(Vt=>Vt instanceof HTMLElement&&Vt.getAttribute("data-wrapper-id")===Tt.id)).filter(Tt=>!!Tt);if(Et.length<2)return;let dt=document.createElement("div");dt.className="persona-flex",dt.id=`wrapper-tool-group-${_e}-${Ae[0].id}`,dt.setAttribute("data-wrapper-id",`tool-group-${_e}-${Ae[0].id}`);let St=document.createElement("div");St.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",St.setAttribute("data-persona-tool-group","true");let vt=document.createElement("div");vt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let $t=`Called ${Ae.length} tools`,Io=o.toolCall?.renderGroupedSummary?.({messages:Ae,toolCalls:Ae.map(Tt=>Tt.toolCall).filter(Tt=>!!Tt),defaultSummary:$t,config:o});J(vt,Io)||(vt.textContent=$t);let pt=document.createElement("div");pt.className="persona-tool-group-stack persona-flex persona-flex-col";let de=o.features?.toolCallDisplay?.groupedMode==="summary";St.appendChild(vt),de||St.appendChild(pt),dt.appendChild(St),Et[0].before(dt),Et.forEach((Tt,Vt)=>{if(de){Tt.remove();return}let Dt=document.createElement("div");Dt.className="persona-tool-group-item persona-relative",Dt.setAttribute("data-persona-tool-group-item","true"),Vt<Et.length-1&&Dt.setAttribute("data-persona-tool-group-connector","true"),Dt.appendChild(Tt),pt.appendChild(Dt)})})}Tu(Mo,F);let it=g.some(W=>W.role==="assistant"&&W.streaming),qt=g[g.length-1],Bt=qt?.role==="assistant"&&!qt.streaming&&qt.variant!=="approval";if(yn&&g.some(W=>W.role==="user")&&!it&&!Bt){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:Er},Fe=s.find(_e=>_e.renderLoadingIndicator),Ae=null;if(Fe?.renderLoadingIndicator&&(Ae=Fe.renderLoadingIndicator(W)),Ae===null&&o.loadingIndicator?.render&&(Ae=o.loadingIndicator.render(W)),Ae===null&&(Ae=Er()),Ae){let _e=document.createElement("div"),Et=o.loadingIndicator?.showBubble!==!1;_e.className=Et?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_e.setAttribute("data-typing-indicator","true"),_e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",_e.appendChild(Ae);let dt=document.createElement("div");dt.className="persona-flex",dt.id="wrapper-typing-indicator",dt.setAttribute("data-wrapper-id","typing-indicator"),dt.appendChild(_e),x.appendChild(dt)}}if(!yn&&g.length>0){let W=g[g.length-1],Fe={config:o,lastMessage:W,messageCount:g.length},Ae=s.find(Et=>Et.renderIdleIndicator),_e=null;if(Ae?.renderIdleIndicator&&(_e=Ae.renderIdleIndicator(Fe)),_e===null&&o.loadingIndicator?.renderIdle&&(_e=o.loadingIndicator.renderIdle(Fe)),_e){let Et=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;Et.className=dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Et.setAttribute("data-idle-indicator","true"),Et.appendChild(_e);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-idle-indicator",St.setAttribute("data-wrapper-id","idle-indicator"),St.appendChild(Et),x.appendChild(St)}}if(za(l,x),ce.length>0)for(let{messageId:W,fingerprint:Fe,bubble:Ae}of ce){let _e=l.querySelector(`#wrapper-${W}`);_e&&Ae!==null&&(_e.replaceChildren(Ae),_e.setAttribute("data-bubble-fp",Fe),or.set(W,Fe))}if(or.size>0)for(let W of or.keys())F.has(W)||or.delete(W);if(se.length>0)for(let{messageId:W,fingerprint:Fe,bubble:Ae}of se){let _e=l.querySelector(`#wrapper-${W}`);_e&&Ae!==null&&(_e.replaceChildren(Ae),_e.setAttribute("data-bubble-fp",Fe),ko.set(W,Fe))}if(ko.size>0)for(let W of ko.keys())F.has(W)||ko.delete(W);if(yt.length>0)for(let{messageId:W,fingerprint:Fe,bubble:Ae}of yt){let _e=l.querySelector(`#wrapper-${W}`);_e&&Ae!==null&&(_e.replaceChildren(Ae),_e.setAttribute("data-bubble-fp",Fe),Jn.set(W,Fe))}if(Jn.size>0)for(let W of Jn.keys())F.has(W)||Jn.delete(W)},zr=(l,g,b)=>{wg(l,g,b),Oc()},qr=null,Ag=()=>{if(qr)return;let l=b=>{let x=b.composedPath();x.includes(Ie)||Ye&&x.includes(Ye)||mt(!1,"user")};qr=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},ed=()=>{if(!qr)return;(e.ownerDocument??document).removeEventListener("pointerdown",qr,!0),qr=null};Ke.push(()=>ed());let Vr=null,Sg=()=>{if(Vr)return;let l=b=>{b.key==="Escape"&&(b.isComposing||mt(!1,"user"))};Vr=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},td=()=>{if(!Vr)return;(e.ownerDocument??document).removeEventListener("keydown",Vr,!0),Vr=null};Ke.push(()=>td());let Kr=!1,nd=new Set,Tg=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},sr=()=>{if(!Q())return;let l=ke.peekBanner,g=ke.peekTextNode;if(!l||!g)return;if(j){l.classList.remove("persona-pill-peek--visible");return}let b=$?.getMessages()??[],x;for(let Bt=b.length-1;Bt>=0;Bt--){let W=b[Bt];if(W.role==="assistant"&&W.content){x=W;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let T=x.content,P=!!x.streaming,J=Tg(),F=Ga(J),G=F.type!=="none"?Sr(F.type,J?.plugins):null,re=G?.isAnimating?.(x)===!0,ce=G!==null&&(P||re);ce&&G&&!nd.has(G.name)&&(Qa(G,e),nd.add(G.name));let se=ce&&G?.containerClass?G.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==se&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),se&&we!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),ce?(g.style.setProperty("--persona-stream-step",`${F.speed}ms`),g.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ge=ce?Ja(T,F.buffer,G,x,P):T;if(ce&&F.placeholder==="skeleton"&&P&&(!Ge||!Ge.trim())){let Bt=document.createElement("div"),W=Rs();W.classList.add("persona-pill-peek__skeleton"),Bt.appendChild(W),za(g,Bt)}else{let Bt=Math.max(0,Ge.length-100),W=Ge.length>100?Ge.slice(-100):Ge,Fe=$n(W);if(!ce||!G){let Ae=Ge.length>100?`\u2026${W}`:W;g.textContent!==Ae&&(g.textContent=Ae)}else{let Ae=Fe;(G.wrap==="char"||G.wrap==="word")&&(Ae=Ps(Fe,G.wrap,`peek-${x.id}`,{skipTags:G.skipTags,startIndex:Bt}));let _e=document.createElement("div");if(_e.innerHTML=Ae,G.useCaret&&W.length>0){let Et=Xa(),dt=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),St=dt[dt.length-1];St?.parentNode?St.parentNode.insertBefore(Et,St.nextSibling):_e.appendChild(Et)}za(g,_e),G.onAfterRender?.({container:g,bubble:l,messageId:x.id,message:x,speed:F.speed,duration:F.duration})}}let qt=yn||Kr;l.classList.toggle("persona-pill-peek--visible",qt)};if(Q()){let l=ke.peekBanner;if(l){let x=T=>{T.preventDefault(),T.stopPropagation(),mt(!0,"user")};l.addEventListener("pointerdown",x),Ke.push(()=>{l.removeEventListener("pointerdown",x)})}let g=()=>{Kr||(Kr=!0,sr())},b=()=>{Kr&&(Kr=!1,sr())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",b),Ke.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",b)}),Ye&&(Ye.addEventListener("pointerenter",g),Ye.addEventListener("pointerleave",b),Ke.push(()=>{Ye.removeEventListener("pointerenter",g),Ye.removeEventListener("pointerleave",b)}))}let Eg=l=>{let g=o.launcher?.composerBar??{},b=g.expandedSize??"anchored",x=g.bottomOffset??"16px",T=g.collapsedMaxWidth,P=g.expandedMaxWidth??"880px",J=g.expandedTopOffset??"5vh",F=g.modalMaxWidth??"880px",G=g.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",se=Ie.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Ye){let we=Ye.style;we.bottom=x,we.width=T??""}if(l&&b!=="fullscreen"){if(b==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=F,se.maxWidth=re,se.maxHeight=G,se.height=G;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${x} + ${ce})`,se.top=J,se.width=P,se.maxWidth=re}},Gr=()=>{if(!D())return;if(Q()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ce=j?"expanded":"collapsed";Ie.dataset.state=ce,Ie.dataset.expandedSize=re,Ye&&(Ye.dataset.state=ce,Ye.dataset.expandedSize=re),Ie.style.removeProperty("display"),Ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Eg(j),fe.style.display=j?"flex":"none",Ys(),j?(Ag(),Sg()):(ed(),td()),sr();return}let l=Ht(o),g=e.ownerDocument.defaultView??window,b=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,T=g.innerWidth<=b,P=x&&T&&A,J=sn(o).reveal;j?(Ie.style.removeProperty("display"),Ie.style.display=l?"flex":"",Ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":zt&&(zt.style.display="none")):(l?l&&(J==="overlay"||J==="push")&&!P?(Ie.style.removeProperty("display"),Ie.style.display="flex",Ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ie.style.setProperty("display","none","important"),Ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ie.style.display="",Ie.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=l?"none":"":zt&&(zt.style.display=l?"none":""))},mt=(l,g="user")=>{if(!D()||j===l)return;let b=j;j=l,Gr();let x=(()=>{let P=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,re=J.innerWidth<=G,ce=Ht(o)&&F&&re,se=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||F&&re&&A||ce||se})();if(j&&x){if(!Sn){let P=e.getRootNode(),J=P instanceof ShadowRoot?P.host:e.closest(".persona-host");J&&(Sn=$l(J,o.launcher?.zIndex??Ut))}Tn||(Tn=jl(e.ownerDocument))}else j||(Sn?.(),Sn=null,Tn?.(),Tn=null);j&&(Qr(),Yc()||(Xt()==="follow"?Zn(!0):Xc()));let T={open:j,source:g,timestamp:Date.now()};j&&!b?i.emit("widget:opened",T):!j&&b&&i.emit("widget:closed",T),i.emit("widget:state",{open:j,launcherEnabled:A,voiceActive:Ze.active,streaming:$.isStreaming()})},ji=l=>{lt(l?"stop":"send"),K&&(K.disabled=l),ea.buttons.forEach(g=>{g.disabled=l}),U.dataset.personaComposerStreaming=l?"true":"false",U.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Ui=()=>{Ze.active||ye&&ye.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Ui(),200)});let od=()=>{N.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ye.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=ie.querySelector("[data-persona-intro-card]");if(l){let b=o.copy?.showWelcomeCard!==!1;l.style.display=b?"":"none",b?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!$?.isStreaming()&&(ue.textContent=o.copy?.sendButtonLabel??"Send"),ye.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ye.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{C(g=>({...g,sessionId:l}))}});let Po=null,Mg=()=>{Po==null&&(Po=setInterval(()=>{let l=xe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Po),Po=null;return}let g=Date.now();l.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=Sa(g-x))})},100))},zi=(l,g)=>{if(Object.is(l,g))return!0;if(l===null||g===null||typeof l!="object"||typeof g!="object")return!1;if(Array.isArray(l)||Array.isArray(g))return!Array.isArray(l)||!Array.isArray(g)||l.length!==g.length?!1:l.every((J,F)=>zi(J,g[F]));let b=l,x=g,T=Object.keys(b),P=Object.keys(x);return T.length===P.length&&T.every(J=>Object.prototype.hasOwnProperty.call(x,J)&&zi(b[J],x[J]))},rd=l=>{let{content:g,rawContent:b,llmContent:x,...T}=l;return T},qi=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!fi(l),kg=(l,g,b)=>{if(l.length!==g.length)return!1;let x=l[b.index],T=g[b.index];return!x||!T||x.id!==b.id||T.id!==b.id?!1:(!Object.is(x.content,T.content)||!Object.is(x.rawContent,T.rawContent)||!Object.is(x.llmContent,T.llmContent))&&qi(x)&&qi(T)&&zi(rd(x),rd(T))},sd=null,ar=null,Ro=null,On=null,sa=l=>{sd=l;let g,b;ar=null;for(let T=l.length-1;T>=0;T-=1){let P=l[T];if(!g&&P.role==="user"&&(g=P),!b&&P.role==="assistant"&&(b=P),!ar&&qi(P)&&(ar={index:T,id:P.id}),g&&b&&ar)break}zr(xe,l,De),Bl(xe,mn.artifacts,{suppressTransition:yn}),Mg(),Ri(l),Zn(!yn),Cg(l),l.length===0&&(Ur(),_r=!0,Bi=!1),!Wi||na?(Wi=!0,Hi=g?.id??null,Di=b?.id??null):g&&g.id!==Hi?(Hi=g.id,vg(g.id)):b&&b.id!==Di&&xg(),b&&(Di=b.id);let x=Ze.lastUserMessageId;g&&g.id!==x&&(Ze.lastUserMessageId=g.id,i.emit("user:message",g)),Ze.lastUserMessageWasVoice=!!g?.viaVoice,Fi(l),sr()},Vi=()=>{On!==null&&(cancelAnimationFrame(On),On=null);let l=Ro;Ro=null,l&&sa(l)},ad=()=>{On!==null&&cancelAnimationFrame(On),On=null,Ro=null},Lg=l=>{let g=Ro??sd;if(yn&&g&&ar&&kg(g,l,ar)){Ro=l,On===null&&(On=requestAnimationFrame(()=>{On=null;let b=Ro;Ro=null,b&&sa(b)}));return}if(l.length===0){ad(),sa(l);return}Vi(),sa(l)};$=new vs(o,{onMessagesChanged(l){Lg(l)},onStatusChanged(l){let g=o.statusIndicator??{};ht(M,(x=>x==="idle"?g.idleText??Wt.idle:x==="connecting"?g.connectingText??Wt.connecting:x==="connected"?g.connectedText??Wt.connected:x==="error"?g.errorText??Wt.error:x==="paused"?g.pausedText??Wt.paused:x==="resuming"?g.resumingText??Wt.resuming:Wt[x])(l),g,l)},onStreamingChanged(l){l||($?.getMessages().length===0?ad():Vi()),yn=l,ji(l),$&&zr(xe,$.getMessages(),De),l||Zn(!0),tn(),Lc(l?"Responding\u2026":"Response complete."),sr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Nn(),lr();break;case"processing":Nn(),_g();break;case"speaking":Nn(),$g();break;default:l==="idle"&&$.isBargeInActive()?(Nn(),lr(),K?.setAttribute("aria-label","End voice session")):(Ze.active=!1,Nn(),Dn("system"),vn());break}},onArtifactsState(l){mn=l,l.artifacts.length===0&&(er=!1),Bl(xe,l.artifacts,{suppressTransition:yn}),Bn(),Fi()},onReconnect(l){let{executionId:g,lastEventId:b}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:g,after:b}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:g,after:b,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:g,after:b})}}),ft.current=$,Ke.push(()=>$.cancel());let Ki=null;if($.onReadAloudChange((l,g)=>{Bc=l,Dc=g,Oc();let b=l??Ki;l&&(Ki=l);let x=b?$.getMessages().find(T=>T.id===b)??null:null;i.emit("message:read-aloud",{messageId:b,message:x,state:g,timestamp:Date.now()}),g==="idle"&&(Ki=null)}),Wi=!0,o.voiceRecognition?.provider?.type==="runtype")try{$.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&$.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Oe||o.onSSEEvent)&&$.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),$e?.processEvent(l,g),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let id=()=>{o.resume&&typeof o.reconnectStream=="function"&&$.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=fc(l.metadata),R.syncFromMetadata()),l.messages?.length){na=!0;try{$.hydrateMessages(l.messages)}finally{na=!1}}l.artifacts?.length&&$.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>id()):id();let ld=()=>{!Q()||j||!(o.launcher?.composerBar?.expandOnSubmit??!0)||mt(!0,"auto")},Pg=(l,g)=>l?g?{refs:[...l.refs,...g.refs],finalize:async()=>{let[b,x]=await Promise.allSettled([l.finalize(),g.finalize()]),T=[];return b.status==="fulfilled"?T.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),x.status==="fulfilled"?T.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),fC(T)}}:l:g,Rg=()=>{let g=ye.getInlineMessageFields?.();return g&&g.contentSegments.some(x=>x.kind==="mention")?g.contentSegments:void 0},Jr=!1,Ig=async l=>{let g=ye.value.trim(),b=Mt?.hasAttachments()??!1,x=g?await(Zt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(x?.kind==="action"){ye.value="",ye.style.height="auto",Xr(),Zt?.clear();return}let T=Zt?.collectForSubmit()??null,P=x?.kind==="server"?x.mentions:null,J=Pg(T,P),F=x?.kind==="prompt"?x.sendText:g,G=!!T&&T.refs.length>0;if(!F&&!b&&!G&&!P)return;ld();let re;b&&(re=[],re.push(...Mt.getContentParts()),F&&re.push(Uo(F)));let ce=x?.kind==="prompt"?void 0:Rg();ye.value="",ye.style.height="auto",Xr(),$.sendMessage(F,{contentParts:re,mentions:J??void 0,contentSegments:ce,viaVoice:l?.viaVoice}),b&&Mt.clearAttachments(),T&&Zt?.clear()},Gi=async l=>{if(!Jr){Jr=!0;try{await Ig(l)}finally{Jr=!1}}},cd=l=>{if(l.preventDefault(),$.isStreaming()){$.cancel(),$e?.reset(),He?.update();return}Jr||Gi()},Wg=()=>o.features?.composerHistory!==!1,Ji={...Nl},Xi=!1,Xr=()=>{Ji={...Nl}},Hg=()=>$.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),Bg=l=>{if(!ye)return;Xi=!0,ye.value=l,ye.dispatchEvent(new Event("input",{bubbles:!0})),Xi=!1;let g=ye.value.length;ye.setSelectionRange(g,g)},Dg=l=>{Xi||(l.isComposing||Zt?.handleInput(l.inputType??void 0),Xr())},Og=l=>{if(ye&&!(!l.isComposing&&Zt?.handleKeydown(l))){if(Wg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=ye.selectionStart===0&&ye.selectionEnd===0,b=xu({direction:l.key==="ArrowUp"?"up":"down",history:Hg(),currentValue:ye.value,atStart:g,state:Ji});if(Ji=b.state,b.handled){l.preventDefault(),b.value!==void 0&&Bg(b.value);return}}if(l.key==="Enter"&&!l.shiftKey){if($.isStreaming()){l.preventDefault();return}if(Jr){l.preventDefault();return}Xr(),l.preventDefault(),ue.click()}}},dd=l=>{l.key!=="Escape"||l.isComposing||$.isStreaming()&&l.composedPath().includes(fe)&&($.cancel(),$e?.reset(),He?.update(),Xr(),l.preventDefault(),l.stopImmediatePropagation())},Ng=async l=>{if(o.attachments?.enabled!==!0||!Mt)return;let g=cC(l.clipboardData);g.length!==0&&(l.preventDefault(),await Mt.handleFiles(g))},dn=null,En=!1,ir=null,At=null,pd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,aa=(l="user")=>{if(En||$.isStreaming())return;let g=pd();if(!g)return;dn=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;dn.continuous=!0,dn.interimResults=!0,dn.lang="en-US";let T=ye.value;dn.onresult=P=>{let J="",F="";for(let re=0;re<P.results.length;re++){let ce=P.results[re],se=ce[0].transcript;ce.isFinal?J+=se+" ":F=se}let G=T+J+F;ye.value=G,ir&&clearTimeout(ir),(J||F)&&(ir=window.setTimeout(()=>{ye.value.trim()&&dn&&En&&(eo(),Gi({viaVoice:!0}))},x))},dn.onerror=P=>{P.error!=="no-speech"&&eo()},dn.onend=()=>{if(En){let P=ye.value.trim();P&&P!==T.trim()&&Gi({viaVoice:!0}),eo()}};try{if(dn.start(),En=!0,Ze.active=!0,l!=="system"&&(Ze.manuallyDeactivated=!1),Dn(l),vn(),K){let P=o.voiceRecognition??{};At={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??o.sendButton?.size??"40")||24};let J=P.recordingBackgroundColor,F=P.recordingIconColor,G=P.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let re=K.querySelector("svg");re&&re.setAttribute("stroke",F)}G&&(K.style.borderColor=G),K.setAttribute("aria-label","Stop voice recognition")}}catch{eo("system")}},eo=(l="user")=>{if(En){if(En=!1,ir&&(clearTimeout(ir),ir=null),dn){try{dn.stop()}catch{}dn=null}if(Ze.active=!1,Dn(l),vn(),K){if(K.classList.remove("persona-voice-recording"),At){K.style.backgroundColor=At.backgroundColor,K.style.color=At.color,K.style.borderColor=At.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",At.color||"currentColor"),At=null}K.setAttribute("aria-label","Start voice recognition")}}},Fg=(l,g)=>{let b=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",T=l?.provider?.type==="custom";if(!(b||x||T))return null;let J=m("div","persona-send-button-wrapper"),F=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let G=l?.iconName??"mic",re=g?.size??"40px",ce=l?.iconSize??re,se=parseFloat(ce)||24,we=l?.backgroundColor??g?.backgroundColor,Ge=l?.iconColor??g?.textColor;F.style.width=ce,F.style.height=ce,F.style.minWidth=ce,F.style.minHeight=ce,F.style.fontSize="18px",F.style.lineHeight="1",Ge?F.style.color=Ge:F.style.color="var(--persona-text, #111827)";let it=te(G,se,Ge||"currentColor",1.5);it?F.appendChild(it):F.textContent="\u{1F3A4}",we?F.style.backgroundColor=we:F.style.backgroundColor="",l?.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l?.borderColor&&(F.style.borderColor=l.borderColor),l?.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l?.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),J.appendChild(F);let qt=l?.tooltipText??"Start voice recognition";if((l?.showTooltip??!1)&&qt){let W=m("div","persona-send-button-tooltip");W.textContent=qt,J.appendChild(W)}return{micButton:F,micButtonWrapper:J}},Qi=()=>{if(!K||At)return;let l=o.voiceRecognition??{};At={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Yi=(l,g)=>{if(!K)return;let b=K.querySelector("svg");b&&b.remove();let x=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),T=te(l,x,g,1.5);T&&K.appendChild(T)},ia=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},lr=()=>{if(!K)return;Qi();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,b=l.recordingIconColor,x=l.recordingBorderColor;if(ia(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b??"var(--persona-voice-recording-indicator, #ffffff)",b){let T=K.querySelector("svg");T&&T.setAttribute("stroke",b)}x&&(K.style.borderColor=x),K.setAttribute("aria-label","Stop voice recognition")},_g=()=>{if(!K)return;Qi();let l=o.voiceRecognition??{},g=$.getVoiceInterruptionMode(),b=l.processingIconName??"loader",x=l.processingIconColor??At?.color??"",T=l.processingBackgroundColor??At?.backgroundColor??"",P=l.processingBorderColor??At?.borderColor??"";ia(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=T,K.style.borderColor=P;let J=x||"currentColor";K.style.color=J,Yi(b,J),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},$g=()=>{if(!K)return;Qi();let l=o.voiceRecognition??{},g=$.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",x=l.speakingIconName??b,T=l.speakingIconColor??(g==="barge-in"?l.recordingIconColor??At?.color??"":At?.color??""),P=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),J=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":At?.borderColor??"");ia(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=P,K.style.borderColor=J;let F=T||"currentColor";K.style.color=F,Yi(x,F);let G=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",G),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},Nn=()=>{K&&(ia(),At&&(K.style.backgroundColor=At.backgroundColor??"",K.style.color=At.color??"",K.style.borderColor=At.borderColor??"",Yi(At.iconName,At.color||"currentColor"),At=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},la=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=$.getVoiceStatus(),g=$.getVoiceInterruptionMode();if(g==="none"&&(l==="processing"||l==="speaking"))return;if(g==="cancel"&&(l==="processing"||l==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{Ze.active=!1,Ze.manuallyDeactivated=!0,vn(),Dn("user"),Nn()});return}$.toggleVoice().then(()=>{Ze.active=$.isVoiceActive(),Ze.manuallyDeactivated=!$.isVoiceActive(),vn(),Dn("user"),$.isVoiceActive()?lr():Nn()});return}if(En){let l=ye.value.trim();Ze.manuallyDeactivated=!0,vn(),eo("user"),l&&(ye.value="",ye.style.height="auto",$.sendMessage(l))}else Ze.manuallyDeactivated=!1,vn(),aa("user")};Rc=la,K&&(K.addEventListener("click",la),Ke.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Nn()):eo("system"),K&&K.removeEventListener("click",la)}));let jg=i.on("assistant:complete",()=>{zc&&(Ze.active||Ze.manuallyDeactivated||zc==="assistant"&&!Ze.lastUserMessageWasVoice||setTimeout(()=>{!Ze.active&&!Ze.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?$.toggleVoice().then(()=>{Ze.active=$.isVoiceActive(),Dn("auto"),$.isVoiceActive()&&lr()}):aa("auto"))},600))});Ke.push(jg);let Ug=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});Ke.push(Ug);let ud=()=>{mt(!j,"user")},Ft=null,zt=null;if(A&&!Q()){let{instance:l,element:g}=ql({config:o,plugins:s,onToggle:ud});Ft=l,l||(zt=g)}Ft?e.appendChild(Ft.element):zt&&e.appendChild(zt),Gr(),Ri(),od(),ji($.isStreaming()),Yc()||(Xt()==="follow"?Zn(!0):Xc()),fg(),_&&(!A||Q()?setTimeout(()=>Ui(),0):j&&setTimeout(()=>Ui(),200));let Qr=()=>{if(Q()){Zo(),Gr();return}let l=Ht(o),g=o.launcher?.sidebarMode??!1,b=l||g||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640,J=x.innerWidth<=P,F=T&&J&&A;try{if(F){Dr(),Or=Qs();return}let G=!1;q&&(q=!1,Dr(),G=!0);let re=Qs();if(!G&&re!==Or&&(Dr(),G=!0),Or=re,G&&Li(),!A&&!l){he.style.height="",he.style.width="";return}if(!g&&!l){let se=o?.launcher?.width??o?.launcherWidth??fn;he.style.width=se,he.style.maxWidth=se}if(Xs(),!b){let ce=x.innerHeight,se=64,we=o.launcher?.heightOffset??0,Ge=Math.max(200,ce-se),yt=Math.min(640,Ge),it=Math.max(200,yt-we);he.style.height=`${it}px`}}finally{if(Zo(),Gr(),j&&A){let re=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ce=o.launcher?.sidebarMode??!1,se=o.launcher?.mobileFullscreen??!0,we=Ht(o)&&se&&re,Ge=ce||se&&re&&A||we;if(Ge&&!Tn){let yt=e.getRootNode(),it=yt instanceof ShadowRoot?yt.host:e.closest(".persona-host");it&&!Sn&&(Sn=$l(it,o.launcher?.zIndex??Ut)),Tn=jl(e.ownerDocument)}else Ge||(Sn?.(),Sn=null,Tn?.(),Tn=null)}}};Qr();let fd=e.ownerDocument.defaultView??window;if(fd.addEventListener("resize",Qr),Ke.push(()=>fd.removeEventListener("resize",Qr)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Zo()});l.observe(U),Ke.push(()=>l.disconnect())}ln=ie.scrollTop;let gd=In(ie),zg=()=>{let l=ie.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??ie.ownerDocument.getSelection()},Zi=()=>Eu(zg(),ie),md=()=>{let l=ie.scrollTop,g=In(ie),b=g<gd;if(gd=g,!qn()){ln=l,tn();return}let{action:x,nextLastScrollTop:T}=Va({following:en.isFollowing(),currentScrollTop:l,lastScrollTop:ln,nearBottom:mo(ie,oa),userScrollThreshold:pg,isAutoScrolling:cn||ta||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=T,x==="resume"){Zi()||Yn();return}x==="pause"&&jr()};if(ie.addEventListener("scroll",md,{passive:!0}),Ke.push(()=>ie.removeEventListener("scroll",md)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{bg()});l.observe(xe),l.observe(ie),Ke.push(()=>l.disconnect())}let hd=()=>{qn()&&en.isFollowing()&&Zi()&&jr()},yd=ie.ownerDocument;yd.addEventListener("selectionchange",hd),Ke.push(()=>{yd.removeEventListener("selectionchange",hd)});let qg=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),bd=l=>{Ec()&&qn()&&en.isFollowing()&&qg.has(l.key)&&jr()},vd=l=>{if(!Ec()||!qn()||!en.isFollowing())return;let g=l.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&jr()};ie.addEventListener("keydown",bd),ie.addEventListener("focusin",vd),Ke.push(()=>{ie.removeEventListener("keydown",bd),ie.removeEventListener("focusin",vd)});let xd=l=>{if(!qn())return;let g=Ka({following:en.isFollowing(),deltaY:l.deltaY,nearBottom:mo(ie,oa),resumeWhenNearBottom:!0});g==="pause"?jr():g==="resume"&&!Zi()&&Yn()};ie.addEventListener("wheel",xd,{passive:!0}),Ke.push(()=>ie.removeEventListener("wheel",xd)),Rt.addEventListener("click",()=>{Ur(),ie.scrollTop=ie.scrollHeight,ln=ie.scrollTop,Yn(),Zn(!0),tn()}),Ke.push(()=>Rt.remove()),Ke.push(()=>{Kc(),Ur()});let Cd=()=>{S&&(Eo&&(S.removeEventListener("click",Eo),Eo=null),D()?(S.style.display="",Eo=()=>{mt(!1,"user")},S.addEventListener("click",Eo)):S.style.display="none")};Cd(),(()=>{let{clearChatButton:l}=ke;l&&l.addEventListener("click",()=>{$.clearMessages(),Mo.clear(),Yn(),$o(ke.composerOverlay);try{localStorage.removeItem(Rr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Rr}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Rr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&Ni(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},R.syncFromMetadata(),Oe?.clear(),$e?.reset(),He?.update()})})(),X&&X.addEventListener("submit",cd);let wd=[["keydown",Og],["input",Dg],["paste",Ng],["focus",ag]],Ad=l=>{if(l)for(let[g,b]of wd)l.addEventListener(g,b)},Sd=l=>{if(l)for(let[g,b]of wd)l.removeEventListener(g,b)};Ad(ye),Zt?.onComposerSwap((l,g)=>{Sd(g),ye=l,Ad(l)});let Td=e.ownerDocument??document;Td.addEventListener("keydown",dd,!0);let Ed="persona-attachment-drop-active",Yr=0,el=()=>{Yr=0,fe.classList.remove(Ed)},cr=()=>o.attachments?.enabled===!0&&Mt!==null,Md=l=>{!gi(l.dataTransfer)||!cr()||(Yr++,Yr===1&&fe.classList.add(Ed))},kd=l=>{!gi(l.dataTransfer)||!cr()||(Yr--,Yr<=0&&el())},Ld=l=>{!gi(l.dataTransfer)||!cr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Pd=l=>{if(!gi(l.dataTransfer)||!cr())return;l.preventDefault(),l.stopPropagation(),el();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&Mt.handleFiles(g)},to=!0;fe.addEventListener("dragenter",Md,to),fe.addEventListener("dragleave",kd,to),e.addEventListener("dragover",Ld,to),e.addEventListener("drop",Pd,to);let ca=e.ownerDocument,Rd=l=>{cr()&&l.preventDefault()},Id=l=>{cr()&&l.preventDefault()};ca.addEventListener("dragover",Rd),ca.addEventListener("drop",Id),Ke.push(()=>{X&&X.removeEventListener("submit",cd),Sd(ye),Td.removeEventListener("keydown",dd,!0),Zt?.destroy()}),Ke.push(()=>{fe.removeEventListener("dragenter",Md,to),fe.removeEventListener("dragleave",kd,to),e.removeEventListener("dragover",Ld,to),e.removeEventListener("drop",Pd,to),ca.removeEventListener("dragover",Rd),ca.removeEventListener("drop",Id),el()}),Ke.push(()=>{$.cancel()}),Ft?Ke.push(()=>{Ft?.destroy()}):zt&&Ke.push(()=>{zt?.remove()});let It={update(l){let g=o.toolCall,b=o.messageActions,x=o.layout?.messages,T=o.colorScheme,P=o.loadingIndicator,J=o.iterationDisplay,F=o.features?.showReasoning,G=o.features?.showToolCalls,re=o.features?.toolCallDisplay,ce=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type;o=di(o,l),Ys(),xr(e,o),_s(e,o),$s(e,o),Bn(),o.colorScheme!==T&&Uc();let we=ci.getForInstance(o.plugins);s.length=0,s.push(...we),A=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,ae=o.features?.showReasoning??!0,ve=o.features?.showToolCalls??!0,le=o.features?.scrollToBottom??{};let Ge=Xt();Z=o.features?.scrollBehavior??{},Ge!==Xt()&&(Ur(),Yn()),Pc(),tn();let yt=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!yt){if(Oe||(pe=new Ns(me),Oe=new Os(Pe,pe),$e=$e??new Fs,pe.open().then(()=>Oe?.restore()).catch(()=>{}),$.setSSEEventCallback((ee,Qe)=>{o.onSSEEvent?.(ee,Qe),$e?.processEvent(ee,Qe),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Qe)})})),!at&&B){let ee=o.features?.eventStream?.classNames,Qe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");at=m("button",Qe),at.style.width="28px",at.style.height="28px",at.style.color=Gt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let bt=te("activity","18px","currentColor",1.5);bt&&at.appendChild(bt);let Ve=ke.clearChatButtonWrapper,st=ke.closeButtonWrapper,jt=Ve||st;jt&&jt.parentNode===B?B.insertBefore(at,jt):B.appendChild(at),at.addEventListener("click",()=>{je?Hr():Ti()})}}else!Y&&yt&&(Hr(),at&&(at.remove(),at=null),Oe?.clear(),pe?.destroy(),Oe=null,pe=null,$e?.reset(),$e=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!Ft&&!zt){let{instance:ee,element:Qe}=ql({config:o,plugins:s,onToggle:ud});Ft=ee,ee||(zt=Qe),e.appendChild(Qe)}Ft&&Ft.update(o),H&&o.launcher?.title!==void 0&&(H.textContent=o.launcher.title),V&&o.launcher?.subtitle!==void 0&&(V.textContent=o.launcher.subtitle);let it=o.layout?.header;if(it?.layout!==z&&B){let ee=it?Hs(o,it,{showClose:D(),onClose:()=>mt(!1,"user")}):bo({config:o,showClose:D(),onClose:()=>mt(!1,"user")});ct.replaceHeader(ee),B=ct.header.element,k=ct.header.iconHolder,H=ct.header.headerTitle,V=ct.header.headerSubtitle,S=ct.header.closeButton,z=it?.layout}else if(it){if(k&&(k.style.display=it.showIcon===!1?"none":""),H&&(H.style.display=it.showTitle===!1?"none":""),V&&(V.style.display=it.showSubtitle===!1?"none":""),S){let ee=D()&&it.showCloseButton!==!1;S.style.display=ee?"":"none"}if(ke.clearChatButtonWrapper){let ee=it.showClearChat;if(ee!==void 0){ke.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Qe}=ke;Qe&&!Qe.classList.contains("persona-absolute")&&(ee?Qe.classList.remove("persona-ml-auto"):Qe.classList.add("persona-ml-auto"))}}}let Bt=o.layout?.showHeader!==!1;B&&(B.style.display=Bt?"":"none");let W=o.layout?.showFooter!==!1;U&&(U.style.display=W?"":"none"),Zo(),tn(),A!==w?A?mt(I,"auto"):(j=!0,Gr()):I!==O&&mt(I,"auto"),O=I,w=A,Qr(),Cd();let _e=JSON.stringify(o.toolCall)!==JSON.stringify(g),Et=JSON.stringify(o.messageActions)!==JSON.stringify(b),dt=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),St=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,vt=o.iterationDisplay!==J,$t=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ce);(_e||Et||dt||St||vt||$t)&&$&&(Ii++,zr(xe,$.getMessages(),De));let pt=o.features?.streamAnimation?.type;if(pt!==se&&pt&&pt!=="none"){let ee=Sr(pt,o.features?.streamAnimation?.plugins);ee&&Qa(ee,e)}let de=o.launcher??{},Tt=de.headerIconHidden??!1,Vt=o.layout?.header?.showIcon,Dt=Tt||Vt===!1,rt=de.headerIconName,qe=de.headerIconSize??"48px";if(k){let ee=fe.querySelector(".persona-border-b-persona-divider"),Qe=ee?.querySelector(".persona-flex-col");if(Dt)k.style.display="none",ee&&Qe&&!ee.contains(Qe)&&ee.insertBefore(Qe,ee.firstChild);else{if(k.style.display="",k.style.height=qe,k.style.width=qe,ee&&Qe&&(ee.contains(k)?k.nextSibling!==Qe&&(k.remove(),ee.insertBefore(k,Qe)):ee.insertBefore(k,Qe)),rt){let Ve=parseFloat(qe)||24,st=te(rt,Ve*.6,"currentColor",1);st?k.replaceChildren(st):k.textContent=de.agentIconText??"\u{1F4AC}"}else if(de.iconUrl){let Ve=k.querySelector("img");if(Ve)Ve.src=de.iconUrl,Ve.style.height=qe,Ve.style.width=qe;else{let st=document.createElement("img");st.src=de.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=qe,st.style.width=qe,k.replaceChildren(st)}}else{let Ve=k.querySelector("svg"),st=k.querySelector("img");(Ve||st)&&k.replaceChildren(),k.textContent=de.agentIconText??"\u{1F4AC}"}let bt=k.querySelector("img");bt&&(bt.style.height=qe,bt.style.width=qe)}}let nt=o.layout?.header?.showTitle,Lt=o.layout?.header?.showSubtitle;if(H&&(H.style.display=nt===!1?"none":""),V&&(V.style.display=Lt===!1?"none":""),S){let ee=D()&&o.layout?.header?.showCloseButton!==!1;S.style.display=ee?"":"none";let Qe=de.closeButtonSize??"32px",bt=de.closeButtonPlacement??"inline";S.style.height=Qe,S.style.width=Qe;let{closeButtonWrapper:Ve}=ke,st=bt==="top-right",jt=Ve?.classList.contains("persona-absolute");if(Ve&&st!==jt)if(Ve.remove(),st)Ve.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(Ve);else{let ze=de.clearChat?.placement??"inline",Nt=de.clearChat?.enabled??!0;Ve.className=Nt&&ze==="inline"?"":"persona-ml-auto";let Yt=fe.querySelector(".persona-border-b-persona-divider");Yt&&Yt.appendChild(Ve)}if(S.style.color=de.closeButtonColor||Gt.actionIconColor,de.closeButtonBackgroundColor?(S.style.backgroundColor=de.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),de.closeButtonBorderWidth||de.closeButtonBorderColor){let ze=de.closeButtonBorderWidth||"0px",Nt=de.closeButtonBorderColor||"transparent";S.style.border=`${ze} solid ${Nt}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");de.closeButtonBorderRadius?(S.style.borderRadius=de.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),de.closeButtonPaddingX?(S.style.paddingLeft=de.closeButtonPaddingX,S.style.paddingRight=de.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),de.closeButtonPaddingY?(S.style.paddingTop=de.closeButtonPaddingY,S.style.paddingBottom=de.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let on=de.closeButtonIconName??"x",xn=de.closeButtonIconText??"\xD7";S.innerHTML="";let _t=te(on,"28px","currentColor",1);_t?(_t.style.display="block",S.appendChild(_t)):S.textContent=xn;let kt=de.closeButtonTooltipText??"Close chat",rn=de.closeButtonShowTooltip??!0;if(S.setAttribute("aria-label",kt),Ve&&(Ve._cleanupTooltip&&(Ve._cleanupTooltip(),delete Ve._cleanupTooltip),rn&&kt)){let ze=null,Nt=()=>{if(ze||!S)return;let Do=S.ownerDocument,ns=Do.body;if(!ns)return;ze=kn(Do,"div","persona-clear-chat-tooltip"),ze.textContent=kt;let os=kn(Do,"div");os.className="persona-clear-chat-tooltip-arrow",ze.appendChild(os);let Oo=S.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(po),ze.style.left=`${Oo.left+Oo.width/2}px`,ze.style.top=`${Oo.top-8}px`,ze.style.transform="translate(-50%, -100%)",ns.appendChild(ze)},Yt=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};Ve.addEventListener("mouseenter",Nt),Ve.addEventListener("mouseleave",Yt),S.addEventListener("focus",Nt),S.addEventListener("blur",Yt),Ve._cleanupTooltip=()=>{Yt(),Ve&&(Ve.removeEventListener("mouseenter",Nt),Ve.removeEventListener("mouseleave",Yt)),S&&(S.removeEventListener("focus",Nt),S.removeEventListener("blur",Yt))}}}let{clearChatButton:Be,clearChatButtonWrapper:ot}=ke;if(Be){let ee=de.clearChat??{},Qe=ee.enabled??!0,bt=o.layout?.header?.showClearChat,Ve=bt!==void 0?bt:Qe,st=ee.placement??"inline";if(ot){ot.style.display=Ve?"":"none";let{closeButtonWrapper:jt}=ke;!Q()&&jt&&!jt.classList.contains("persona-absolute")&&(Ve?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let on=st==="top-right",xn=ot.classList.contains("persona-absolute");if(!Q()&&on!==xn&&Ve){if(ot.remove(),on)ot.className="persona-absolute persona-top-4 persona-z-50",ot.style.right="48px",fe.style.position="relative",fe.appendChild(ot);else{ot.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ot.style.right="";let kt=fe.querySelector(".persona-border-b-persona-divider"),rn=ke.closeButtonWrapper;kt&&rn&&rn.parentElement===kt?kt.insertBefore(ot,rn):kt&&kt.appendChild(ot)}let _t=ke.closeButtonWrapper;_t&&!_t.classList.contains("persona-absolute")&&(on?_t.classList.add("persona-ml-auto"):_t.classList.remove("persona-ml-auto"))}}if(Ve){if(!Q()){let ze=ee.size??"32px";Be.style.height=ze,Be.style.width=ze}let jt=ee.iconName??"refresh-cw",on=ee.iconColor??"";Be.style.color=on||Gt.actionIconColor,Be.innerHTML="";let xn=Q()?"14px":"20px",_t=te(jt,xn,"currentColor",1);if(_t&&(_t.style.display="block",Be.appendChild(_t)),ee.backgroundColor?(Be.style.backgroundColor=ee.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let ze=ee.borderWidth||"0px",Nt=ee.borderColor||"transparent";Be.style.border=`${ze} solid ${Nt}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");ee.borderRadius?(Be.style.borderRadius=ee.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),ee.paddingX?(Be.style.paddingLeft=ee.paddingX,Be.style.paddingRight=ee.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),ee.paddingY?(Be.style.paddingTop=ee.paddingY,Be.style.paddingBottom=ee.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let kt=ee.tooltipText??"Clear chat",rn=ee.showTooltip??!0;if(Be.setAttribute("aria-label",kt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),rn&&kt)){let ze=null,Nt=()=>{if(ze||!Be)return;let Do=Be.ownerDocument,ns=Do.body;if(!ns)return;ze=kn(Do,"div","persona-clear-chat-tooltip"),ze.textContent=kt;let os=kn(Do,"div");os.className="persona-clear-chat-tooltip-arrow",ze.appendChild(os);let Oo=Be.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(po),ze.style.left=`${Oo.left+Oo.width/2}px`,ze.style.top=`${Oo.top-8}px`,ze.style.transform="translate(-50%, -100%)",ns.appendChild(ze)},Yt=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};ot.addEventListener("mouseenter",Nt),ot.addEventListener("mouseleave",Yt),Be.addEventListener("focus",Nt),Be.addEventListener("blur",Yt),ot._cleanupTooltip=()=>{Yt(),ot&&(ot.removeEventListener("mouseenter",Nt),ot.removeEventListener("mouseleave",Yt)),Be&&(Be.removeEventListener("focus",Nt),Be.removeEventListener("blur",Yt))}}}}let nn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[pi],Wo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Pr.message,Pr.messageAndClick];R=ui({parsers:nn,handlers:Wo,getSessionMetadata:h,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),De=xf(o,R,Ee),$.updateConfig(o),zr(xe,$.getMessages(),De),Ri(),od(),ji($.isStreaming());let Wd=o.voiceRecognition?.enabled===!0,da=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Pt=o.voiceRecognition?.provider?.type==="runtype";if(Wd&&(da||Pt))if(!K||!Ue){let ee=Fg(o.voiceRecognition,o.sendButton);ee&&(K=ee.micButton,Ue=ee.micButtonWrapper,Xe.insertBefore(Ue,gn),K.addEventListener("click",la),K.disabled=$.isStreaming())}else{let ee=o.voiceRecognition??{},Qe=o.sendButton??{},bt=ee.iconName??"mic",Ve=Qe.size??"40px",st=ee.iconSize??Ve,jt=parseFloat(st)||24;K.style.width=st,K.style.height=st,K.style.minWidth=st,K.style.minHeight=st;let on=ee.iconColor??Qe.textColor;K.innerHTML="";let xn=te(bt,jt,on||"currentColor",1.5);xn?K.appendChild(xn):K.textContent="\u{1F3A4}";let _t=ee.backgroundColor??Qe.backgroundColor;_t?K.style.backgroundColor=_t:K.style.backgroundColor="",on?K.style.color=on:K.style.color="var(--persona-text, #111827)",ee.borderWidth?(K.style.borderWidth=ee.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),ee.borderColor?K.style.borderColor=ee.borderColor:K.style.borderColor="",ee.paddingX?(K.style.paddingLeft=ee.paddingX,K.style.paddingRight=ee.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),ee.paddingY?(K.style.paddingTop=ee.paddingY,K.style.paddingBottom=ee.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let kt=Ue?.querySelector(".persona-send-button-tooltip"),rn=ee.tooltipText??"Start voice recognition";if((ee.showTooltip??!1)&&rn)if(kt)kt.textContent=rn,kt.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=rn,Ue?.insertBefore(Nt,K)}else kt&&(kt.style.display="none");Ue.style.display="",K.disabled=$.isStreaming()}else K&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()&&$.toggleVoice():En&&eo());if(o.attachments?.enabled===!0){if(!We||!Te){let ee=o.attachments??{},bt=(o.sendButton??{}).size??"40px";et||(et=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),et.style.display="none",X.insertBefore(et,ye)),Le||(Le=document.createElement("input"),Le.type="file",Le.accept=(ee.allowedTypes??Un).join(","),Le.multiple=(ee.maxFiles??4)>1,Le.style.display="none",Le.setAttribute("aria-label","Attach files"),X.insertBefore(Le,ye)),We=m("div","persona-send-button-wrapper"),Te=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Te.type="button",Te.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Ve=ee.buttonIconName??"paperclip",st=bt,jt=parseFloat(st)||40,on=Math.round(jt*.6);Te.style.width=st,Te.style.height=st,Te.style.minWidth=st,Te.style.minHeight=st,Te.style.fontSize="18px",Te.style.lineHeight="1";let xn=te(Ve,on,"currentColor",1.5);xn?Te.appendChild(xn):Te.textContent="\u{1F4CE}",Te.addEventListener("click",rn=>{rn.preventDefault(),Le?.click()}),We.appendChild(Te);let _t=ee.buttonTooltipText??"Attach file",kt=m("div","persona-send-button-tooltip");kt.textContent=_t,We.appendChild(kt),Se?Se.append(We):X.appendChild(We),!Mt&&Le&&et&&(Mt=vr.fromConfig(ee),Mt.setPreviewsContainer(et),Le.addEventListener("change",async()=>{Mt&&Le?.files&&(await Mt.handleFileSelect(Le.files),Le.value="")}))}else{We.style.display="";let ee=o.attachments??{};Le&&(Le.accept=(ee.allowedTypes??Un).join(","),Le.multiple=(ee.maxFiles??4)>1),Mt&&Mt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}if(fe.querySelector(".persona-attachment-drop-overlay")?.remove(),fe.appendChild(Cf(o.attachments?.dropOverlay)),Te){let ee=o.attachments??{},Qe=ee.buttonTooltipText??"Attach file";Te.setAttribute("aria-label",Qe),Te.textContent="";let bt=parseFloat(o.sendButton?.size??"40px")||40,Ve=te(ee.buttonIconName??"paperclip",Math.round(bt*.6),"currentColor",1.5);Ve?Te.appendChild(Ve):Te.textContent="\u{1F4CE}";let st=We?.querySelector(".persona-send-button-tooltip");st&&(st.textContent=Qe)}}else We&&(We.style.display="none"),Mt&&Mt.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ot=o.sendButton??{},Zr=Ot.useIcon??!1,ua=Ot.iconText??"\u2191",dr=Ot.iconName,es=Ot.tooltipText??"Send message",tl=Ot.showTooltip??!1,Ho=Ot.size??"40px",Fn=Ot.backgroundColor,Bo=Ot.textColor;if(Zr){if(ue.style.width=Ho,ue.style.height=Ho,ue.style.minWidth=Ho,ue.style.minHeight=Ho,ue.style.fontSize="18px",ue.style.lineHeight="1",Bo?ue.style.color=Bo:ue.style.color="var(--persona-button-primary-fg, #ffffff)",!$.isStreaming())if(ue.innerHTML="",dr){let ee=parseFloat(Ho)||24,Qe=Bo?.trim()||"currentColor",bt=te(dr,ee,Qe,2);bt?ue.appendChild(bt):ue.textContent=ua}else ue.textContent=ua;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fn?(ue.style.backgroundColor=Fn,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=o.copy?.sendButtonLabel??"Send",ue.style.width="",ue.style.height="",ue.style.minWidth="",ue.style.minHeight="",ue.style.fontSize="",ue.style.lineHeight="",ue.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Fn?(ue.style.backgroundColor=Fn,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),Bo?ue.style.color=Bo:ue.classList.add("persona-text-white");Ot.borderWidth?(ue.style.borderWidth=Ot.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),Ot.borderColor?ue.style.borderColor=Ot.borderColor:ue.style.borderColor="",Ot.paddingX?(ue.style.paddingLeft=Ot.paddingX,ue.style.paddingRight=Ot.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Ot.paddingY?(ue.style.paddingTop=Ot.paddingY,ue.style.paddingBottom=Ot.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let ts=gn?.querySelector(".persona-send-button-tooltip");if(tl&&es)if(ts)ts.textContent=es,ts.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=es,gn?.insertBefore(ee,ue)}else ts&&(ts.style.display="none");let fa=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);fa?(xe.style.maxWidth=fa,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",X&&(X.style.maxWidth=fa,X.style.marginLeft="auto",X.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=fa,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",X&&(X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let no=o.statusIndicator??{},Vg=no.visible??!0;if(M.style.display=Vg?"":"none",$){let ee=$.getStatus();ht(M,(bt=>bt==="idle"?no.idleText??Wt.idle:bt==="connecting"?no.connectingText??Wt.connecting:bt==="connected"?no.connectedText??Wt.connected:bt==="error"?no.errorText??Wt.error:Wt[bt])(ee),no,ee)}M.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Kg=no.align==="left"?"persona-text-left":no.align==="center"?"persona-text-center":"persona-text-right";M.classList.add(Kg)},open(){D()&&mt(!0,"api")},close(){D()&&mt(!1,"api")},toggle(){D()&&mt(!j,"api")},reconnect(){$.reconnectNow()},clearChat(){Hn=!1,$.clearMessages(),Mo.clear(),Yn();try{localStorage.removeItem(Rr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Rr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Rr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&Ni(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},R.syncFromMetadata(),Oe?.clear(),$e?.reset(),He?.update()},setMessage(l){return!ye||$.isStreaming()?!1:(!j&&D()&&mt(!0,"system"),ye.value=l,ye.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let g=l?.trim()||ye.value.trim();return g?(!j&&D()&&mt(!0,"system"),ye.value="",ye.style.height="auto",$.sendMessage(g),!0):!1},startVoiceRecognition(){return $.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?($.isVoiceActive()||(!j&&D()&&mt(!0,"system"),Ze.manuallyDeactivated=!1,vn(),$.toggleVoice().then(()=>{Ze.active=$.isVoiceActive(),Dn("user"),$.isVoiceActive()&&lr()})),!0):En?!0:pd()?(!j&&D()&&mt(!0,"system"),Ze.manuallyDeactivated=!1,vn(),aa("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{Ze.active=!1,Ze.manuallyDeactivated=!0,vn(),Dn("user"),Nn()}),!0):!1:En?(Ze.manuallyDeactivated=!0,vn(),eo("user"),!0):!1},injectMessage(l){return!j&&D()&&mt(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!j&&D()&&mt(!0,"system");let g=$.injectAssistantMessage(l);return ge&&(ge=!1,be&&(clearTimeout(be),be=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),g},injectUserMessage(l){return!j&&D()&&mt(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!j&&D()&&mt(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!j&&D()&&mt(!0,"system"),$.injectMessageBatch(l)},injectComponentDirective(l){return!j&&D()&&mt(!0,"system"),$.injectComponentDirective(l)},injectTestMessage(l){!j&&D()&&mt(!0,"system"),$.injectTestEvent(l)},async connectStream(l,g){return $.connectStream(l,g)},__pushEventStreamEvent(l){Oe&&($e?.processEvent(l.type,l.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Y||!Oe||Ti()},hideEventStream(){je&&Hr()},isEventStreamVisible(){return je},showArtifacts(){Jt(o)&&(Hn=!1,er=!0,Bn(),tt?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(Hn=!0,Bn())},upsertArtifact(l){return Jt(o)?(Fo(o.features?.artifacts,l.artifactType)==="panel"&&(Hn=!1,er=!0),$.upsertArtifact(l)):null},selectArtifact(l){Jt(o)&&$.selectArtifact(l)},clearArtifacts(){Jt(o)&&$.clearArtifacts()},getArtifacts(){return $?.getArtifacts()??[]},getSelectedArtifactId(){return $?.getSelectedArtifactId()??null},focusInput(){return A&&!j&&!Q()||!ye?!1:(ye.focus(),!0)},async resolveApproval(l,g,b){let T=$.getMessages().find(P=>P.variant==="approval"&&P.approval?.id===l);if(!T?.approval)throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){$.resolveWebMcpApproval(T.id,g);return}return $.resolveApproval(T.approval,g,b)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,g){return i.on(l,g)},off(l,g){i.off(l,g)},isOpen(){return D()&&j},isVoiceActive(){return Ze.active},toggleReadAloud(l){$.toggleReadAloud(l)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(l){return $.getReadAloudState(l)},onReadAloudChange(l){return $.onReadAloudChange(l)},getState(){return{open:D()&&j,launcherEnabled:A,voiceActive:Ze.active,streaming:$.isStreaming()}},showCSATFeedback(l){!j&&D()&&mt(!0,"system");let g=xe.querySelector(".persona-feedback-container");g&&g.remove();let b=pc({onSubmit:async(x,T)=>{$.isClientTokenMode()&&await $.submitCSATFeedback(x,T),l?.onSubmit?.(x,T)},onDismiss:l?.onDismiss,...l});xe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!j&&D()&&mt(!0,"system");let g=xe.querySelector(".persona-feedback-container");g&&g.remove();let b=uc({onSubmit:async(x,T)=>{$.isClientTokenMode()&&await $.submitNPSFeedback(x,T),l?.onSubmit?.(x,T)},onDismiss:l?.onDismiss,...l});xe.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return $.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return $.submitNPSFeedback(l,g)},destroy(){Vi(),Po!=null&&(clearInterval(Po),Po=null),Ke.forEach(l=>l()),Ie.remove(),Ye?.remove(),Ft?.destroy(),zt?.remove(),Eo&&S.removeEventListener("click",Eo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:b=>b?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ke.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&It.focusInput()};if(window.addEventListener("persona:focusInput",g),Ke.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let F=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===l)&&It.showEventStream()},G=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===l)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",G),Ke.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",G)})}let b=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&It.showArtifacts()},x=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&It.hideArtifacts()},T=F=>{let G=F.detail;G?.instanceId&&G.instanceId!==l||G?.artifact&&It.upsertArtifact(G.artifact)},P=F=>{let G=F.detail;G?.instanceId&&G.instanceId!==l||typeof G?.id=="string"&&It.selectArtifact(G.id)},J=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",J),Ke.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",J)})}let pn=dC(o.persistState);if(pn&&D()){let l=pC(pn.storage),g=`${pn.keyPrefix}widget-open`,b=`${pn.keyPrefix}widget-voice`,x=`${pn.keyPrefix}widget-voice-mode`;if(l){let T=pn.persist?.openState&&l.getItem(g)==="true",P=pn.persist?.voiceState&&l.getItem(b)==="true",J=pn.persist?.voiceState&&l.getItem(x)==="true";if(T&&setTimeout(()=>{It.open(),setTimeout(()=>{if(P||J)It.startVoiceRecognition();else if(pn.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),pn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(g,"true")}),i.on("widget:closed",()=>{l.setItem(g,"false")})),pn.persist?.voiceState&&(i.on("voice:state",F=>{l.setItem(b,F.active?"true":"false")}),i.on("user:message",F=>{l.setItem(x,F.viaVoice?"true":"false")})),pn.clearOnChatClear){let F=()=>{l.removeItem(g),l.removeItem(b),l.removeItem(x)},G=()=>F();window.addEventListener("persona:clear-chat",G),Ke.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(y&&D()&&setTimeout(()=>{It.open()},0),sr(),!dg){let l=rs(()=>{$&&(Ii++,Mo.clear(),zr(xe,$.getMessages(),De))});Ke.push(l)}return It};var wf=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},gC=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},mC=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},hC=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let s=o.offsetHeight>0;o.style.height="100%";let r=o.offsetHeight>0;o.remove(),!(!s||r)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Af=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},bc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Sf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",bc(e)},mc=e=>{e.style.transition=""},hc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},yc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},yC=(e,t,n,o,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},bC=(e,t,n,o,s,r)=>{let a=r?t:e;s==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},vC=e=>{let t=Ko(e),n=t.components?.panel,o=(s,r)=>s==null||s===""?r:Kt(t,s)??s;return{inset:o(n?.inset,Ha),canvasBackground:o(n?.canvasBackground,Ba)}},Tf=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},xC=(e,t,n,o,s,r,a,i)=>{let p=sn(r),d=p.reveal==="push",c=i!=null,u=i?.inset??"",y=i?.canvasBackground??"";yC(e,t,n,o,d),bC(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=r?.launcher?.mobileFullscreen??!0,C=r?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=C:!1;if(h&&E&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),hc(t),mc(o),Sf(o),yc(n),mi(s,o),Tf(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(r?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Sf(o),gC(o,p.maxHeight),Tf(o,c&&a,u,y),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",hc(t),mc(o),yc(n),mi(s,o);let R=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",I=a?"translateX(0)":A;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=R,o.style.transform=I,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",mc(o),bc(o),mi(s,o);let R=wf(p.width,e.clientWidth),A=Math.max(0,e.clientWidth),I=p.animate?"margin-left 180ms ease":"none",_=p.side==="right"?a?-R:0:a?0:-R;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${A+R}px`,t.style.transition=I,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",hc(t),bc(o),yc(n),mi(s,o);let R=p.reveal==="emerge";R?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let A=a?p.width:"0px",I=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",_=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",mC(o,p.maxHeight),o.style.overflow=R||_?"hidden":"visible",o.style.transition=I,R){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let O=c?`calc(${wf(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;s.style.width=O,s.style.minWidth=O,s.style.maxWidth=O,s.style.boxSizing="border-box"}}},CC=(e,t)=>{let n=e.ownerDocument.createElement("div");return Af(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Af(n,o)},destroy(){n.remove()}}},wC=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let r=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let y=null,f=()=>{y?.disconnect(),y=null},h=null,C=()=>{h=t?.launcher?.detachedPanel===!0?vC(t):null};C();let E=()=>{xC(a,i,p,d,c,t,u,h)},L=null,R=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=As(()=>{C(),E()}))},A=()=>{f(),sn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{E()}),y.observe(a)))},I=!1,_=()=>{E(),A(),u&&!I&&a.dataset.personaDockMobileFullscreen!=="true"&&(I=!0,hC(a,sn(t)))},O=a.ownerDocument.defaultView,w=()=>{_()};return O?.addEventListener("resize",w),sn(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),_(),R(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let q=z.launcherEnabled?z.open:!0;u!==q&&(u=q,_())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),_(),R()},destroy(){O?.removeEventListener("resize",w),L?.(),L=null,f(),o.isConnected&&(r&&r.parentNode===o?o.insertBefore(e,r):o.appendChild(e)),a.remove()}}},hi=(e,t)=>Ht(t)?wC(e,t):CC(e,t);var AC=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Ef=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Mf=e=>{let t=AC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,s=e.config,r=hi(t,s),a,i=[],p=(E,L)=>{let A=!(L?.launcher?.enabled??!0)||Ht(L),I=o.createElement("div");if(I.setAttribute("data-persona-root","true"),A&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let _=E.attachShadow({mode:"open"});_.appendChild(I),Ef(_,o)}else E.appendChild(I),Ef(E,o);return t.id&&I.setAttribute("data-persona-instance",t.id),I},d=()=>{r.syncWidgetState(a.getState())},c=()=>{i.forEach(E=>E()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let E=p(r.host,s);a=gc(E,s,{debugTools:e.debugTools}),c()},y=()=>{i.forEach(E=>E()),i=[],a.destroy()};u(),e.onChatReady?.();let f=E=>{y(),r.destroy(),r=hi(t,E),s=E,u()},h={update(E){let L=di(s??{},E),R=Ht(s),A=Ht(L),I=yo(s),_=yo(L);if(R!==A||I!==_){f(L);return}s=L,r.updateConfig(s),a.update(E),d()},destroy(){y(),r.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(h,{get(E,L,R){if(L==="host")return r.host;if(L in E)return Reflect.get(E,L,R);let A=a[L];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function SC(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function TC(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(r=>r.toLowerCase().startsWith(o))?1:SC(o,n)?2:3}function kf(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function vc(e,t){let n=t.trim();if(!n)return[...e].sort(kf);let o=[];for(let s of e){let r=TC(s.label,n);r!==3&&o.push({item:s,tier:r})}return o.sort((s,r)=>s.tier!==r.tier?s.tier-r.tier:kf(s.item,r.item)),o.map(s=>s.item)}function EC(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function MC(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>vc(e.items,t),resolve:e.resolve}}function kC(e){let t=e.commands.map(s=>({id:s.name,label:s.name,description:s.description,iconName:s.iconName,command:s.kind??"prompt",insertMode:s.insertMode,submitOnSelect:s.submitOnSelect,action:s.action,commandArgsPlaceholder:s.argsPlaceholder})),n=new Map(e.commands.map(s=>[s.name,s])),o=new Map(t.map(s=>[s.id,s]));return{id:e.id,label:e.label,matchCommand:s=>o.get(s),resolveOn:"submit",search:s=>vc(t,EC(s).name),resolve:(s,r)=>{let a=n.get(s.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(r.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(r.args):a.prompt??""}:{}}}}var Wf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),LC=new Set(["button","a","input","select","textarea","details","summary"]),PC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),xc=/\b(product|card|item|listing|result)\b/i,wc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,RC=3e3,IC=100;function Hf(e){let t=typeof e.className=="string"?e.className:"";if(xc.test(t)||e.id&&xc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&xc.test(o.value))return!0}return!1}function Bf(e){return wc.test((e.textContent??"").trim())}function Df(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function WC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Lf(e){let t=e.match(wc);return t?t[0]:null}function Pf(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function HC(e){let t=[],n=o=>{let s=o.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var BC="commerce-card",DC="result-card";function Rf(e){return!Hf(e)||!Bf(e)||!Df(e)&&!WC(e)?0:5200}function If(e){return!Hf(e)||Bf(e)||!Df(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Of=[{id:BC,scoreElement(e){return Rf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||wc.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Rf(e)===0)return null;let{title:n,href:o}=Pf(e),s=Lf((e.textContent??"").trim())??Lf(t.text)??"",r=HC(e);return[o&&n?`[${n}](${o})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,r.length?`actions: ${r.join(", ")}`:""].filter(Boolean).join(`
143
+ `)}},{id:DC,scoreElement(e){return If(e)},formatSummary(e,t){if(If(e)===0)return null;let{title:n,href:o}=Pf(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
+ `)}}];function OC(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function NC(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",s=t.maxTextLength??e.maxTextLength??200,r=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??Of;return i==="simple"&&e.rules&&e.rules.length>0?(OC(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:s,visibleOnly:r,root:a,rules:d}}function Cc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var FC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function _C(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||LC.has(t)||n&&PC.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Nf(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function $C(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let r=e.getAttribute("type");r&&(t.type=r);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function Ff(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${Cc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of FC){let r=e.getAttribute(s);if(r){let a=`${t}[${s}="${Cc(r)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>Cc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let r=e.parentElement;if(r){let i=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function jC(e){return e==="static"?IC:RC}function _f(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Ff(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:_C(e),attributes:$C(e)}}function UC(e,t,n,o){let s=jC(t.interactivity),r=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(s+=i,a.formatSummary&&!r&&(r=a))}return{score:s,formattingRule:r}}function zC(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function qC(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,s=[],r=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(Wf.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Nf(d)){i=a.nextNode();continue}let u=_f(d,e.maxTextLength),y=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!y&&!f){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:h,formattingRule:C}=UC(d,u,e.rules,n);s.push({el:d,domIndex:r,enriched:u,score:h,formattingRule:C}),r+=1}i=a.nextNode()}s.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of s){if(p.length>=e.maxElements)break;zC(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,y=c.enriched.interactivity==="static"?1:0;return u!==y?u-y:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let y=d.formattingRule.formatSummary(d.el,d.enriched,n);y&&(c=y)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function VC(e,t){let n=[],o=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),r=s.currentNode;for(;r&&n.length<e.maxElements;){if(r.nodeType===Node.ELEMENT_NODE){let p=r,d=p.tagName.toLowerCase();if(Wf.has(d)){r=s.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){r=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Nf(p)){r=s.nextNode();continue}let c=_f(p,e.maxTextLength),u=c.text.length>0,y=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!y){r=s.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}r=s.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function KC(e={}){let t=NC(e),n=t.root??document.body;return n?t.mode==="simple"?VC(t,n):qC(t,n):[]}var yi=100;function GC(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let r=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);r.length>0&&o.push(`Structured summaries:
145
145
  ${r.map(a=>`- ${a.split(`
146
146
  `).join(`
147
147
  `)}`).join(`
148
- `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let r of e)n==="structured"&&r.formattedSummary||s[r.interactivity].push(r);if(s.clickable.length>0){let r=s.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,mi)}" (clickable)`);o.push(`Interactive elements:
148
+ `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let r of e)n==="structured"&&r.formattedSummary||s[r.interactivity].push(r);if(s.clickable.length>0){let r=s.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,yi)}" (clickable)`);o.push(`Interactive elements:
149
149
  ${r.join(`
150
- `)}`)}if(s.navigable.length>0){let r=s.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,mi)}" (navigable)`);o.push(`Navigation links:
150
+ `)}`)}if(s.navigable.length>0){let r=s.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,yi)}" (navigable)`);o.push(`Navigation links:
151
151
  ${r.join(`
152
- `)}`)}if(s.input.length>0){let r=s.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,mi)}" (input)`);o.push(`Form inputs:
152
+ `)}`)}if(s.input.length>0){let r=s.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,yi)}" (input)`);o.push(`Form inputs:
153
153
  ${r.join(`
154
- `)}`)}if(s.static.length>0){let r=s.static.map(a=>`- ${a.selector}: "${a.text.substring(0,mi)}"`);o.push(`Content:
154
+ `)}`)}if(s.static.length>0){let r=s.static.map(a=>`- ${a.selector}: "${a.text.substring(0,yi)}"`);o.push(`Content:
155
155
  ${r.join(`
156
156
  `)}`)}return o.join(`
157
157
 
158
- `)}function qC(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function VC(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function KC(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Wn(e.colors.primary,.95),100:Wn(e.colors.primary,.9),200:Wn(e.colors.primary,.8),300:Wn(e.colors.primary,.7),400:Wn(e.colors.primary,.6),500:e.colors.primary,600:Wn(e.colors.primary,.8),700:Wn(e.colors.primary,.7),800:Wn(e.colors.primary,.6),900:Wn(e.colors.primary,.5),950:Wn(e.colors.primary,.45)}}),{...t,palette:n}}}}function GC(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function JC(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Wn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),r=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function XC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var QC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Nf={components:{panel:{borderRadius:"0",shadow:"none"}}},Ff={id:"shop",label:"Shopping Assistant",config:{theme:QC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:gn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},_f={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Nf}},$f={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Nf}},jf={shop:Ff,minimal:_f,fullscreen:$f};function YC(e){return jf[e]}var ZC=Sf;function zn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function ew(e){if(e)return{getHeaders:zn(e.getHeaders),onFeedback:zn(e.onFeedback),onCopy:zn(e.onCopy),requestMiddleware:zn(e.requestMiddleware),actionHandlers:zn(e.actionHandlers),actionParsers:zn(e.actionParsers),postprocessMessage:zn(e.postprocessMessage),contextProviders:zn(e.contextProviders),streamParser:zn(e.streamParser)}}var Uf=`({ text, message }: any) => {
158
+ `)}function JC(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function XC(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function QC(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Wn(e.colors.primary,.95),100:Wn(e.colors.primary,.9),200:Wn(e.colors.primary,.8),300:Wn(e.colors.primary,.7),400:Wn(e.colors.primary,.6),500:e.colors.primary,600:Wn(e.colors.primary,.8),700:Wn(e.colors.primary,.7),800:Wn(e.colors.primary,.6),900:Wn(e.colors.primary,.5),950:Wn(e.colors.primary,.45)}}),{...t,palette:n}}}}function YC(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function ZC(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Wn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),r=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function ew(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var tw={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},$f={components:{panel:{borderRadius:"0",shadow:"none"}}},jf={id:"shop",label:"Shopping Assistant",config:{theme:tw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:fn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Uf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:$f}},zf={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:$f}},qf={shop:jf,minimal:Uf,fullscreen:zf};function nw(e){return qf[e]}var ow=Mf;function zn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function rw(e){if(e)return{getHeaders:zn(e.getHeaders),onFeedback:zn(e.onFeedback),onCopy:zn(e.onCopy),requestMiddleware:zn(e.requestMiddleware),actionHandlers:zn(e.actionHandlers),actionParsers:zn(e.actionParsers),postprocessMessage:zn(e.postprocessMessage),contextProviders:zn(e.contextProviders),streamParser:zn(e.streamParser)}}var Vf=`({ text, message }: any) => {
159
159
  const jsonSource = (message as any).rawContent || text || message.content;
160
160
  if (!jsonSource || typeof jsonSource !== 'string') return null;
161
161
  let cleanJson = jsonSource
@@ -168,7 +168,7 @@ ${r.join(`
168
168
  if (parsed.action) return { type: parsed.action, payload: parsed };
169
169
  } catch (e) { return null; }
170
170
  return null;
171
- }`,zf=`function(ctx) {
171
+ }`,Kf=`function(ctx) {
172
172
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
173
173
  if (!jsonSource || typeof jsonSource !== 'string') return null;
174
174
  var cleanJson = jsonSource
@@ -181,7 +181,7 @@ ${r.join(`
181
181
  if (parsed.action) return { type: parsed.action, payload: parsed };
182
182
  } catch (e) { return null; }
183
183
  return null;
184
- }`,qf=`(action: any, context: any) => {
184
+ }`,Gf=`(action: any, context: any) => {
185
185
  if (action.type !== 'nav_then_click') return;
186
186
  const payload = action.payload || action.raw || {};
187
187
  const url = payload?.page;
@@ -198,7 +198,7 @@ ${r.join(`
198
198
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
199
199
  window.location.href = targetUrl;
200
200
  return { handled: true, displayText: text };
201
- }`,Vf=`function(action, context) {
201
+ }`,Jf=`function(action, context) {
202
202
  if (action.type !== 'nav_then_click') return;
203
203
  var payload = action.payload || action.raw || {};
204
204
  var url = payload.page;
@@ -215,26 +215,26 @@ ${r.join(`
215
215
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
216
216
  window.location.href = targetUrl;
217
217
  return { handled: true, displayText: text };
218
- }`,tw=`(parsed: any) => {
218
+ }`,sw=`(parsed: any) => {
219
219
  if (!parsed || typeof parsed !== 'object') return null;
220
220
  if (parsed.action === 'nav_then_click') return 'Navigating...';
221
221
  if (parsed.action === 'message') return parsed.text || '';
222
222
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
223
223
  return parsed.text || null;
224
- }`,nw=`function(parsed) {
224
+ }`,aw=`function(parsed) {
225
225
  if (!parsed || typeof parsed !== 'object') return null;
226
226
  if (parsed.action === 'nav_then_click') return 'Navigating...';
227
227
  if (parsed.action === 'message') return parsed.text || '';
228
228
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
229
229
  return parsed.text || null;
230
- }`;function ow(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function hi(e){return e.parserType??ow(e.streamParser)??"plain"}function yi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,s])=>{typeof s=="string"&&n.push(`${t} ${o}: "${s}",`)}),n.push(`${t}},`)),n}function bi(e,t,n){let o=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),r=n?.onFeedback||n?.onCopy;return(s||r)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function vi(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(o||s)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([r,a])=>{typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function xi(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(r=>r!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(r=>r!=="renderUserMessage"&&r!=="renderAssistantMessage");(o||s)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([r,a])=>{r!=="render"&&(typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([r,a])=>{r==="renderUserMessage"||r==="renderAssistantMessage"||(r==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):r==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function wc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Kf(e,t,n){Object.entries(t).forEach(([o,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${o}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${o}: {`),Kf(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(s)},`)}})}function vo(e,t,n,o){n&&(e.push(`${o}${t}: {`),Kf(e,n,`${o} `),e.push(`${o}},`))}function js(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function rw(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let s=n?{...n,hooks:ew(n.hooks)}:void 0;return t==="esm"?sw(o,s):t==="script-installer"?lw(o,s):t==="script-advanced"?dw(o,s):t==="react-component"?aw(o,s):t==="react-advanced"?iw(o,s):cw(o,s)}function sw(e,t){let n=t?.hooks,o=hi(e),s=o!=="plain",r=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${js(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(r,"theme",e.theme," "),e.launcher&&vo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...yi(e," ")),r.push(...bi(e," ",n)),r.push(...vi(e," ")),r.push(...xi(e," ")),r.push(...wc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push("});"),r.join(`
231
- `)}function aw(e,t){let n=t?.hooks,o=hi(e),s=o!=="plain",r=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${js(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(r,"theme",e.theme," "),e.launcher&&vo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...yi(e," ")),r.push(...bi(e," ",n)),r.push(...vi(e," ")),r.push(...xi(e," ")),r.push(...wc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage in your app:"),r.push("// import { ChatWidget } from './components/ChatWidget';"),r.push("//"),r.push("// export default function App() {"),r.push("// return ("),r.push("// <div>"),r.push("// {/* Your app content */}"),r.push("// <ChatWidget />"),r.push("// </div>"),r.push("// );"),r.push("// }"),r.join(`
232
- `)}function iw(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${js(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(o,"theme",e.theme," "),e.launcher&&vo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([s,r])=>{o.push(` ${s}: "${r}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"?o.push(` ${s}: ${r},`):typeof r=="number"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([s,r])=>{o.push(` ${s}: ${r},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{o.push(` "${s}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...yi(e," ")),o.push(...bi(e," ",n)),o.push(...vi(e," ")),o.push(...xi(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${tw}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Uf}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Uf}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${qf}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${qf}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
233
- `)}function Gf(e){let t=hi(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([r,a])=>{typeof a=="string"&&(s[r]=a)}),Object.keys(s).length>0&&(o.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([r,a])=>{r!=="onFeedback"&&r!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[r]=a)}),Object.keys(s).length>0&&(o.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(o.markdown=s)}if(e.layout){let s={};if(e.layout.header){let r={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.header=r)}if(e.layout.messages){let r={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)r.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(r.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.messages=r)}Object.keys(s).length>0&&(o.layout=s)}return o}function lw(e,t){let n=Gf(e),s=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,r=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist/install.global.js" data-config='${r}'></script>`}function cw(e,t){let n=t?.hooks,o=hi(e),s=o!=="plain",r=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${js(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(r,"theme",e.theme," "),e.launcher&&vo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...yi(e," ")),r.push(...bi(e," ",n)),r.push(...vi(e," ")),r.push(...xi(e," ")),r.push(...wc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push("</script>"),r.join(`
234
- `)}function dw(e,t){let n=t?.hooks,o=Gf(e),r=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
230
+ }`;function iw(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function bi(e){return e.parserType??iw(e.streamParser)??"plain"}function vi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,s])=>{typeof s=="string"&&n.push(`${t} ${o}: "${s}",`)}),n.push(`${t}},`)),n}function xi(e,t,n){let o=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),r=n?.onFeedback||n?.onCopy;return(s||r)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function Ci(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(o||s)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([r,a])=>{typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function wi(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(r=>r!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(r=>r!=="renderUserMessage"&&r!=="renderAssistantMessage");(o||s)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([r,a])=>{r!=="render"&&(typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([r,a])=>{r==="renderUserMessage"||r==="renderAssistantMessage"||(r==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):r==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Ac(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Xf(e,t,n){Object.entries(t).forEach(([o,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${o}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${o}: {`),Xf(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(s)},`)}})}function vo(e,t,n,o){n&&(e.push(`${o}${t}: {`),Xf(e,n,`${o} `),e.push(`${o}},`))}function js(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function lw(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let s=n?{...n,hooks:rw(n.hooks)}:void 0;return t==="esm"?cw(o,s):t==="script-installer"?uw(o,s):t==="script-advanced"?gw(o,s):t==="react-component"?dw(o,s):t==="react-advanced"?pw(o,s):fw(o,s)}function cw(e,t){let n=t?.hooks,o=bi(e),s=o!=="plain",r=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${js(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(r,"theme",e.theme," "),e.launcher&&vo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...vi(e," ")),r.push(...xi(e," ",n)),r.push(...Ci(e," ")),r.push(...wi(e," ")),r.push(...Ac(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push("});"),r.join(`
231
+ `)}function dw(e,t){let n=t?.hooks,o=bi(e),s=o!=="plain",r=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${js(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(r,"theme",e.theme," "),e.launcher&&vo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...vi(e," ")),r.push(...xi(e," ",n)),r.push(...Ci(e," ")),r.push(...wi(e," ")),r.push(...Ac(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage in your app:"),r.push("// import { ChatWidget } from './components/ChatWidget';"),r.push("//"),r.push("// export default function App() {"),r.push("// return ("),r.push("// <div>"),r.push("// {/* Your app content */}"),r.push("// <ChatWidget />"),r.push("// </div>"),r.push("// );"),r.push("// }"),r.join(`
232
+ `)}function pw(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${js(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(o,"theme",e.theme," "),e.launcher&&vo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([s,r])=>{o.push(` ${s}: "${r}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"?o.push(` ${s}: ${r},`):typeof r=="number"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([s,r])=>{o.push(` ${s}: ${r},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{o.push(` "${s}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...vi(e," ")),o.push(...xi(e," ",n)),o.push(...Ci(e," ")),o.push(...wi(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${sw}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Vf}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Vf}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${Gf}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${Gf}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
233
+ `)}function Qf(e){let t=bi(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([r,a])=>{typeof a=="string"&&(s[r]=a)}),Object.keys(s).length>0&&(o.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([r,a])=>{r!=="onFeedback"&&r!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[r]=a)}),Object.keys(s).length>0&&(o.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(o.markdown=s)}if(e.layout){let s={};if(e.layout.header){let r={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.header=r)}if(e.layout.messages){let r={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)r.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(r.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.messages=r)}Object.keys(s).length>0&&(o.layout=s)}return o}function uw(e,t){let n=Qf(e),s=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,r=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist/install.global.js" data-config='${r}'></script>`}function fw(e,t){let n=t?.hooks,o=bi(e),s=o!=="plain",r=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${js(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&vo(r,"theme",e.theme," "),e.launcher&&vo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...vi(e," ")),r.push(...xi(e," ",n)),r.push(...Ci(e," ")),r.push(...wi(e," ")),r.push(...Ac(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push("</script>"),r.join(`
234
+ `)}function gw(e,t){let n=t?.hooks,o=Qf(e),r=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
235
235
  `).map((a,i)=>i===0?a:" "+a).join(`
236
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(r.push(` widgetConfig.getHeaders = ${n.getHeaders};`),r.push("")),n?.contextProviders&&(r.push(` widgetConfig.contextProviders = ${n.contextProviders};`),r.push("")),n?.streamParser?r.push(` widgetConfig.streamParser = ${n.streamParser};`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(" widgetConfig.streamParser = function() {"),r.push(` return agentWidget.createFlexibleJsonStreamParser(${nw});`),r.push(" };")),r.push(""),n?.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` var customParsers = ${n.actionParsers};`),r.push(" widgetConfig.actionParsers = customParsers.concat(["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${zf}`),r.push(" ]);")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" widgetConfig.actionParsers = ["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${zf}`),r.push(" ];")),r.push(""),n?.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` var customHandlers = ${n.actionHandlers};`),r.push(" widgetConfig.actionHandlers = customHandlers.concat(["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Vf}`),r.push(" ]);")):(r.push(" // Action handlers for navigation and other actions"),r.push(" widgetConfig.actionHandlers = ["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Vf}`),r.push(" ];")),r.push(""),n?.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(` var customResult = (${n.requestMiddleware})(ctx);`),r.push(" var merged = customResult || ctx.payload;"),r.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),r.push(" };")):(r.push(" // Send DOM context with each request"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),r.push(" };")),r.push(""),n?.postprocessMessage?r.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(r.push(" // Markdown postprocessor"),r.push(" widgetConfig.postprocessMessage = function(ctx) {"),r.push(" return agentWidget.markdownPostprocessor(ctx.text);"),r.push(" };")),r.push(""),(n?.onFeedback||n?.onCopy)&&(r.push(" // Message action callbacks"),r.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&r.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&r.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),r.push("")),r.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${js(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),r.join(`
237
- `)}var Jf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Xf=.1,Qf=.15,Yf=1.5,Ac=24,Zf=40,pw=`
236
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${wn}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(r.push(` widgetConfig.getHeaders = ${n.getHeaders};`),r.push("")),n?.contextProviders&&(r.push(` widgetConfig.contextProviders = ${n.contextProviders};`),r.push("")),n?.streamParser?r.push(` widgetConfig.streamParser = ${n.streamParser};`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(" widgetConfig.streamParser = function() {"),r.push(` return agentWidget.createFlexibleJsonStreamParser(${aw});`),r.push(" };")),r.push(""),n?.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` var customParsers = ${n.actionParsers};`),r.push(" widgetConfig.actionParsers = customParsers.concat(["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${Kf}`),r.push(" ]);")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" widgetConfig.actionParsers = ["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${Kf}`),r.push(" ];")),r.push(""),n?.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` var customHandlers = ${n.actionHandlers};`),r.push(" widgetConfig.actionHandlers = customHandlers.concat(["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Jf}`),r.push(" ]);")):(r.push(" // Action handlers for navigation and other actions"),r.push(" widgetConfig.actionHandlers = ["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Jf}`),r.push(" ];")),r.push(""),n?.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(` var customResult = (${n.requestMiddleware})(ctx);`),r.push(" var merged = customResult || ctx.payload;"),r.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),r.push(" };")):(r.push(" // Send DOM context with each request"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),r.push(" };")),r.push(""),n?.postprocessMessage?r.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(r.push(" // Markdown postprocessor"),r.push(" widgetConfig.postprocessMessage = function(ctx) {"),r.push(" return agentWidget.markdownPostprocessor(ctx.text);"),r.push(" };")),r.push(""),(n?.onFeedback||n?.onCopy)&&(r.push(" // Message action callbacks"),r.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&r.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&r.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),r.push("")),r.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${js(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),r.join(`
237
+ `)}var Yf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Zf=.1,eg=.15,tg=1.5,Sc=24,ng=40,mw=`
238
238
  /* \u2500\u2500 Root \u2500\u2500 */
239
239
  .persona-dc-root {
240
240
  display: flex;
@@ -385,7 +385,7 @@ ${r.join(`
385
385
  .persona-dc-stage {
386
386
  height: 550px;
387
387
  min-height: 400px;
388
- padding: ${Ac}px;
388
+ padding: ${Sc}px;
389
389
  overflow: auto;
390
390
  background: #f0f1f3;
391
391
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -475,5 +475,5 @@ ${r.join(`
475
475
  min-height: 300px;
476
476
  }
477
477
  }
478
- `;function uw(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=pw,document.head.appendChild(e)}function fw(e,t){let n=e.clientWidth-Ac*2-Zf,o=e.clientHeight-Ac*2-Zf;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function gw(e,t,n,o,s){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=s==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function mw(e,t){let{items:n,initialIndex:o=0,initialDevice:s="desktop",initialColorScheme:r="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");uw();let c=Math.max(0,Math.min(o,n.length-1)),u=s,y=r,f=null,h=1,C=!1,E=m("div","persona-dc-root"),L=m("div","persona-dc-toolbar"),R=m("div","persona-dc-toolbar-lead"),A=m("div","persona-dc-toolbar-trail"),I=mt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ue(-1)}),_=m("div");_.style.position="relative";let O=m("button","persona-dc-title-btn");O.type="button",O.setAttribute("aria-expanded","false"),O.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),U=m("span","persona-dc-title-chevron"),q=ne("chevron-down",12,"currentColor",2);q&&U.appendChild(q),O.append(w,U);let Q=m("div","persona-dc-dropdown");Q.setAttribute("role","listbox"),Q.style.display="none";let D=!1;function j(){Q.innerHTML="";for(let ie=0;ie<n.length;ie++){let Re=n[ie],xt=m("button","persona-dc-dropdown-item");xt.type="button",xt.setAttribute("role","option"),xt.setAttribute("aria-current",ie===c?"true":"false");let yt=m("span");if(yt.textContent=Re.title,xt.appendChild(yt),Re.description){let rt=m("span","persona-dc-dropdown-desc");rt.textContent=Re.description,xt.appendChild(rt)}xt.addEventListener("click",()=>{ye(),Ne(ie)}),Q.appendChild(xt)}}function ge(){D=!D,Q.style.display=D?"":"none",O.setAttribute("aria-expanded",D?"true":"false"),D&&j()}function ye(){D&&(D=!1,Q.style.display="none",O.setAttribute("aria-expanded","false"))}O.addEventListener("click",ie=>{ie.stopPropagation(),ge()});let Ee=()=>ye();document.addEventListener("click",Ee),_.append(O,Q);let De=mt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ue(1)}),se=m("span","persona-dc-counter");R.append(I,_,De,se);let be=null;i&&(be=fo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ie=>{u=ie,me.dataset.device=u,f=null,we()}}),A.appendChild(be.element));let Y=null;if(a){let ie=m("div","persona-dc-zoom-controls"),Re=mt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(Qf,(f??h)-Xf),we()}});Y=m("span","persona-dc-zoom-level"),Y.title="Reset to 100%",Y.style.cursor="pointer",Y.addEventListener("click",()=>{f=1,we()});let xt=mt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min(Yf,(f??h)+Xf),we()}}),yt=mt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,we()}});ie.append(Re,Y,xt,yt),A.appendChild(ie)}if(p){let ie=m("div","persona-dc-separator");A.appendChild(ie);let Re=fo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:xt=>{y=xt,me.dataset.colorScheme=y,Pe()}});A.appendChild(Re.element)}let ce=m("div","persona-dc-separator");A.appendChild(ce);let Z=mt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});A.appendChild(Z),L.append(R,A);let xe=m("div","persona-dc-stage"),me=m("div","persona-dc-iframe-wrapper");me.dataset.device=u,me.dataset.colorScheme=y;let ue=m("iframe","persona-dc-iframe");ue.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ue.setAttribute("loading","lazy"),ue.title=n[c].title,me.appendChild(ue),xe.appendChild(me),E.append(L,xe),e.appendChild(E);function Pe(){try{let ie=ue.contentDocument?.body;if(!ie)return;y==="dark"?ie.classList.add("theme-dark"):ie.classList.remove("theme-dark")}catch{}}ue.addEventListener("load",()=>Pe());function Oe(){let ie=n[c];w.textContent=ie.title,se.textContent=`${c+1} / ${n.length}`,ue.title=ie.title}function Ue(ie){let Re=((c+ie)%n.length+n.length)%n.length;Ne(Re)}function Ne(ie){ie<0||ie>=n.length||(c=ie,ue.src=n[c].url,Oe(),d?.(c,n[c]))}function we(){if(C)return;let ie=Jf[u]??Jf.desktop;h=fw(xe,ie);let Re=Math.max(Qf,Math.min(Yf,f??h));gw(me,ue,ie,Re,u),Y&&(Y.textContent=`${Math.round(Re*100)}%`)}let Le=new ResizeObserver(()=>we());Le.observe(xe),Oe(),ue.src=n[c].url,requestAnimationFrame(()=>we());function ot(){C||(C=!0,Le.disconnect(),document.removeEventListener("click",Ee),E.remove())}return{element:E,goTo:Ne,next:()=>Ue(1),prev:()=>Ue(-1),getIndex:()=>c,setDevice(ie){u=ie,me.dataset.device=ie,be?.setSelected(ie),f=null,we()},setColorScheme(ie){y=ie,me.dataset.colorScheme=ie},setZoom(ie){f=ie,we()},destroy:ot}}export{hp as ASK_USER_QUESTION_CLIENT_TOOL,mp as ASK_USER_QUESTION_PARAMETERS_SCHEMA,ba as ASK_USER_QUESTION_TOOL_NAME,hr as AgentWidgetClient,vs as AgentWidgetSession,vr as AttachmentManager,Vo as BrowserSpeechEngine,Xp as DEFAULT_COMPONENTS,Tl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,gn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Gp as DEFAULT_PALETTE,Jp as DEFAULT_SEMANTIC,ft as DEFAULT_WIDGET_CONFIG,jf as PRESETS,$f as PRESET_FULLSCREEN,_f as PRESET_MINIMAL,Ff as PRESET_SHOP,br as ReadAloudController,cl as SUGGEST_REPLIES_CLIENT_TOOL,up as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Ln as SUGGEST_REPLIES_TOOL_NAME,Db as THEME_ZONES,wn as VERSION,Mn as WEBMCP_TOOL_PREFIX,as as WebMcpBridge,qC as accessibilityPlugin,VC as animationsPlugin,xr as applyThemeVariables,Tr as attachHeaderToContainer,KC as brandPlugin,Bs as buildComposer,Ru as buildDefaultHeader,bo as buildHeader,Hs as buildHeaderWithLayout,Iu as buildMinimalHeader,ps as builtInClientToolsForDispatch,UC as collectEnrichedPageContext,Rn as componentRegistry,di as createActionManager,fc as createAgentExperience,jm as createAskUserQuestionBubble,xl as createBestAvailableVoiceProvider,nx as createBubbleWithLayout,dc as createCSATFeedback,Wl as createComboButton,eC as createComponentMiddleware,ic as createComponentStreamParser,jd as createDefaultSanitizer,mw as createDemoCarousel,em as createDirectivePostprocessor,Jo as createDropdownMenu,Vm as createFlexibleJsonStreamParser,mt as createIconButton,nh as createImagePart,ml as createJsonStreamParser,uo as createLabelButton,ac as createLocalStorageAdapter,ma as createMarkdownProcessor,fr as createMarkdownProcessorFromConfig,zu as createMessageActions,pc as createNPSFeedback,fl as createPlainTextParser,XC as createPlugin,gl as createRegexJsonParser,Zl as createRovingTablist,SC as createSlashCommandsSource,Ds as createStandardBubble,AC as createStaticMentionSource,Uo as createTextPart,ws as createTheme,As as createThemeObserver,fo as createToggleGroup,Er as createTypingIndicator,qo as createVoiceProvider,gi as createWidgetHostLayout,hl as createXmlParser,ZC as default,Pr as defaultActionHandlers,ci as defaultJsonActionParser,bc as defaultMentionFilter,Hf as defaultParseRules,Da as detectColorScheme,tm as directivePostprocessor,ds as ensureAskUserQuestionSheet,$n as escapeHtml,cc as extractComponentDirectiveFromMessage,oh as fileToImagePart,zC as formatEnrichedContext,jo as generateAssistantMessageId,rw as generateCodeSnippet,Ym as generateMessageId,Df as generateStableSelector,ms as generateUserMessageId,Ko as getActiveTheme,Ll as getColorScheme,eh as getDisplayText,Wu as getHeaderLayout,th as getImageParts,YC as getPreset,pi as hasComponentDirective,bl as hasImages,jl as headerLayouts,JC as highContrastPlugin,Sf as initAgentWidget,oo as isAskUserQuestionMessage,Zx as isComponentDirectiveType,Bt as isDockedMountMode,wa as isSuggestRepliesMessage,Pa as isVoiceSupported,No as isWebMcpToolName,pl as latestAgentSuggestions,Mv as listRegisteredStreamAnimations,Dd as loadMarkdownParsers,Fd as markdownPostprocessor,El as mergeWithDefaults,Zm as normalizeContent,rs as onMarkdownParsersReady,ro as parseAskUserQuestionPayload,fp as parseSuggestRepliesPayload,ys as pickBestVoice,li as pluginRegistry,GC as reducedMotionPlugin,Tv as registerStreamAnimationPlugin,$o as removeAskUserQuestionSheet,lc as renderComponentDirective,Uu as renderLoadingIndicatorWithFallback,ne as renderLucideIcon,an as resolveDockConfig,ss as resolveSanitizer,Ml as resolveTokens,ol as stripWebMcpPrefix,kl as themeToCssVariables,Ev as unregisterStreamAnimationPlugin,rh as validateImageFile,Qp as validateTheme};
478
+ `;function hw(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=mw,document.head.appendChild(e)}function yw(e,t){let n=e.clientWidth-Sc*2-ng,o=e.clientHeight-Sc*2-ng;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function bw(e,t,n,o,s){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=s==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function vw(e,t){let{items:n,initialIndex:o=0,initialDevice:s="desktop",initialColorScheme:r="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");hw();let c=Math.max(0,Math.min(o,n.length-1)),u=s,y=r,f=null,h=1,C=!1,E=m("div","persona-dc-root"),L=m("div","persona-dc-toolbar"),R=m("div","persona-dc-toolbar-lead"),A=m("div","persona-dc-toolbar-trail"),I=gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>$e(-1)}),_=m("div");_.style.position="relative";let O=m("button","persona-dc-title-btn");O.type="button",O.setAttribute("aria-expanded","false"),O.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),z=m("span","persona-dc-title-chevron"),q=te("chevron-down",12,"currentColor",2);q&&z.appendChild(q),O.append(w,z);let Q=m("div","persona-dc-dropdown");Q.setAttribute("role","listbox"),Q.style.display="none";let D=!1;function j(){Q.innerHTML="";for(let ne=0;ne<n.length;ne++){let Re=n[ne],xt=m("button","persona-dc-dropdown-item");xt.type="button",xt.setAttribute("role","option"),xt.setAttribute("aria-current",ne===c?"true":"false");let ht=m("span");if(ht.textContent=Re.title,xt.appendChild(ht),Re.description){let ct=m("span","persona-dc-dropdown-desc");ct.textContent=Re.description,xt.appendChild(ct)}xt.addEventListener("click",()=>{be(),He(ne)}),Q.appendChild(xt)}}function ge(){D=!D,Q.style.display=D?"":"none",O.setAttribute("aria-expanded",D?"true":"false"),D&&j()}function be(){D&&(D=!1,Q.style.display="none",O.setAttribute("aria-expanded","false"))}O.addEventListener("click",ne=>{ne.stopPropagation(),ge()});let Ee=()=>be();document.addEventListener("click",Ee),_.append(O,Q);let De=gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>$e(1)}),ae=m("span","persona-dc-counter");R.append(I,_,De,ae);let ve=null;i&&(ve=fo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ne=>{u=ne,me.dataset.device=u,f=null,je()}}),A.appendChild(ve.element));let Y=null;if(a){let ne=m("div","persona-dc-zoom-controls"),Re=gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(eg,(f??h)-Zf),je()}});Y=m("span","persona-dc-zoom-level"),Y.title="Reset to 100%",Y.style.cursor="pointer",Y.addEventListener("click",()=>{f=1,je()});let xt=gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min(tg,(f??h)+Zf),je()}}),ht=gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,je()}});ne.append(Re,Y,xt,ht),A.appendChild(ne)}if(p){let ne=m("div","persona-dc-separator");A.appendChild(ne);let Re=fo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:xt=>{y=xt,me.dataset.colorScheme=y,Pe()}});A.appendChild(Re.element)}let le=m("div","persona-dc-separator");A.appendChild(le);let Z=gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});A.appendChild(Z),L.append(R,A);let Ce=m("div","persona-dc-stage"),me=m("div","persona-dc-iframe-wrapper");me.dataset.device=u,me.dataset.colorScheme=y;let pe=m("iframe","persona-dc-iframe");pe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),pe.setAttribute("loading","lazy"),pe.title=n[c].title,me.appendChild(pe),Ce.appendChild(me),E.append(L,Ce),e.appendChild(E);function Pe(){try{let ne=pe.contentDocument?.body;if(!ne)return;y==="dark"?ne.classList.add("theme-dark"):ne.classList.remove("theme-dark")}catch{}}pe.addEventListener("load",()=>Pe());function Oe(){let ne=n[c];w.textContent=ne.title,ae.textContent=`${c+1} / ${n.length}`,pe.title=ne.title}function $e(ne){let Re=((c+ne)%n.length+n.length)%n.length;He(Re)}function He(ne){ne<0||ne>=n.length||(c=ne,pe.src=n[c].url,Oe(),d?.(c,n[c]))}function je(){if(C)return;let ne=Yf[u]??Yf.desktop;h=yw(Ce,ne);let Re=Math.max(eg,Math.min(tg,f??h));bw(me,pe,ne,Re,u),Y&&(Y.textContent=`${Math.round(Re*100)}%`)}let Je=new ResizeObserver(()=>je());Je.observe(Ce),Oe(),pe.src=n[c].url,requestAnimationFrame(()=>je());function Me(){C||(C=!0,Je.disconnect(),document.removeEventListener("click",Ee),E.remove())}return{element:E,goTo:He,next:()=>$e(1),prev:()=>$e(-1),getIndex:()=>c,setDevice(ne){u=ne,me.dataset.device=ne,ve?.setSelected(ne),f=null,je()},setColorScheme(ne){y=ne,me.dataset.colorScheme=ne},setZoom(ne){f=ne,je()},destroy:Me}}export{yp as ASK_USER_QUESTION_CLIENT_TOOL,hp as ASK_USER_QUESTION_PARAMETERS_SCHEMA,ba as ASK_USER_QUESTION_TOOL_NAME,hr as AgentWidgetClient,vs as AgentWidgetSession,vr as AttachmentManager,Vo as BrowserSpeechEngine,Qp as DEFAULT_COMPONENTS,Ml as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,fn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Jp as DEFAULT_PALETTE,Xp as DEFAULT_SEMANTIC,ut as DEFAULT_WIDGET_CONFIG,qf as PRESETS,zf as PRESET_FULLSCREEN,Uf as PRESET_MINIMAL,jf as PRESET_SHOP,br as ReadAloudController,pl as SUGGEST_REPLIES_CLIENT_TOOL,fp as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Ln as SUGGEST_REPLIES_TOOL_NAME,Fb as THEME_ZONES,wn as VERSION,Mn as WEBMCP_TOOL_PREFIX,as as WebMcpBridge,JC as accessibilityPlugin,XC as animationsPlugin,xr as applyThemeVariables,Tr as attachHeaderToContainer,QC as brandPlugin,Bs as buildComposer,Iu as buildDefaultHeader,bo as buildHeader,Hs as buildHeaderWithLayout,Wu as buildMinimalHeader,ps as builtInClientToolsForDispatch,KC as collectEnrichedPageContext,Rn as componentRegistry,ui as createActionManager,gc as createAgentExperience,qm as createAskUserQuestionBubble,wl as createBestAvailableVoiceProvider,sx as createBubbleWithLayout,pc as createCSATFeedback,Hl as createComboButton,rC as createComponentMiddleware,lc as createComponentStreamParser,Ud as createDefaultSanitizer,vw as createDemoCarousel,om as createDirectivePostprocessor,Jo as createDropdownMenu,Jm as createFlexibleJsonStreamParser,gt as createIconButton,sh as createImagePart,yl as createJsonStreamParser,uo as createLabelButton,ic as createLocalStorageAdapter,ma as createMarkdownProcessor,fr as createMarkdownProcessorFromConfig,qu as createMessageActions,uc as createNPSFeedback,ml as createPlainTextParser,ew as createPlugin,hl as createRegexJsonParser,ec as createRovingTablist,kC as createSlashCommandsSource,Ds as createStandardBubble,MC as createStaticMentionSource,Uo as createTextPart,Da as createTheme,As as createThemeObserver,fo as createToggleGroup,Er as createTypingIndicator,qo as createVoiceProvider,hi as createWidgetHostLayout,bl as createXmlParser,ow as default,Pr as defaultActionHandlers,pi as defaultJsonActionParser,vc as defaultMentionFilter,Of as defaultParseRules,Oa as detectColorScheme,rm as directivePostprocessor,ds as ensureAskUserQuestionSheet,$n as escapeHtml,dc as extractComponentDirectiveFromMessage,ah as fileToImagePart,GC as formatEnrichedContext,jo as generateAssistantMessageId,lw as generateCodeSnippet,th as generateMessageId,Ff as generateStableSelector,ms as generateUserMessageId,Ko as getActiveTheme,Pl as getColorScheme,oh as getDisplayText,Hu as getHeaderLayout,rh as getImageParts,nw as getPreset,fi as hasComponentDirective,xl as hasImages,Ul as headerLayouts,ZC as highContrastPlugin,Mf as initAgentWidget,oo as isAskUserQuestionMessage,oC as isComponentDirectiveType,Ht as isDockedMountMode,wa as isSuggestRepliesMessage,Pa as isVoiceSupported,No as isWebMcpToolName,fl as latestAgentSuggestions,Pv as listRegisteredStreamAnimations,Od as loadMarkdownParsers,_d as markdownPostprocessor,ws as mergeWithDefaults,nh as normalizeContent,rs as onMarkdownParsersReady,ro as parseAskUserQuestionPayload,gp as parseSuggestRepliesPayload,ys as pickBestVoice,ci as pluginRegistry,YC as reducedMotionPlugin,kv as registerStreamAnimationPlugin,$o as removeAskUserQuestionSheet,cc as renderComponentDirective,zu as renderLoadingIndicatorWithFallback,te as renderLucideIcon,sn as resolveDockConfig,ss as resolveSanitizer,kl as resolveTokens,sl as stripWebMcpPrefix,Ll as themeToCssVariables,Lv as unregisterStreamAnimationPlugin,ih as validateImageFile,Yp as validateTheme};
479
479
  //# sourceMappingURL=index.js.map