@runtypelabs/persona 4.1.0 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,22 @@
1
- var dg=Object.defineProperty;var Ss=(n,e)=>()=>(n&&(e=n(n=0)),e);var Lp=(n,e)=>{for(var t in e)dg(n,t,{get:e[t],enumerable:!0})};var Pp={};Lp(Pp,{DOMPurify:()=>ug,Marked:()=>pg});import{Marked as pg}from"marked";import ug from"dompurify";var Ip=Ss(()=>{"use strict"});var ts,Mi=Ss(()=>{"use strict";ts=class{constructor(e=24e3,t={}){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;var o;this.sampleRate=e;let r=Math.max(0,(o=t.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),t=o,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.pcmToFloat32(t);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.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(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}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 e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let t of e)this.scheduleSamples(t)}scheduleSamples(e){if(e.length===0)return;let t=this.ensureContext(),r=t.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=t.createBufferSource();o.buffer=r,o.connect(t.destination);let s=t.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);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 e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),r=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Tf(n){return n.replace(/\/+$/,"")}async function Mf(n){var e,t;try{let r=await n.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${n.status}`}: ${r.detail}`:(t=r.error)!=null?t:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var Ta,vu=Ss(()=>{"use strict";Mi();Ta=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,t;return(t=this.playerPromise)!=null?t:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new ts(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,t){let r=++this.generation;this.run(r,e,t)}async run(e,t,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;e===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;e===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${Tf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,m=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!m.ok||!m.body)throw new Error(await Mf(m));let f=m.body.getReader();for(;;){let{done:g,value:u}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(g)break;u&&u.byteLength>0&&d.enqueue(u)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var Ma,xu=Ss(()=>{"use strict";Ma=class{constructor(e,t,r={}){this.primary=e;this.fallback=t;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,t){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=t.onStart)==null||o.call(t)},onEnd:()=>{var o;return(o=t.onEnd)==null?void 0:o.call(t)},onError:o=>{var s,a,i;if(r){(s=t.onError)==null||s.call(t,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,t)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,t,r,o;(t=(e=this.primary).destroy)==null||t.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var wu={};Lp(wu,{FallbackSpeechEngine:()=>Ma,RuntypeSpeechEngine:()=>Ta});var Cu=Ss(()=>{"use strict";vu();xu()});var Wp=null,Ts=null,Go=null;var Rp=()=>Ts?Promise.resolve(Ts):Go||(Wp?(Go=Wp().then(n=>(Ts=n,n)),Go):(Go=Promise.resolve().then(()=>(Ip(),Pp)).then(n=>(Ts=n,n)),Go)),To=()=>Ts;var mg=n=>{if(n)return n},di=n=>{let e=null;return t=>{var o,s;let r=To();if(!r)return oo(t);if(!e){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;e=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=mg(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},da=n=>n?di({markedOptions:n.options,renderer:n.renderer}):di(),Kv=di();var oo=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var gg={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"]},fg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,hg=()=>{let n=null;return e=>{let t=To();if(!t)return oo(e);if(!n){let{DOMPurify:r}=t;n=r(typeof window!="undefined"?window:void 0),n.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!fg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,gg)}},pa=n=>n===!1?null:typeof n=="function"?n:hg();var Hp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Bp=n=>n.includes("|"),Dp=n=>{let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())},yg=n=>`| ${n.join(" | ")} |`,bg=n=>`| ${Array.from({length:n},()=>"---").join(" | ")} |`,vg=(n,e)=>n.length>=e?n.slice(0,e):n.concat(Array.from({length:e-n.length},()=>"")),Np=n=>{if(!n||!n.includes("|"))return n;let e=n.split(`
2
- `),t=!1;for(let r=0;r<e.length-1;r++){let o=e[r],s=e[r+1];if(!Bp(o)||Hp.test(o)||!Hp.test(s))continue;let a=Dp(o).length;if(a<1)continue;let i=bg(a);e[r+1]!==i&&(e[r+1]=i,t=!0);let d=r+2;for(;d<e.length;d++){let c=e[d];if(c.trim()===""||!Bp(c))break;let m=yg(vg(Dp(c),a));e[d]!==m&&(e[d]=m,t=!0)}r=d-1}return t?e.join(`
3
- `):n};var Mo="webmcp:",pi=new Map,Fp=n=>{var e;pi.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&pi.set(t.name,r)}},ui=n=>pi.get(Up(n)),ua={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},Op=null;function $p(n){if(n.length===0)return"0:empty";let e=n.map(t=>{var r,o;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(o=t.origin)!=null?o:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${n.length}:${xg(e.join(""))}`}function _p(n,e){let t=3735928559^e,r=1103547991^e;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);t=Math.imul(t^s,2654435761),r=Math.imul(r^s,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function xg(n){let e=_p(n,0).toString(36),t=_p(n,2654435761).toString(36);return`${e}.${t}`}var ma=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let t;try{t=await e.getTools()}catch(o){return ua.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Fp(t);let r=typeof location!="undefined"?location.origin:"";return t.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Cg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return ur("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return ur(v?"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 s=Up(e),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return ur(`Failed to read WebMCP registry: ${x}`)}Fp(a);let i=a.find(v=>v.name===s);if(!i)return ur(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return ur(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return ur("Aborted by cancel()");let d=ui(s),c={toolName:s,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return ur("User declined the tool call.");if(r!=null&&r.aborted)return ur("Aborted by cancel()");let m=new AbortController,f=!1,g=setTimeout(()=>{f=!0,m.abort()},this.timeoutMs),u=()=>m.abort();r&&(r.aborted?m.abort():r.addEventListener("abort",u,{once:!0}));try{let v=await o.executeTool(i,Mg(t),{signal:m.signal});return Ag(v)}catch(v){if(f)return ur(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return ur("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return ur(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",u)}}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}(Op?await Op():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ua.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ua.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):e}async requestConfirm(e){var r;let t=(r=this.confirmHandler)!=null?r:Sg;try{return await t(e)}catch(o){return ua.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>wg(e,r))}},Up=n=>n.startsWith(Mo)?n.slice(Mo.length):n,Qo=n=>n.startsWith(Mo),wg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Cg=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Ag=n=>{if(n==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Eg(e)}]}},ur=n=>({isError:!0,content:[{type:"text",text:n}]}),Sg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Tg(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
1
+ var vg=Object.defineProperty;var ks=(t,e)=>()=>(t&&(e=t(t=0)),e);var Rp=(t,e)=>{for(var n in e)vg(t,n,{get:e[n],enumerable:!0})};var Hp={};Rp(Hp,{DOMPurify:()=>wg,Marked:()=>xg});import{Marked as xg}from"marked";import wg from"dompurify";var Bp=ks(()=>{"use strict"});var ss,Li=ks(()=>{"use strict";ss=class{constructor(e=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;var o;this.sampleRate=e;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),n=o,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 r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.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(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}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 e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=n.createBufferSource();o.buffer=r,o.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);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 e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),r=new Float32Array(n),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Hf(t){return t.replace(/\/+$/,"")}async function Bf(t){var e,n;try{let r=await t.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${t.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var La,Au=ks(()=>{"use strict";Li();La=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new ss(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,n){let r=++this.generation;this.run(r,e,n)}async run(e,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;e===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;e===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${Hf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,u=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!u.ok||!u.body)throw new Error(await Bf(u));let f=u.body.getReader();for(;;){let{done:g,value:m}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(g)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var Pa,Su=ks(()=>{"use strict";Pa=class{constructor(e,n,r={}){this.primary=e;this.fallback=n;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,n,r,o;(n=(e=this.primary).destroy)==null||n.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Tu={};Rp(Tu,{FallbackSpeechEngine:()=>Pa,RuntypeSpeechEngine:()=>La});var Eu=ks(()=>{"use strict";Au();Su()});var Dp=null,Ls=null,Zo=null;var Np=()=>Ls?Promise.resolve(Ls):Zo||(Dp?(Zo=Dp().then(t=>(Ls=t,t)),Zo):(Zo=Promise.resolve().then(()=>(Bp(),Hp)).then(t=>(Ls=t,t)),Zo)),ko=()=>Ls;var Cg=t=>{if(t)return t},gi=t=>{let e=null;return n=>{var o,s;let r=ko();if(!r)return ao(n);if(!e){let{Marked:a}=r,i=t==null?void 0:t.markedOptions;e=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Cg(t==null?void 0:t.renderer);d&&e.use({renderer:d})}return e.parse(n)}},ga=t=>t?gi({markedOptions:t.options,renderer:t.renderer}):gi(),lx=gi();var ao=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Ag={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"]},Sg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Tg=()=>{let t=null;return e=>{let n=ko();if(!n)return ao(e);if(!t){let{DOMPurify:r}=n;t=r(typeof window!="undefined"?window:void 0),t.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Sg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Ag)}},fa=t=>t===!1?null:typeof t=="function"?t:Tg();var Fp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Op=t=>t.includes("|"),_p=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},Eg=t=>`| ${t.join(" | ")} |`,Mg=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,kg=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),$p=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
2
+ `),n=!1;for(let r=0;r<e.length-1;r++){let o=e[r],s=e[r+1];if(!Op(o)||Fp.test(o)||!Fp.test(s))continue;let a=_p(o).length;if(a<1)continue;let i=Mg(a);e[r+1]!==i&&(e[r+1]=i,n=!0);let d=r+2;for(;d<e.length;d++){let c=e[d];if(c.trim()===""||!Op(c))break;let u=Eg(kg(_p(c),a));e[d]!==u&&(e[d]=u,n=!0)}r=d-1}return n?e.join(`
3
+ `):t};var Ur="webmcp:",fi=new Map,Up=t=>{var e;fi.clear();for(let n of t){let r=(e=n.title)==null?void 0:e.trim();r&&fi.set(n.name,r)}},Ps=t=>fi.get(Vp(t)),ha={warn(t,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},zp=null;function jp(t){if(t.length===0)return"0:empty";let e=t.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${t.length}:${Lg(e.join(""))}`}function qp(t,e){let n=3735928559^e,r=1103547991^e;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Lg(t){let e=qp(t,0).toString(36),n=qp(t,2654435761).toString(36);return`${e}.${n}`}var ya=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=e.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(o){return ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Up(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Ig(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return mr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let x=typeof document!="undefined"&&!!document.modelContext;return mr(x?"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 s=Vp(e),a;try{a=await o.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return mr(`Failed to read WebMCP registry: ${v}`)}Up(a);let i=a.find(x=>x.name===s);if(!i)return mr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return mr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let d=Ps(s),c={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return mr("User declined the tool call.");if(r!=null&&r.aborted)return mr("Aborted by cancel()");let u=new AbortController,f=!1,g=setTimeout(()=>{f=!0,u.abort()},this.timeoutMs),m=()=>u.abort();r&&(r.aborted?u.abort():r.addEventListener("abort",m,{once:!0}));try{let x=await o.executeTool(i,Bg(n),{signal:u.signal});return Wg(x)}catch(x){if(f)return mr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return mr(v)}finally{clearTimeout(g),r&&r.removeEventListener("abort",m)}}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}(zp?await zp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;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):e}async requestConfirm(e){var r;let n=(r=this.confirmHandler)!=null?r:Rg;try{return await n(e)}catch(o){return ha.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Pg(e,r))}},Vp=t=>t.startsWith(Ur)?t.slice(Ur.length):t,es=t=>t.startsWith(Ur),Pg=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Ig=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Wg=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Dg(e)}]}},mr=t=>({isError:!0,content:[{type:"text",text:t}]}),Rg=async t=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Hg(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
4
4
 
5
5
  Arguments:
6
- ${e}`:"")+(n.description?`
6
+ ${e}`:"")+(t.description?`
7
7
 
8
- ${n.description}`:"");return window.confirm(t)},Tg=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},Mg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Eg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};import{parse as kg,ARR as Lg,OBJ as Pg,STR as Ig}from"partial-json";var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},kr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Tt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Ms=(...n)=>n.filter(Boolean).join(" ");var mi="ask_user_question",Es=8,Xo="data-persona-ask-sheet-for",Wg="Other",Rg="Other\u2026",zp="Type your own answer here",jp="Send",Hg="Next",Bg="Back",Dg="Submit all",Ng="Skip",Fg=3,gi="data-ask-current-index",fi="data-ask-question-count",Vp="data-ask-answers",hi="data-ask-grouped",Kp="data-ask-layout",Og=n=>n.layout==="pills"?"pills":"rows",_g=n=>n.getAttribute(Kp)==="pills"?"pills":"rows",qp=!1,Gp=n=>n.replace(/["\\]/g,"\\$&"),Eo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===mi,yi=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},Jo=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=kg(o,Ig|Pg|Lg);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},ks=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>Es&&!qp&&(qp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Es}.`)),e.slice(0,Es)},$g=n=>{var e;return(e=ks(n)[0])!=null?e:null},Ug=(n,e)=>{var t;return(t=ks(n)[e])!=null?t:null},qg=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Qp=(n,e,t)=>{if(n!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},zg=(n,e,t,r)=>{let s=b("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=b("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=Qp(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},jg=n=>{let t=b("span",n==="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 t.setAttribute("aria-hidden","true"),t},Vg=(n,e,t,r)=>{var m,f,g;let s=b("div",r==="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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!t){for(let u=0;u<Fg;u++)s.appendChild(jg(r));return s}if(d.forEach((u,v)=>{s.appendChild(zg(u,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let u=r==="rows"?Wg:Rg;if(r==="rows"){let v=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=b("span","persona-ask-row-content"),P=document.createElement("input");P.type="text",P.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",P.placeholder=(m=e.freeTextPlaceholder)!=null?m:zp,P.setAttribute("data-ask-free-text-input","true"),P.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:u),x.appendChild(P),v.appendChild(x);let T=Qp(r,a,d.length);T&&v.appendChild(T),s.appendChild(v)}else{let v=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=e.freeTextLabel)!=null?g:u,s.appendChild(v)}}return s},Xp=(n,e)=>{var s,a;let r=b("div",e==="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");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:zp,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:jp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Kg=n=>{var r;let e=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=b("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:jp,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Gg=(n,e,t)=>{var c,m,f,g;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Bg,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(m=t.skipLabel)!=null?m:Ng,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(f=t.submitAllLabel)!=null?f:Dg:(g=t.nextLabel)!=null?g:Hg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},ko=n=>{let e=n.getAttribute(Vp);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Jp=(n,e)=>{n.setAttribute(Vp,JSON.stringify(e))},or=n=>{var t;let e=Number((t=n.getAttribute(gi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Qg=(n,e)=>{n.setAttribute(gi,String(Math.max(0,Math.floor(e))))},Yo=n=>{var t;let e=Number((t=n.getAttribute(fi))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},so=n=>n.getAttribute(hi)==="true",Xg=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Jg=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},ga=(n,e)=>{let{payload:t}=Jo(e),r=ks(t),o=ko(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},Yp=n=>{let e=ko(n),t=or(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",m=o.has(c);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Zp=n=>{if(!so(n))return;let e=ko(n),t=or(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},bi=(n,e,t)=>{let r=yi(t),o=_g(n),{payload:s,complete:a}=Jo(e),i=so(n),d=or(n),c=Yo(n),m=i?Ug(s,d):$g(s),f=!!(m!=null&&m.multiSelect),g=n.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let u=n.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let M=typeof(m==null?void 0:m.question)=="string"?m.question:"";v.textContent=M,v.classList.toggle("persona-ask-question-skeleton",!M&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let M=Vg(m,r,a,o);x.replaceWith(M)}if(o!=="rows"){let M=n.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Xp(r,o))}let P=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!P?n.appendChild(Kg(r)):(!f||i)&&P&&P.remove(),n.setAttribute("data-multi-select",f?"true":"false");let T=n.querySelector('[data-ask-nav-row="true"]');if(i){let M=Gg(d,c,r);T?T.replaceWith(M):n.appendChild(M)}else T&&T.remove();Yp(n),Zp(n)},Yg=(n,e,t)=>{let r=yi(e),o=Og(r),s=n.toolCall.id,a=ks(t),i=Math.max(1,a.length),d=i>1,c=Xg(n,a),m=d?Jg(n,i):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Xo,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(fi,String(i)),f.setAttribute(gi,String(m)),f.setAttribute(hi,d?"true":"false"),f.setAttribute(Kp,o),Jp(f,c),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),qg(f,r);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),f.appendChild(g);let P=b("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");return P.setAttribute("data-ask-pill-list","true"),P.setAttribute("role","group"),f.appendChild(P),o!=="rows"&&f.appendChild(Xp(r,o)),bi(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Zg=(n,e,t)=>{let{payload:r}=Jo(e),o=Math.max(1,ks(r).length);o>Yo(n)&&(n.setAttribute(fi,String(o)),o>1&&!so(n)&&n.setAttribute(hi,"true")),bi(n,e,t)};var fa=(n,e,t)=>{if(!t||!Eo(n)||yi(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${Xo}]`).forEach(c=>{c.getAttribute(Xo)!==o&&c.remove()});let a=t.querySelector(`[${Xo}="${Gp(o)}"]`);if(a){Zg(a,n,e);return}let{payload:i}=Jo(n),d=Yg(n,e,i);t.appendChild(d)},Zo=(n,e)=>{if(!n)return;let t=e?`[${Xo}="${Gp(e)}"]`:`[${Xo}]`;n.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},vi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),ao=(n,e)=>{let t=ko(n),r=or(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,Jp(n,t),Yp(n),Zp(n)},ha=(n,e,t,r)=>{let o=Yo(n),s=Math.max(0,Math.min(o-1,r));Qg(n,s),bi(n,e,t)};var _r="suggest_replies";var ef={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},eu={name:_r,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:ef,origin:"sdk",annotations:{readOnlyHint:!0}},xi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),wi=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===_r},tf=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},tu=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!wi(r))continue;let o=tf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},nu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var nf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Es,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},rf={name:mi,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:nf,origin:"sdk",annotations:{readOnlyHint:!0}},Ci=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(rf),nu(n)&&e.push(eu),e};import{parse as of,STR as sf,OBJ as af}from"partial-json";var ru=n=>n.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),es=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},lf=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},ou=n=>n.status==="complete"?lf(n):n.status==="pending"?"Waiting":"",cf=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var su=n=>n.status==="complete"?cf(n):"Using tool...",ya=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Ps=n=>{var t,r,o;let e=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return ya(e)},ba=n=>{var t,r,o;let e=n.durationMs!==void 0?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return ya(e)},Ai=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Ps(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},va=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Ls(r,t.slice(s,a.index),[]),a[1]!==void 0?Ls(r,a[1],["bold"]):a[2]!==void 0?Ls(r,a[2],["italic"]):a[3]!==void 0&&Ls(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Ls(r,t.slice(s),[]),r},Ls=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},df=()=>{let n=null,e=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${t.description}`:"");return window.confirm(n)},Hg=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Bg=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Dg=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};import{parse as Ng,ARR as Fg,OBJ as Og,STR as _g}from"partial-json";var y=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Pr=(t,e,n)=>{let r=t.createElement(e);return n&&(r.className=n),r};var Et=(t,e={},...n)=>{let r=document.createElement(t);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Is=(...t)=>t.filter(Boolean).join(" ");var hi="ask_user_question",Ws=8,ts="data-persona-ask-sheet-for",$g="Other",Ug="Other\u2026",Gp="Type your own answer here",Qp="Send",zg="Next",qg="Back",jg="Submit all",Vg="Skip",Kg=3,yi="data-ask-current-index",bi="data-ask-question-count",Xp="data-ask-answers",vi="data-ask-grouped",Jp="data-ask-layout",Gg=t=>t.layout==="pills"?"pills":"rows",Qg=t=>t.getAttribute(Jp)==="pills"?"pills":"rows",Kp=!1,Yp=t=>t.replace(/["\\]/g,"\\$&"),Lo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===hi,xi=t=>{var e,n;return(n=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?n:{}},ns=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=Ng(o,_g|Og|Fg);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Rs=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Ws&&!Kp&&(Kp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ws}.`)),e.slice(0,Ws)},Xg=t=>{var e;return(e=Rs(t)[0])!=null?e:null},Jg=(t,e)=>{var n;return(n=Rs(t)[e])!=null?n:null},Yg=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Zp=(t,e,n)=>{if(t!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Zg=(t,e,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let c=y("span","persona-ask-row-description");c.textContent=t.description,a.appendChild(c)}s.appendChild(a);let d=Zp(n,r,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},ef=t=>{let n=y("span",t==="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},tf=(t,e,n,r)=>{var u,f,g;let s=y("div",r==="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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<Kg;m++)s.appendChild(ef(r));return s}if(d.forEach((m,x)=>{s.appendChild(Zg(m,x,r,a))}),(t==null?void 0:t.allowFreeText)!==!1){let m=r==="rows"?$g:Ug;if(r==="rows"){let x=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(u=e.freeTextPlaceholder)!=null?u:Gp,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),v.appendChild(M),x.appendChild(v);let W=Zp(r,a,d.length);W&&x.appendChild(W),s.appendChild(x)}else{let x=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(g=e.freeTextLabel)!=null?g:m,s.appendChild(x)}}return s},eu=(t,e)=>{var s,a;let r=y("div",e==="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");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=t.freeTextPlaceholder)!=null?s:Gp,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:Qp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},nf=t=>{var r;let e=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=t.submitLabel)!=null?r:Qp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},rf=(t,e,n)=>{var c,u,f,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:qg,o.setAttribute("data-ask-user-action","back"),o.disabled=t===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:Vg,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=t===e-1;return i.textContent=d?(f=n.submitAllLabel)!=null?f:jg:(g=n.nextLabel)!=null?g:zg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Po=t=>{let e=t.getAttribute(Xp);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},tu=(t,e)=>{t.setAttribute(Xp,JSON.stringify(e))},or=t=>{var n;let e=Number((n=t.getAttribute(yi))!=null?n:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},of=(t,e)=>{t.setAttribute(yi,String(Math.max(0,Math.floor(e))))},rs=t=>{var n;let e=Number((n=t.getAttribute(bi))!=null?n:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},io=t=>t.getAttribute(vi)==="true",sf=(t,e)=>{var o;let n=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},af=(t,e)=>{var r;let n=(r=t.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},ba=(t,e)=>{let{payload:n}=ns(e),r=Rs(n),o=Po(t),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},nu=t=>{let e=Po(t),n=or(t),r=e[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=t.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},ru=t=>{if(!io(t))return;let e=Po(t),n=or(t),r=e[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},wi=(t,e,n)=>{let r=xi(n),o=Qg(t),{payload:s,complete:a}=ns(e),i=io(t),d=or(t),c=rs(t),u=i?Jg(s,d):Xg(s),f=!!(u!=null&&u.multiSelect),g=t.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let m=t.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=t.querySelector('[data-ask-question="true"]');if(x){let T=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=T,x.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let v=t.querySelector('[data-ask-pill-list="true"]');if(v){let T=tf(u,r,a,o);v.replaceWith(T)}if(o!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(eu(r,o))}let M=t.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!M?t.appendChild(nf(r)):(!f||i)&&M&&M.remove(),t.setAttribute("data-multi-select",f?"true":"false");let W=t.querySelector('[data-ask-nav-row="true"]');if(i){let T=rf(d,c,r);W?W.replaceWith(T):t.appendChild(T)}else W&&W.remove();nu(t),ru(t)},lf=(t,e,n)=>{let r=xi(e),o=Gg(r),s=t.toolCall.id,a=Rs(n),i=Math.max(1,a.length),d=i>1,c=sf(t,a),u=d?af(t,i):0,f=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ts,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",t.id),f.setAttribute(bi,String(i)),f.setAttribute(yi,String(u)),f.setAttribute(vi,d?"true":"false"),f.setAttribute(Jp,o),tu(f,c),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Yg(f,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=y("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",g.appendChild(x),f.appendChild(g);let M=y("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");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),f.appendChild(M),o!=="rows"&&f.appendChild(eu(r,o)),wi(f,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},cf=(t,e,n)=>{let{payload:r}=ns(e),o=Math.max(1,Rs(r).length);o>rs(t)&&(t.setAttribute(bi,String(o)),o>1&&!io(t)&&t.setAttribute(vi,"true")),wi(t,e,n)};var va=(t,e,n)=>{if(!n||!Lo(t)||xi(e).enabled===!1)return;let o=t.toolCall.id;n.querySelectorAll(`[${ts}]`).forEach(c=>{c.getAttribute(ts)!==o&&c.remove()});let a=n.querySelector(`[${ts}="${Yp(o)}"]`);if(a){cf(a,t,e);return}let{payload:i}=ns(t),d=lf(t,e,i);n.appendChild(d)},os=(t,e)=>{if(!t)return;let n=e?`[${ts}="${Yp(e)}"]`:`[${ts}]`;t.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Ci=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),lo=(t,e)=>{let n=Po(t),r=or(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[r]:n[r]=e,tu(t,n),nu(t),ru(t)},xa=(t,e,n,r)=>{let o=rs(t),s=Math.max(0,Math.min(o-1,r));of(t,s),wi(t,e,n)};var zr="suggest_replies";var df={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},ou={name:zr,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:df,origin:"sdk",annotations:{readOnlyHint:!0}},Ai=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Si=t=>{var e;return t.variant==="tool"&&((e=t.toolCall)==null?void 0:e.name)===zr},pf=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e==null?void 0:e.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},su=t=>{var e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.role==="user")return null;if(!Si(r))continue;let o=pf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},au=t=>{var n;let e=(n=t==null?void 0:t.features)==null?void 0:n.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var uf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ws,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},mf={name:hi,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:uf,origin:"sdk",annotations:{readOnlyHint:!0}},Ti=t=>{var r;let e=[],n=(r=t==null?void 0:t.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&e.push(mf),au(t)&&e.push(ou),e};import{parse as gf,STR as ff,OBJ as hf}from"partial-json";var iu=t=>t.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),co=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},yf=t=>{var a,i;let e=(a=t.completedAt)!=null?a:Date.now(),n=(i=t.startedAt)!=null?i:e,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},lu=t=>t.status==="complete"?yf(t):t.status==="pending"?"Waiting":"",bf=t=>{var o,s,a;let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a: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 cu=t=>t.status==="complete"?bf(t):"Using tool...",wa=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Bs=t=>{var n,r,o;let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((n=t.completedAt)!=null?n:Date.now())-((o=(r=t.startedAt)!=null?r:t.completedAt)!=null?o:Date.now()));return wa(e)},Ca=t=>{var n,r,o;let e=t.durationMs!==void 0?t.durationMs:Math.max(0,((n=t.completedAt)!=null?n:Date.now())-((o=(r=t.startedAt)!=null?r:t.completedAt)!=null?o:Date.now()));return wa(e)},Ei=(t,e,n)=>{var s;if(!e)return n;let r=((s=t.name)==null?void 0:s.trim())||"tool",o=Bs(t);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Aa=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Hs(r,n.slice(s,a.index),[]),a[1]!==void 0?Hs(r,a[1],["bold"]):a[2]!==void 0?Hs(r,a[2],["italic"]):a[3]!==void 0&&Hs(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Hs(r,n.slice(s),[]),r},Hs=(t,e,n)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&t.push({text:r[o],styles:n}),o<r.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},vf=()=>{let t=null,e=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.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:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Is=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},au=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},iu=()=>{var e;let n=df();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},lu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=of(t,sf|af);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?ru(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=ru(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var cu=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var du="4.1.0";var Ws=du;var uf="https://api.runtype.com/v1/dispatch",xa="https://api.runtype.com";function mf(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Si=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function gf(n){switch(n){case"json":return lu;case"regex-json":return iu;case"xml":return cu;default:return au}}var pu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function ff(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=pu(t);if(!pu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Is(n);return Is(e)!==null&&a===null?e:n}var Rs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;this.apiUrl=(t=e.apiUrl)!=null?t:uf,this.headers={"Content-Type":"application/json","X-Persona-Version":Ws,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:gf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new ma(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;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 r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ws},body:JSON.stringify(t)});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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xa}/v1/client/feedback`}async sendFeedback(e){var a,i;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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ws},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let k=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:k}),k}let c=await this.buildPayload(e.messages),m=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Si).map(k=>{var W,C,I;return{id:k.id,role:k.role,content:(I=(C=(W=k.contentParts)!=null?W:k.llmContent)!=null?C:k.rawContent)!=null?I:k.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,u=!!(g&&g.length>0),v=u?$p(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,P=u&&x&&this.lastSentClientToolsFingerprint===v,T=!1,M=null,N;for(let k=0;;k++){let C={...f,...u&&(T||!P)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),N=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ws},body:JSON.stringify(C),signal:r.signal}),N.status===409&&k===0&&u){let I=await N.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}M=I!=null?I:{error:"Chat request failed"}}break}if(!N.ok){let k=M!=null?M:await N.json().catch(()=>({error:"Chat request failed"}));if(N.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(N.status===429){let C=new Error(k.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let W=new Error(k.error||"Failed to send message");throw t({type:"error",error:W}),W}if(!N.body){let k=new Error("No response body received");throw t({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(N.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,m;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||xa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(m=r==null?void 0:r.streamResponse)!=null?m:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(Si).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ci(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(e){var s,a;let r={messages:e.slice().filter(Si).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ci(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=m=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return r.current=f,o(f),f},c=m=>r.current?r.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=c(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,o(m)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r){var nn,fr,fn,je;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,m=S=>{let pe=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,ke=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,Te=S.tools?S.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...S,reasoning:pe,toolCall:ke,tools:Te}},f=S=>{if(S.role!=="assistant"||S.variant)return!0;let pe=Array.isArray(S.contentParts)&&S.contentParts.length>0,ke=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||pe||ke||!!S.stopReason},g=S=>{f(S)&&t({type:"message",message:m(S)})},u=null,v=null,x={current:null},P={current:null},T=null,M="",N=new Map,k=new Map,W=new Map,C=new Map,I=new Map,D={lastId:null,byStep:new Map},B={lastId:null,byCall:new Map},E=S=>{if(S==null)return null;try{return String(S)}catch{return null}},z=S=>{var pe,ke,Te,Re,Ye;return E((Ye=(Re=(Te=(ke=(pe=S.stepId)!=null?pe:S.step_id)!=null?ke:S.step)!=null?Te:S.parentId)!=null?Re:S.flowStepId)!=null?Ye:S.flow_step_id)},j=S=>{var pe,ke,Te,Re,Ye,Ke,pt;return E((pt=(Ke=(Ye=(Re=(Te=(ke=(pe=S.callId)!=null?pe:S.call_id)!=null?ke:S.requestId)!=null?Te:S.request_id)!=null?Re:S.toolCallId)!=null?Ye:S.tool_call_id)!=null?Ke:S.stepId)!=null?pt:S.step_id)},te=r,We=!1,$e=()=>{if(u)return u;let S,pe=T;return!We&&te?(S=te,We=!0):te&&pe?S=`${te}_${pe}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:S,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(u),u},ve=(S,pe)=>{D.lastId=pe,S&&D.byStep.set(S,pe)},Pe=(S,pe)=>{var Ye;let ke=(Ye=S.reasoningId)!=null?Ye:S.id,Te=z(S);if(ke){let Ke=String(ke);return ve(Te,Ke),Ke}if(Te){let Ke=D.byStep.get(Te);if(Ke)return D.lastId=Ke,Ke}if(D.lastId&&!pe)return D.lastId;if(!pe)return null;let Re=`reason-${c()}`;return ve(Te,Re),Re},Oe=S=>{let pe=C.get(S);if(pe)return pe;let ke={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:S,status:"streaming",chunks:[]}};return C.set(S,ke),g(ke),ke},Ae=(S,pe)=>{B.lastId=pe,S&&B.byCall.set(S,pe)},be=new Set,ne=new Map,Q=new Set,ae=new Map,fe=S=>{if(!S)return!1;let pe=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},re=(S,pe)=>{var Ye;let ke=(Ye=S.toolId)!=null?Ye:S.id,Te=j(S);if(ke){let Ke=String(ke);return Ae(Te,Ke),Ke}if(Te){let Ke=B.byCall.get(Te);if(Ke)return B.lastId=Ke,Ke}if(B.lastId&&!pe)return B.lastId;if(!pe)return null;let Re=`tool-${c()}`;return Ae(Te,Re),Re},V=S=>{let pe=I.get(S);if(pe)return pe;let ke={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:S,status:"pending"}};return I.set(S,ke),g(ke),ke},ee=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let pe=Number(S);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let ke=Date.parse(S);if(!Number.isNaN(ke))return ke}return Date.now()},Ue=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},J=new Map,ie=new Map,Le=new Map,at=(S,pe,ke)=>{var pt;let Te=Le.get(S);Te||(Te=[],Le.set(S,Te));let Re=0,Ye=Te.length;for(;Re<Ye;){let It=Re+Ye>>>1;Te[It].seq<pe?Re=It+1:Ye=It}((pt=Te[Re])==null?void 0:pt.seq)===pe?Te[Re]={seq:pe,text:ke}:Te.splice(Re,0,{seq:pe,text:ke});let Ke="";for(let It=0;It<Te.length;It++)Ke+=Te[It].text;return Ke},it=(S,pe)=>{let ke=Ue(pe),Te=ie.get(S.id),Re=ff(Te,ke);S.rawContent=Re;let Ye=J.get(S.id),Ke=K=>{var Ee;let ce=(Ee=S.content)!=null?Ee:"";K.trim()!==""&&(ce.trim().length===0||K.startsWith(ce)||K.trimStart().startsWith(ce.trim()))&&(S.content=K)},pt=()=>{var K;if(Ye){let ce=(K=Ye.close)==null?void 0:K.call(Ye);ce instanceof Promise&&ce.catch(()=>{})}J.delete(S.id),ie.delete(S.id),S.streaming=!1,g(S)};if(!Ye){Ke(ke),pt();return}let It=Is(Re);if(It!==null&&It.trim()!==""){Ke(It),pt();return}let U=K=>{var bt;let ce=typeof K=="string"?K:(bt=K==null?void 0:K.text)!=null?bt:null;if(ce!==null&&ce.trim()!=="")return ce;let Ee=Ye.getExtractedText();return Ee!==null&&Ee.trim()!==""?Ee:ke},rt;try{rt=Ye.processChunk(Re)}catch{Ke(ke),pt();return}if(rt instanceof Promise){rt.then(K=>{Ke(U(K)),pt()}).catch(()=>{Ke(ke),pt()});return}Ke(U(rt)),pt()},nt=null,Me=(S,pe,ke,Te)=>{var It;S.rawContent=pe,J.has(S.id)||J.set(S.id,this.createStreamParser());let Re=J.get(S.id),Ye=pe.trim().startsWith("{")||pe.trim().startsWith("[");if(Ye&&ie.set(S.id,pe),Re.__isPlainTextParser===!0){S.content=Te!==void 0?pe:S.content+ke,ie.delete(S.id),J.delete(S.id),S.rawContent=void 0,g(S);return}let pt=Re.processChunk(pe);if(pt instanceof Promise)pt.then(U=>{var K;let rt=typeof U=="string"?U:(K=U==null?void 0:U.text)!=null?K:null;rt!==null&&rt.trim()!==""?(S.content=rt,g(S)):!Ye&&!pe.trim().startsWith("<")&&(S.content=Te!==void 0?pe:S.content+ke,ie.delete(S.id),J.delete(S.id),S.rawContent=void 0,g(S))}).catch(()=>{S.content=Te!==void 0?pe:S.content+ke,ie.delete(S.id),J.delete(S.id),S.rawContent=void 0,g(S)});else{let U=typeof pt=="string"?pt:(It=pt==null?void 0:pt.text)!=null?It:null;U!==null&&U.trim()!==""?(S.content=U,g(S)):!Ye&&!pe.trim().startsWith("<")&&(S.content=Te!==void 0?pe:S.content+ke,ie.delete(S.id),J.delete(S.id),S.rawContent=void 0,g(S))}},de=(S,pe)=>{var It,U;let ke=pe!=null?pe:S.content;if(ke==null||ke===""){S.streaming=!1,g(S);return}let Te=ie.get(S.id),Re=Te!=null?Te:Ue(ke);S.rawContent=Re;let Ye=J.get(S.id),Ke=null,pt=!1;if(Ye&&(Ke=Ye.getExtractedText(),Ke===null&&(Ke=Is(Re)),Ke===null)){let rt=Ye.processChunk(Re);rt instanceof Promise?(pt=!0,rt.then(K=>{var Ee;let ce=typeof K=="string"?K:(Ee=K==null?void 0:K.text)!=null?Ee:null;ce!==null&&(S.content=ce,S.streaming=!1,J.delete(S.id),ie.delete(S.id),g(S))}).catch(()=>{})):Ke=typeof rt=="string"?rt:(It=rt==null?void 0:rt.text)!=null?It:null}if(!pt){Ke!==null&&Ke.trim()!==""?S.content=Ke:ie.has(S.id)||(S.content=Ue(ke));let rt=J.get(S.id);if(rt){let K=(U=rt.close)==null?void 0:U.call(rt);K instanceof Promise&&K.catch(()=>{}),J.delete(S.id)}ie.delete(S.id),S.streaming=!1,g(S)}},Qe=(S,pe,ke)=>{let Te=k.get(S);if(Te)return Te;let Re={id:`nested-${pe}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ke?{variant:ke}:{},...ke==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:pe}};return k.set(S,Re),g(Re),Re},X=[],le,xe=new Map,ze=0,Lt="agent",Se=null,ue=null,gn=new Map,Pt=(nn=this.config.iterationDisplay)!=null?nn:"separate";for(le=()=>{var S,pe,ke,Te,Re,Ye,Ke,pt,It,U,rt,K,ce,Ee,bt,Jt,Yt,dn,Rt,Ze,Wt,lt,Vt,Xn,Cn,Zt,Pn,hr,vt,Dn,yr,Lr,ar,ht,co,br,po,In,Bo,zr,Pr,jr,Vr,uo,mo,Kr,wt,Nn,Fn,An,At,Jn,Yn,On,Gr,Ir,Qr,_n,Ht,Sn,Zn,Xr,Wr,Jr,vr,$n,he,ct,Gt,rn,xr,us,Rr,go,wr,O,Do,Cr,Ar,Hr,Sr,ir,No,ea,Un,qn,lr,cr,fo,Br,hn,Tr,Fo,ho,Oo,ta,_o,na,$o,ft,ms,er,Wn,ra,oa;for(let Yr=0;Yr<X.length;Yr++){let et=X[Yr].payloadType,w=X[Yr].payload;if(et==="reasoning_start"){let $=typeof w.id=="string"?w.id:null,_=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if($&&_){N.set($,_),Qe($,_,"reasoning");continue}let G=(S=Pe(w,!0))!=null?S:`reason-${c()}`,ge=Oe(G);ge.reasoning=(pe=ge.reasoning)!=null?pe:{id:G,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Te=ge.reasoning.startedAt)!=null?Te:ee((ke=w.startedAt)!=null?ke:w.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(ge.reasoning.scope=w.scope),ge.streaming=!0,ge.reasoning.status="streaming",g(ge)}else if(et==="reasoning_delta"){let $=typeof w.id=="string"?w.id:null;if($&&N.has($)&&k.has($)){let Fe=k.get($),Xe=(Ke=(Ye=(Re=w.reasoningText)!=null?Re:w.text)!=null?Ye:w.delta)!=null?Ke:"";Xe&&w.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(Xe)),g(Fe));continue}let _=(It=(pt=Pe(w,!1))!=null?pt:Pe(w,!0))!=null?It:`reason-${c()}`,G=Oe(_);G.reasoning=(U=G.reasoning)!=null?U:{id:_,status:"streaming",chunks:[]},G.reasoning.startedAt=(K=G.reasoning.startedAt)!=null?K:ee((rt=w.startedAt)!=null?rt:w.timestamp);let ge=(bt=(Ee=(ce=w.reasoningText)!=null?ce:w.text)!=null?Ee:w.delta)!=null?bt:"";if(ge&&w.hidden!==!0){let Fe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Fe!==void 0){let Xe=at(_,Fe,String(ge));G.reasoning.chunks=[Xe]}else G.reasoning.chunks.push(String(ge))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=ee((Jt=w.completedAt)!=null?Jt:w.timestamp);let Fe=(Yt=G.reasoning.startedAt)!=null?Yt:Date.now();G.reasoning.durationMs=Math.max(0,((dn=G.reasoning.completedAt)!=null?dn:Date.now())-Fe)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(et==="reasoning_complete"){let $=typeof w.id=="string"?w.id:null;if($&&N.has($)&&k.has($)){let Xe=k.get($);if(Xe.reasoning){let Mt=typeof w.text=="string"?w.text:"";Mt&&Xe.reasoning.chunks.length===0&&Xe.reasoning.chunks.push(Mt),Xe.reasoning.status="complete",Xe.streaming=!1,g(Xe)}N.delete($),k.delete($);continue}let _=(Ze=(Rt=Pe(w,!1))!=null?Rt:Pe(w,!0))!=null?Ze:`reason-${c()}`,G=typeof w.text=="string"?w.text:"";!C.get(_)&&(G||w.scope==="loop")&&Oe(_);let ge=C.get(_);if(ge!=null&&ge.reasoning){(w.scope==="loop"||w.scope==="turn")&&(ge.reasoning.scope=w.scope),G&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(G),ge.reasoning.status="complete",ge.reasoning.completedAt=ee((Wt=w.completedAt)!=null?Wt:w.timestamp);let Xe=(lt=ge.reasoning.startedAt)!=null?lt:Date.now();ge.reasoning.durationMs=Math.max(0,((Vt=ge.reasoning.completedAt)!=null?Vt:Date.now())-Xe),ge.streaming=!1,g(ge)}let Fe=z(w);Fe&&D.byStep.delete(Fe)}else if(et==="tool_start"){u&&(u.streaming=!1,g(u),u=null),typeof w.iteration=="number"&&(ze=w.iteration);let $=(Cn=(Xn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Xn:re(w,!0))!=null?Cn:`tool-${c()}`,_=(Zt=w.toolName)!=null?Zt:w.name;if(fe(_)){be.add($);continue}Ae(j(w),$);let G=V($),ge=(Pn=G.toolCall)!=null?Pn:{id:$,status:"pending"};ge.name=_!=null?_:ge.name,ge.status="running",w.parameters!==void 0?ge.args=w.parameters:w.args!==void 0&&(ge.args=w.args),ge.startedAt=(vt=ge.startedAt)!=null?vt:ee((hr=w.startedAt)!=null?hr:w.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,G.toolCall=ge,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(et==="tool_output_delta"){let $=(yr=(Dn=re(w,!1))!=null?Dn:re(w,!0))!=null?yr:`tool-${c()}`;if(be.has($))continue;let _=V($),G=(Lr=_.toolCall)!=null?Lr:{id:$,status:"running"};G.startedAt=(ht=G.startedAt)!=null?ht:ee((ar=w.startedAt)!=null?ar:w.timestamp);let ge=(po=(br=(co=w.text)!=null?co:w.delta)!=null?br:w.message)!=null?po:"";ge&&(G.chunks=(In=G.chunks)!=null?In:[],G.chunks.push(String(ge))),G.status="running",_.toolCall=G,_.streaming=!0;let Fe=w.agentContext;(Fe||w.executionId)&&(_.agentMetadata=(Pr=_.agentMetadata)!=null?Pr:{executionId:(Bo=Fe==null?void 0:Fe.executionId)!=null?Bo:w.executionId,iteration:(zr=Fe==null?void 0:Fe.iteration)!=null?zr:w.iteration}),g(_)}else if(et==="tool_complete"){let $=(Vr=(jr=re(w,!1))!=null?jr:re(w,!0))!=null?Vr:`tool-${c()}`;if(be.has($)){be.delete($);continue}let _=V($),G=(uo=_.toolCall)!=null?uo:{id:$,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=ee((mo=w.completedAt)!=null?mo:w.timestamp);let ge=(Kr=w.duration)!=null?Kr:w.executionTime;if(typeof ge=="number")G.durationMs=ge;else{let Mt=(wt=G.startedAt)!=null?wt:Date.now();G.durationMs=Math.max(0,((Nn=G.completedAt)!=null?Nn:Date.now())-Mt)}_.toolCall=G,_.streaming=!1;let Fe=w.agentContext;(Fe||w.executionId)&&(_.agentMetadata=(At=_.agentMetadata)!=null?At:{executionId:(Fn=Fe==null?void 0:Fe.executionId)!=null?Fn:w.executionId,iteration:(An=Fe==null?void 0:Fe.iteration)!=null?An:w.iteration}),g(_);let Xe=j(w);Xe&&B.byCall.delete(Xe)}else if(et==="await"&&w.toolName){let $=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,_=(Jn=$!=null?$:w.toolId)!=null?Jn:`local-${c()}`,G=V(_),ge=w.toolName,Fe=w.origin==="webmcp"&&!Qo(ge)?`webmcp:${ge}`:ge,Xe=Qo(Fe),Mt=(Yn=G.toolCall)!=null?Yn:{id:_,status:"pending"};Mt.name=Fe,Mt.args=w.parameters,Mt.status=Xe?"running":"complete",Mt.chunks=(On=Mt.chunks)!=null?On:[],Mt.startedAt=(Qr=Mt.startedAt)!=null?Qr:ee((Ir=(Gr=w.startedAt)!=null?Gr:w.timestamp)!=null?Ir:w.awaitedAt),Xe?(Mt.completedAt=void 0,Mt.duration=void 0,Mt.durationMs=void 0):Mt.completedAt=(_n=Mt.completedAt)!=null?_n:Mt.startedAt,G.toolCall=Mt,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Sn=w.executionId)!=null?Sn:(Ht=G.agentMetadata)==null?void 0:Ht.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},g(G)}else if(et==="text_start"){let $=typeof w.id=="string"?w.id:null,_=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if($&&_){N.set($,_);continue}let G=u;G&&(Lt==="flow"?(de(G),nt=G):(G.streaming=!1,g(G)),u=null),T=typeof w.id=="string"?w.id:T,M=""}else if(et==="text_delta"){let $=typeof w.id=="string"?w.id:null,_=$?N.get($):void 0;if($&&_){let ge=typeof w.delta=="string"?w.delta:"",Fe=((Zn=W.get($))!=null?Zn:"")+ge;if(W.set($,Fe),Fe.trim()==="")continue;let Xe=Qe($,_);Xe.agentMetadata={...Xe.agentMetadata,executionId:w.executionId,parentToolId:_},Me(Xe,Fe,ge,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Lt==="flow"){let ge=typeof w.delta=="string"?w.delta:"";if(M+=ge,M.trim()==="")continue;let Fe=$e();Fe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Me(Fe,M,ge,void 0),v=Fe;continue}let G=$e();G.content+=(Xr=w.delta)!=null?Xr:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Se!=null?Se:void 0,agentName:ue==null?void 0:ue.agentName},v=G,g(G)}else if(et==="text_complete"){let $=typeof w.id=="string"?w.id:null;if($&&N.has($)){let G=k.get($);G&&de(G),N.delete($),W.delete($),k.delete($);continue}let _=u;_&&(Lt==="flow"?(de(_),nt=_):(((Wr=_.content)!=null?Wr:"")===""&&typeof w.text=="string"&&(_.content=w.text),_.streaming=!1,g(_)),u=null),T=null,M=""}else if(et==="step_complete"){let $=w.stepType,_=w.executionType;if($==="tool"||_==="context")continue;if(w.success===!1){let G=w.error,ge=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Jr=G.message)!=null?Jr:"Step failed"):"Step failed";t({type:"error",error:new Error(ge)});let Fe=u;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),t({type:"status",status:"idle"});continue}{let G=nt;nt=null;let ge=w.stopReason,Fe=(vr=w.result)==null?void 0:vr.response;if(G)ge&&(G.stopReason=ge),Fe!=null?it(G,Fe):G.streaming!==!1&&(J.delete(G.id),ie.delete(G.id),G.streaming=!1,g(G));else{let Xe=Fe!=null&&Fe!=="";if(Xe||ge){let Mt=$e();ge&&(Mt.stopReason=ge),Xe?de(Mt,Fe):(Mt.streaming=!1,g(Mt))}}continue}}else if(et==="execution_start")Lt=w.kind==="flow"?"flow":"agent",Lt==="agent"&&(ue={executionId:w.executionId,agentId:($n=w.agentId)!=null?$n:"virtual",agentName:(he=w.agentName)!=null?he:"",status:"running",currentIteration:0,maxTurns:(ct=w.maxTurns)!=null?ct:1,startedAt:ee(w.startedAt)});else if(et==="turn_start"){let $=typeof w.iteration=="number"?w.iteration:ze;if($!==ze){if(ue&&(ue.currentIteration=$),Pt==="separate"&&$>1){let _=u;_&&(_.streaming=!1,g(_),gn.set($-1,_),u=null)}ze=$}Se=typeof w.id=="string"?w.id:null,v=null}else if(et==="tool_input_delta"){let $=(Gt=w.toolCallId)!=null?Gt:B.lastId;if($){let _=I.get($);_!=null&&_.toolCall&&(_.toolCall.chunks=(rn=_.toolCall.chunks)!=null?rn:[],_.toolCall.chunks.push((xr=w.delta)!=null?xr:""),g(_))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let $=w.stopReason,_=u!=null?u:v;if($&&_!==null){let G=w.id;(!G||((us=_.agentMetadata)==null?void 0:us.turnId)===G)&&(_.stopReason=$,g(_))}Se===w.id&&(Se=null)}else if(et==="media_start"){let $=String(w.id);xe.set($,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(et==="media_delta"){let $=xe.get(String(w.id));$&&typeof w.delta=="string"&&$.parts.push(w.delta)}else if(et==="media_complete"){let $=String(w.id),_=xe.get($);xe.delete($);let G=(go=(Rr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Rr:_==null?void 0:_.mediaType)!=null?go:"application/octet-stream",ge=typeof w.data=="string"?w.data:void 0,Fe=typeof w.url=="string"?w.url:_&&_.parts.length>0?_.parts.join(""):void 0,Xe=null;if(ge)Xe={type:"media",data:ge,mediaType:G};else if(Fe){let zn=G.toLowerCase();Xe={type:zn==="image"||zn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:G}}let Mt=(wr=w.toolCallId)!=null?wr:_==null?void 0:_.toolCallId,Dr=Xe?[Xe]:[],Rn=[];for(let zn of Dr){if(!zn||typeof zn!="object")continue;let pn=zn,Zr=typeof pn.type=="string"?pn.type:void 0,Nr=typeof pn.mediaType=="string"?pn.mediaType.toLowerCase():"",un=null,Hn="";if(Zr==="media"){let jn=typeof pn.data=="string"?pn.data:void 0;if(!jn)continue;Hn=Nr.length>0?Nr:"application/octet-stream",un=`data:${Hn};base64,${jn}`}else if(Zr==="image-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;Hn=Nr,un=jn}else if(Zr==="file-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;Hn=Nr,un=jn}else continue;if(un)if(Zr==="image-url"||Hn.startsWith("image/"))Rn.push({type:"image",image:un,...Hn.includes("/")?{mimeType:Hn}:{}});else if(Hn.startsWith("audio/"))Rn.push({type:"audio",audio:un,mimeType:Hn});else if(Hn.startsWith("video/"))Rn.push({type:"video",video:un,mimeType:Hn});else{let jn=Hn||"application/octet-stream";Rn.push({type:"file",data:un,mimeType:jn,filename:mf(jn)})}}if(Rn.length>0){let zn=c(),pn=Mt,Nr={id:`agent-media-${typeof pn=="string"&&pn.length>0?`${pn}-${zn}`:String(zn)}`,role:"assistant",content:"",contentParts:Rn,createdAt:new Date().toISOString(),streaming:!1,sequence:zn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:ze}};g(Nr);let un=u;un&&(un.streaming=!1,g(un)),u=null,x.current=null}}else if(et==="execution_complete"){let $=(O=w.kind)!=null?O:Lt;$==="agent"&&ue&&(ue.status=w.success?"complete":"error",ue.completedAt=ee(w.completedAt),ue.stopReason=w.stopReason);let _=u;_&&($==="flow"&&_.streaming!==!1?de(_):(_.streaming=!1,g(_)),u=null),T=null,M="",nt=null,t({type:"status",status:"idle"})}else if(et==="execution_error"){let $=typeof w.error=="string"?w.error:(Cr=(Do=w.error)==null?void 0:Do.message)!=null?Cr:"Execution error";t({type:"error",error:new Error($)})}else if(et!=="ping"){if(et==="approval_start"){let $=(Ar=w.approvalId)!=null?Ar:`approval-${c()}`,_={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Hr=ue==null?void 0:ue.agentId)!=null?Hr:"virtual",executionId:(ir=(Sr=w.executionId)!=null?Sr:ue==null?void 0:ue.executionId)!=null?ir:"",toolName:(No=w.toolName)!=null?No:"",toolType:w.toolType,description:(Un=w.description)!=null?Un:`Execute ${(ea=w.toolName)!=null?ea:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(_)}else if(et==="step_await"&&w.awaitReason==="approval_required"){let $=(qn=w.approvalId)!=null?qn:`approval-${c()}`,_={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(lr=ue==null?void 0:ue.agentId)!=null?lr:"virtual",executionId:(fo=(cr=w.executionId)!=null?cr:ue==null?void 0:ue.executionId)!=null?fo:"",toolName:(Br=w.toolName)!=null?Br:"",toolType:w.toolType,description:(Tr=w.description)!=null?Tr:`Execute ${(hn=w.toolName)!=null?hn:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(_)}else if(et==="approval_complete"){let $=w.approvalId;if($){let G={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(Fo=w.decision)!=null?Fo:"approved",agentId:(ho=ue==null?void 0:ue.agentId)!=null?ho:"virtual",executionId:(ta=(Oo=w.executionId)!=null?Oo:ue==null?void 0:ue.executionId)!=null?ta:"",toolName:(_o=w.toolName)!=null?_o:"",description:(na=w.description)!=null?na:"",resolvedAt:Date.now()}};g(G)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let $=w.artifactType,_=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(t({type:"artifact_start",id:_,artifactType:$,title:G,component:typeof w.component=="string"?w.component:void 0}),ae.set(_,{markdown:"",title:G}),!Q.has(_)){Q.add(_);let ge={id:`artifact-ref-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:_,title:G,artifactType:$,status:"streaming"}})};ne.set(_,ge),g(ge)}}else if(et==="artifact_delta"){let $=String(w.id),_=typeof w.delta=="string"?w.delta:String(($o=w.delta)!=null?$o:"");t({type:"artifact_delta",id:$,artDelta:_});let G=ae.get($);G&&(G.markdown+=_)}else if(et==="artifact_update"){let $=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};t({type:"artifact_update",id:String(w.id),props:$,component:typeof w.component=="string"?w.component:void 0})}else if(et==="artifact_complete"){let $=String(w.id);t({type:"artifact_complete",id:$});let _=ne.get($);if(_){_.streaming=!1;try{let G=JSON.parse((ft=_.rawContent)!=null?ft:"{}");if(G.props){G.props.status="complete";let ge=ae.get($);ge!=null&&ge.markdown&&(G.props.markdown=ge.markdown)}_.rawContent=JSON.stringify(G)}catch{}ae.delete($),g(_),ne.delete($)}}}else if(et==="transcript_insert"){let $=w.message;if(!$||typeof $!="object")continue;let _=String((ms=$.id)!=null?ms:`msg-${c()}`),G=$.role,Fe={id:_,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(g(Fe),Fe.rawContent)try{let Xe=JSON.parse(Fe.rawContent),Mt=(er=Xe==null?void 0:Xe.props)==null?void 0:er.artifactId;typeof Mt=="string"&&Q.add(Mt)}catch{}u=null,x.current=null,J.delete(_),ie.delete(_)}else if(et==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let $=typeof w.error=="string"?w.error:((Wn=w.error)==null?void 0:Wn.message)!=null?String(w.error.message):"Execution error";t({type:"error",error:new Error($)});let _=u;_&&_.streaming&&(_.streaming=!1,g(_)),t({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let $=null;if(w.error instanceof Error)$=w.error;else if(et==="dispatch_error"){let _=(ra=w.message)!=null?ra:w.error;_!=null&&_!==""&&($=new Error(String(_)))}else{let _=w.error;typeof _=="string"&&_!==""?$=new Error(_):_!=null&&typeof _=="object"&&"message"in _&&($=new Error(String((oa=_.message)!=null?oa:_)))}if($){t({type:"error",error:$});let _=u;_&&_.streaming&&(_.streaming=!1,g(_)),t({type:"status",status:"idle"})}}}}}X.length=0};;){let{done:S,value:pe}=await o.read();if(S)break;a+=s.decode(pe,{stream:!0});let ke=a.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async r=>{if(r.length<=e)return t!==null?{text:t,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(t=s),e=r.length,t!==null?{text:t,raw:r}:null},close:async()=>{}}},Ds=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},du=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},pu=()=>{var e;let t=vf();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:t.processChunk(n)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},uu=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let o=gf(n,ff|hf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?iu(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=iu(o.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var mu=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(t=r[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var gu="4.2.1";var Ns=gu;var wf="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function Cf(t){var s,a;let e=t.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Mi=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Af(t){switch(t){case"json":return uu;case"regex-json":return pu;case"xml":return mu;default:return du}}var fu=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Sf(t,e){if(!t)return e;let n=t.trim(),r=e.trim();if(n.length===0)return e;if(r.length===0)return t;let o=fu(n);if(!fu(r))return t;if(!o||r===n||r.startsWith(n))return e;let a=Ds(t);return Ds(e)!==null&&a===null?e:t}var Fs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=e.apiUrl)!=null?n:wf,this.headers={"Content-Type":"application/json","X-Persona-Version":Ns,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:Af(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new ya(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,n;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 r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(e=this.config).onSessionInit)==null||n.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(n)});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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/feedback`}async sendFeedback(e){var a,i;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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return this.isAgentMode()?this.dispatchAgent(e,n):this.isClientTokenMode()?this.dispatchClientToken(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Mi).map(E=>{var P,C,L;return{id:E.id,role:E.role,content:(L=(C=(P=E.contentParts)!=null?P:E.llmContent)!=null?C:E.rawContent)!=null?L:E.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,m=!!(g&&g.length>0),x=m?jp(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&v&&this.lastSentClientToolsFingerprint===x,W=!1,T=null,k;for(let E=0;;E++){let C={...f,...m&&(W||!M)&&g?{clientTools:g}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(C),signal:r.signal}),k.status===409&&E===0&&m){let L=await k.json().catch(()=>null);if((L==null?void 0:L.error)==="client_tools_resend_required"){W=!0,this.lastSentClientToolsFingerprint=null;continue}T=L!=null?L:{error:"Chat request failed"}}break}if(!k.ok){let E=T!=null?T:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(E.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(e,n,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Sa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:n,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=e.slice().filter(Mi).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return c-u}).map(i=>{var d,c,u;return{role:i.role,content:(u=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ti(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(e){var s,a;let r={messages:e.slice().filter(Mi).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return c-u}).map(i=>{var d,c,u;return{role:i.role,content:(u=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ti(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=f,o(f),f},c=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.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!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,n,r){var Bt,Xt,Ir,hr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Te=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Re=A.tools?A.tools.map(ke=>({...ke,chunks:ke.chunks?[...ke.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Te,tools:Re}},f=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Te=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Te||!!A.stopReason},g=A=>{f(A)&&n({type:"message",message:u(A)})},m=null,x=null,v={current:null},M={current:null},W=null,T="",k=new Map,E=new Map,P=new Map,C=new Map,L=new Map,F={lastId:null,byStep:new Map},O={lastId:null,byCall:new Map},R=A=>{if(A==null)return null;try{return String(A)}catch{return null}},$=A=>{var te,Te,Re,ke,Be;return R((Be=(ke=(Re=(Te=(te=A.stepId)!=null?te:A.step_id)!=null?Te:A.step)!=null?Re:A.parentId)!=null?ke:A.flowStepId)!=null?Be:A.flow_step_id)},N=A=>{var te,Te,Re,ke,Be,Ve,at;return R((at=(Ve=(Be=(ke=(Re=(Te=(te=A.callId)!=null?te:A.call_id)!=null?Te:A.requestId)!=null?Re:A.request_id)!=null?ke:A.toolCallId)!=null?Be:A.tool_call_id)!=null?Ve:A.stepId)!=null?at:A.step_id)},Z=r,Se=!1,pe=()=>{if(m)return m;let A,te=W;return!Se&&Z?(A=Z,Se=!0):Z&&te?A=`${Z}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(m),m},ee=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},ve=(A,te)=>{var Be;let Te=(Be=A.reasoningId)!=null?Be:A.id,Re=$(A);if(Te){let Ve=String(Te);return ee(Re,Ve),Ve}if(Re){let Ve=F.byStep.get(Re);if(Ve)return F.lastId=Ve,Ve}if(F.lastId&&!te)return F.lastId;if(!te)return null;let ke=`reason-${c()}`;return ee(Re,ke),ke},Ie=A=>{let te=C.get(A);if(te)return te;let Te={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Te),g(Te),Te},ce=(A,te)=>{O.lastId=te,A&&O.byCall.set(A,te)},ue=new Set,oe=new Map,se=new Set,de=new Map,$e=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Ne=(A,te)=>{var Be;let Te=(Be=A.toolId)!=null?Be:A.id,Re=N(A);if(Te){let Ve=String(Te);return ce(Re,Ve),Ve}if(Re){let Ve=O.byCall.get(Re);if(Ve)return O.lastId=Ve,Ve}if(O.lastId&&!te)return O.lastId;if(!te)return null;let ke=`tool-${c()}`;return ce(Re,ke),ke},V=A=>{let te=L.get(A);if(te)return te;let Te={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:A,status:"pending"}};return L.set(A,Te),g(Te),Te},G=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Te=Date.parse(A);if(!Number.isNaN(Te))return Te}return Date.now()},be=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},X=new Map,le=new Map,Ee=new Map,Xe=(A,te,Te)=>{var at;let Re=Ee.get(A);Re||(Re=[],Ee.set(A,Re));let ke=0,Be=Re.length;for(;ke<Be;){let Pt=ke+Be>>>1;Re[Pt].seq<te?ke=Pt+1:Be=Pt}((at=Re[ke])==null?void 0:at.seq)===te?Re[ke]={seq:te,text:Te}:Re.splice(ke,0,{seq:te,text:Te});let Ve="";for(let Pt=0;Pt<Re.length;Pt++)Ve+=Re[Pt].text;return Ve},Ze=(A,te)=>{let Te=be(te),Re=le.get(A.id),ke=Sf(Re,Te);A.rawContent=ke;let Be=X.get(A.id),Ve=J=>{var it;let Ae=(it=A.content)!=null?it:"";J.trim()!==""&&(Ae.trim().length===0||J.startsWith(Ae)||J.trimStart().startsWith(Ae.trim()))&&(A.content=J)},at=()=>{var J;if(Be){let Ae=(J=Be.close)==null?void 0:J.call(Be);Ae instanceof Promise&&Ae.catch(()=>{})}X.delete(A.id),le.delete(A.id),A.streaming=!1,g(A)};if(!Be){Ve(Te),at();return}let Pt=Ds(ke);if(Pt!==null&&Pt.trim()!==""){Ve(Pt),at();return}let bt=J=>{var Qe;let Ae=typeof J=="string"?J:(Qe=J==null?void 0:J.text)!=null?Qe:null;if(Ae!==null&&Ae.trim()!=="")return Ae;let it=Be.getExtractedText();return it!==null&&it.trim()!==""?it:Te},H;try{H=Be.processChunk(ke)}catch{Ve(Te),at();return}if(H instanceof Promise){H.then(J=>{Ve(bt(J)),at()}).catch(()=>{Ve(Te),at()});return}Ve(bt(H)),at()},wt=null,dt=(A,te,Te,Re)=>{var Pt;A.rawContent=te,X.has(A.id)||X.set(A.id,this.createStreamParser());let ke=X.get(A.id),Be=te.trim().startsWith("{")||te.trim().startsWith("[");if(Be&&le.set(A.id,te),ke.__isPlainTextParser===!0){A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A);return}let at=ke.processChunk(te);if(at instanceof Promise)at.then(bt=>{var J;let H=typeof bt=="string"?bt:(J=bt==null?void 0:bt.text)!=null?J:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!Be&&!te.trim().startsWith("<")&&(A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A)});else{let bt=typeof at=="string"?at:(Pt=at==null?void 0:at.text)!=null?Pt:null;bt!==null&&bt.trim()!==""?(A.content=bt,g(A)):!Be&&!te.trim().startsWith("<")&&(A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A))}},Ye=(A,te)=>{var Pt,bt;let Te=te!=null?te:A.content;if(Te==null||Te===""){A.streaming=!1,g(A);return}let Re=le.get(A.id),ke=Re!=null?Re:be(Te);A.rawContent=ke;let Be=X.get(A.id),Ve=null,at=!1;if(Be&&(Ve=Be.getExtractedText(),Ve===null&&(Ve=Ds(ke)),Ve===null)){let H=Be.processChunk(ke);H instanceof Promise?(at=!0,H.then(J=>{var it;let Ae=typeof J=="string"?J:(it=J==null?void 0:J.text)!=null?it:null;Ae!==null&&(A.content=Ae,A.streaming=!1,X.delete(A.id),le.delete(A.id),g(A))}).catch(()=>{})):Ve=typeof H=="string"?H:(Pt=H==null?void 0:H.text)!=null?Pt:null}if(!at){Ve!==null&&Ve.trim()!==""?A.content=Ve:le.has(A.id)||(A.content=be(Te));let H=X.get(A.id);if(H){let J=(bt=H.close)==null?void 0:bt.call(H);J instanceof Promise&&J.catch(()=>{}),X.delete(A.id)}le.delete(A.id),A.streaming=!1,g(A)}},He=(A,te,Te)=>{let Re=E.get(A);if(Re)return Re;let ke={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return E.set(A,ke),g(ke),ke},K=[],qe,ze=new Map,xe=0,Ce="agent",tt=!1,Ot=null,ne=null,Oe=new Map,gn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(qe=()=>{var A,te,Te,Re,ke,Be,Ve,at,Pt,bt,H,J,Ae,it,Qe,Ut,fn,vt,xt,It,Ct,ln,_t,Nn,Sn,Tn,bn,En,ar,At,yr,br,Wr,ir,ut,mo,vr,go,Wn,Oo,Kr,Rr,Gr,Qr,fo,ho,Xr,yt,Fn,On,Mn,St,Xn,Jn,_n,Jr,Hr,Yr,$n,Wt,kn,Yn,Zr,Br,eo,he,Rn,xr,mt,nn,rn,wr,hs,Dr,yo,Cr,U,_o,Ar,Sr,Nr,Tr,lr,$o,sa,Un,zn,cr,dr,bo,Fr,vn,Er,Uo,vo,zo,aa,qo,ia,jo,pt,ys,Zn,Hn,la;for(let Vo=0;Vo<K.length;Vo++){let et=K[Vo].payloadType,w=K[Vo].payload;if(!tt&&Ce!=="flow"&&typeof w.stepType=="string"&&(Ce="flow"),et==="reasoning_start"){let j=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&z){k.set(j,z),He(j,z,"reasoning");continue}let Q=(A=ve(w,!0))!=null?A:`reason-${c()}`,ge=Ie(Q);ge.reasoning=(te=ge.reasoning)!=null?te:{id:Q,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Re=ge.reasoning.startedAt)!=null?Re:G((Te=w.startedAt)!=null?Te:w.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(ge.reasoning.scope=w.scope),ge.streaming=!0,ge.reasoning.status="streaming",g(ge)}else if(et==="reasoning_delta"){let j=typeof w.id=="string"?w.id:null;if(j&&k.has(j)&&E.has(j)){let Fe=E.get(j),gt=(Ve=(Be=(ke=w.reasoningText)!=null?ke:w.text)!=null?Be:w.delta)!=null?Ve:"";gt&&w.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(gt)),g(Fe));continue}let z=(Pt=(at=ve(w,!1))!=null?at:ve(w,!0))!=null?Pt:`reason-${c()}`,Q=Ie(z);Q.reasoning=(bt=Q.reasoning)!=null?bt:{id:z,status:"streaming",chunks:[]},Q.reasoning.startedAt=(J=Q.reasoning.startedAt)!=null?J:G((H=w.startedAt)!=null?H:w.timestamp);let ge=(Qe=(it=(Ae=w.reasoningText)!=null?Ae:w.text)!=null?it:w.delta)!=null?Qe:"";if(ge&&w.hidden!==!0){let Fe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Fe!==void 0){let gt=Xe(z,Fe,String(ge));Q.reasoning.chunks=[gt]}else Q.reasoning.chunks.push(String(ge))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=G((Ut=w.completedAt)!=null?Ut:w.timestamp);let Fe=(fn=Q.reasoning.startedAt)!=null?fn:Date.now();Q.reasoning.durationMs=Math.max(0,((vt=Q.reasoning.completedAt)!=null?vt:Date.now())-Fe)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(et==="reasoning_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&k.has(j)&&E.has(j)){let gt=E.get(j);if(gt.reasoning){let ot=typeof w.text=="string"?w.text:"";ot&&gt.reasoning.chunks.length===0&&gt.reasoning.chunks.push(ot),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(j),E.delete(j);continue}let z=(It=(xt=ve(w,!1))!=null?xt:ve(w,!0))!=null?It:`reason-${c()}`,Q=typeof w.text=="string"?w.text:"";!C.get(z)&&(Q||w.scope==="loop")&&Ie(z);let ge=C.get(z);if(ge!=null&&ge.reasoning){(w.scope==="loop"||w.scope==="turn")&&(ge.reasoning.scope=w.scope),Q&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(Q),ge.reasoning.status="complete",ge.reasoning.completedAt=G((Ct=w.completedAt)!=null?Ct:w.timestamp);let gt=(ln=ge.reasoning.startedAt)!=null?ln:Date.now();ge.reasoning.durationMs=Math.max(0,((_t=ge.reasoning.completedAt)!=null?_t:Date.now())-gt),ge.streaming=!1,g(ge)}let Fe=$(w);Fe&&F.byStep.delete(Fe)}else if(et==="tool_start"){m&&(m.streaming=!1,g(m),m=null),typeof w.iteration=="number"&&(xe=w.iteration);let j=(Sn=(Nn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Nn:Ne(w,!0))!=null?Sn:`tool-${c()}`,z=(Tn=w.toolName)!=null?Tn:w.name;if($e(z)){ue.add(j);continue}ce(N(w),j);let Q=V(j),ge=(bn=Q.toolCall)!=null?bn:{id:j,status:"pending"};ge.name=z!=null?z:ge.name,ge.status="running",w.parameters!==void 0?ge.args=w.parameters:w.args!==void 0&&(ge.args=w.args),ge.startedAt=(ar=ge.startedAt)!=null?ar:G((En=w.startedAt)!=null?En:w.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,Q.toolCall=ge,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(Q)}else if(et==="tool_output_delta"){let j=(yr=(At=Ne(w,!1))!=null?At:Ne(w,!0))!=null?yr:`tool-${c()}`;if(ue.has(j))continue;let z=V(j),Q=(br=z.toolCall)!=null?br:{id:j,status:"running"};Q.startedAt=(ir=Q.startedAt)!=null?ir:G((Wr=w.startedAt)!=null?Wr:w.timestamp);let ge=(vr=(mo=(ut=w.text)!=null?ut:w.delta)!=null?mo:w.message)!=null?vr:"";ge&&(Q.chunks=(go=Q.chunks)!=null?go:[],Q.chunks.push(String(ge))),Q.status="running",z.toolCall=Q,z.streaming=!0;let Fe=w.agentContext;(Fe||w.executionId)&&(z.agentMetadata=(Kr=z.agentMetadata)!=null?Kr:{executionId:(Wn=Fe==null?void 0:Fe.executionId)!=null?Wn:w.executionId,iteration:(Oo=Fe==null?void 0:Fe.iteration)!=null?Oo:w.iteration}),g(z)}else if(et==="tool_complete"){let j=(Gr=(Rr=Ne(w,!1))!=null?Rr:Ne(w,!0))!=null?Gr:`tool-${c()}`;if(ue.has(j)){ue.delete(j);continue}let z=V(j),Q=(Qr=z.toolCall)!=null?Qr:{id:j,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=G((fo=w.completedAt)!=null?fo:w.timestamp);let ge=(ho=w.duration)!=null?ho:w.executionTime;if(typeof ge=="number")Q.durationMs=ge;else{let ot=(Xr=Q.startedAt)!=null?Xr:Date.now();Q.durationMs=Math.max(0,((yt=Q.completedAt)!=null?yt:Date.now())-ot)}z.toolCall=Q,z.streaming=!1;let Fe=w.agentContext;(Fe||w.executionId)&&(z.agentMetadata=(Mn=z.agentMetadata)!=null?Mn:{executionId:(Fn=Fe==null?void 0:Fe.executionId)!=null?Fn:w.executionId,iteration:(On=Fe==null?void 0:Fe.iteration)!=null?On:w.iteration}),g(z);let gt=N(w);gt&&O.byCall.delete(gt)}else if(et==="await"&&w.toolName){let j=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,z=(St=j!=null?j:w.toolId)!=null?St:`local-${c()}`,Q=V(z),ge=w.toolName,Fe=w.origin==="webmcp"&&!es(ge)?`webmcp:${ge}`:ge,gt=es(Fe),ot=(Xn=Q.toolCall)!=null?Xn:{id:z,status:"pending"};ot.name=Fe,ot.args=w.parameters,ot.status=gt?"running":"complete",ot.chunks=(Jn=ot.chunks)!=null?Jn:[],ot.startedAt=(Hr=ot.startedAt)!=null?Hr:G((Jr=(_n=w.startedAt)!=null?_n:w.timestamp)!=null?Jr:w.awaitedAt),gt?(ot.completedAt=void 0,ot.duration=void 0,ot.durationMs=void 0):ot.completedAt=(Yr=ot.completedAt)!=null?Yr:ot.startedAt,Q.toolCall=ot,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Wt=w.executionId)!=null?Wt:($n=Q.agentMetadata)==null?void 0:$n.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Q)}else if(et==="text_start"){let j=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&z){k.set(j,z);continue}let Q=m;Q&&(Ce==="flow"?(Ye(Q),wt=Q):(Q.streaming=!1,g(Q)),m=null),W=typeof w.id=="string"?w.id:W,T=""}else if(et==="text_delta"){let j=typeof w.id=="string"?w.id:null,z=j?k.get(j):void 0;if(j&&z){let ge=typeof w.delta=="string"?w.delta:"",Fe=((kn=P.get(j))!=null?kn:"")+ge;if(P.set(j,Fe),Fe.trim()==="")continue;let gt=He(j,z);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:z},dt(gt,Fe,ge,void 0);continue}if(W=typeof w.id=="string"?w.id:W,Ce==="flow"){let ge=typeof w.delta=="string"?w.delta:"";if(T+=ge,T.trim()==="")continue;let Fe=pe();Fe.agentMetadata={executionId:w.executionId,iteration:w.iteration},dt(Fe,T,ge,void 0),x=Fe;continue}let Q=pe();Q.content+=(Yn=w.delta)!=null?Yn:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ot!=null?Ot:void 0,agentName:ne==null?void 0:ne.agentName},x=Q,g(Q)}else if(et==="text_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&k.has(j)){let Q=E.get(j);Q&&Ye(Q),k.delete(j),P.delete(j),E.delete(j);continue}let z=m;z&&(Ce==="flow"?(Ye(z),wt=z):(((Zr=z.content)!=null?Zr:"")===""&&typeof w.text=="string"&&(z.content=w.text),z.streaming=!1,g(z)),m=null),W=null,T=""}else if(et==="step_complete"){let j=w.stepType,z=w.executionType;if(j==="tool"||z==="context")continue;if(w.success===!1){let Q=w.error,ge=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((Br=Q.message)!=null?Br:"Step failed"):"Step failed";n({type:"error",error:new Error(ge)});let Fe=m;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),n({type:"status",status:"idle"});continue}{let Q=wt;wt=null;let ge=w.stopReason,Fe=(eo=w.result)==null?void 0:eo.response;if(Q)ge&&(Q.stopReason=ge),Fe!=null?Ze(Q,Fe):Q.streaming!==!1&&(X.delete(Q.id),le.delete(Q.id),Q.streaming=!1,g(Q));else{let gt=Fe!=null&&Fe!=="";if(gt||ge){let ot=pe();ge&&(ot.stopReason=ge),gt?Ye(ot,Fe):(ot.streaming=!1,g(ot))}}continue}}else if(et==="execution_start")Ce=w.kind==="flow"?"flow":"agent",tt=!0,Ce==="agent"&&(ne={executionId:w.executionId,agentId:(he=w.agentId)!=null?he:"virtual",agentName:(Rn=w.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(xr=w.maxTurns)!=null?xr:1,startedAt:G(w.startedAt)});else if(et==="turn_start"){let j=typeof w.iteration=="number"?w.iteration:xe;if(j!==xe){if(ne&&(ne.currentIteration=j),gn==="separate"&&j>1){let z=m;z&&(z.streaming=!1,g(z),Oe.set(j-1,z),m=null)}xe=j}Ot=typeof w.id=="string"?w.id:null,x=null}else if(et==="tool_input_delta"){let j=(mt=w.toolCallId)!=null?mt:O.lastId;if(j){let z=L.get(j);z!=null&&z.toolCall&&(z.toolCall.chunks=(nn=z.toolCall.chunks)!=null?nn:[],z.toolCall.chunks.push((rn=w.delta)!=null?rn:""),g(z))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let j=w.stopReason,z=m!=null?m:x;if(j&&z!==null){let Q=w.id;(!Q||((wr=z.agentMetadata)==null?void 0:wr.turnId)===Q)&&(z.stopReason=j,g(z))}Ot===w.id&&(Ot=null)}else if(et==="media_start"){let j=String(w.id);ze.set(j,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(et==="media_delta"){let j=ze.get(String(w.id));j&&typeof w.delta=="string"&&j.parts.push(w.delta)}else if(et==="media_complete"){let j=String(w.id),z=ze.get(j);ze.delete(j);let Q=(Dr=(hs=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?hs:z==null?void 0:z.mediaType)!=null?Dr:"application/octet-stream",ge=typeof w.data=="string"?w.data:void 0,Fe=typeof w.url=="string"?w.url:z&&z.parts.length>0?z.parts.join(""):void 0,gt=null;if(ge)gt={type:"media",data:ge,mediaType:Q};else if(Fe){let cn=Q.toLowerCase();gt={type:cn==="image"||cn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:Q}}let ot=(yo=w.toolCallId)!=null?yo:z==null?void 0:z.toolCallId,bs=gt?[gt]:[],Bn=[];for(let cn of bs){if(!cn||typeof cn!="object")continue;let dn=cn,xo=typeof dn.type=="string"?dn.type:void 0,Or=typeof dn.mediaType=="string"?dn.mediaType.toLowerCase():"",Ln=null,hn="";if(xo==="media"){let qn=typeof dn.data=="string"?dn.data:void 0;if(!qn)continue;hn=Or.length>0?Or:"application/octet-stream",Ln=`data:${hn};base64,${qn}`}else if(xo==="image-url"){let qn=typeof dn.url=="string"?dn.url:void 0;if(!qn)continue;hn=Or,Ln=qn}else if(xo==="file-url"){let qn=typeof dn.url=="string"?dn.url:void 0;if(!qn)continue;hn=Or,Ln=qn}else continue;if(Ln)if(xo==="image-url"||hn.startsWith("image/"))Bn.push({type:"image",image:Ln,...hn.includes("/")?{mimeType:hn}:{}});else if(hn.startsWith("audio/"))Bn.push({type:"audio",audio:Ln,mimeType:hn});else if(hn.startsWith("video/"))Bn.push({type:"video",video:Ln,mimeType:hn});else{let qn=hn||"application/octet-stream";Bn.push({type:"file",data:Ln,mimeType:qn,filename:Cf(qn)})}}if(Bn.length>0){let cn=c(),dn=ot,Or={id:`agent-media-${typeof dn=="string"&&dn.length>0?`${dn}-${cn}`:String(cn)}`,role:"assistant",content:"",contentParts:Bn,createdAt:new Date().toISOString(),streaming:!1,sequence:cn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:xe}};g(Or);let Ln=m;Ln&&(Ln.streaming=!1,g(Ln)),m=null,v.current=null}}else if(et==="execution_complete"){let j=(Cr=w.kind)!=null?Cr:Ce;j==="agent"&&ne&&(ne.status=w.success?"complete":"error",ne.completedAt=G(w.completedAt),ne.stopReason=w.stopReason);let z=m;z&&(j==="flow"&&z.streaming!==!1?Ye(z):(z.streaming=!1,g(z)),m=null),W=null,T="",wt=null,n({type:"status",status:"idle"})}else if(et==="execution_error"){let j=typeof w.error=="string"?w.error:(_o=(U=w.error)==null?void 0:U.message)!=null?_o:"Execution error";n({type:"error",error:new Error(j)})}else if(et!=="ping"){if(et==="approval_start"){let j=(Ar=w.approvalId)!=null?Ar:`approval-${c()}`,z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(Sr=ne==null?void 0:ne.agentId)!=null?Sr:"virtual",executionId:(Tr=(Nr=w.executionId)!=null?Nr:ne==null?void 0:ne.executionId)!=null?Tr:"",toolName:(lr=w.toolName)!=null?lr:"",toolType:w.toolType,description:(sa=w.description)!=null?sa:`Execute ${($o=w.toolName)!=null?$o:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(et==="step_await"&&w.awaitReason==="approval_required"){let j=(Un=w.approvalId)!=null?Un:`approval-${c()}`,z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(zn=ne==null?void 0:ne.agentId)!=null?zn:"virtual",executionId:(dr=(cr=w.executionId)!=null?cr:ne==null?void 0:ne.executionId)!=null?dr:"",toolName:(bo=w.toolName)!=null?bo:"",toolType:w.toolType,description:(vn=w.description)!=null?vn:`Execute ${(Fr=w.toolName)!=null?Fr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(et==="approval_complete"){let j=w.approvalId;if(j){let Q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:(Er=w.decision)!=null?Er:"approved",agentId:(Uo=ne==null?void 0:ne.agentId)!=null?Uo:"virtual",executionId:(zo=(vo=w.executionId)!=null?vo:ne==null?void 0:ne.executionId)!=null?zo:"",toolName:(aa=w.toolName)!=null?aa:"",description:(qo=w.description)!=null?qo:"",resolvedAt:Date.now()}};g(Q)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let j=w.artifactType,z=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:z,artifactType:j,title:Q,component:typeof w.component=="string"?w.component:void 0}),de.set(z,{markdown:"",title:Q}),!se.has(z)){se.add(z);let ge={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:Q,artifactType:j,status:"streaming"}})};oe.set(z,ge),g(ge)}}else if(et==="artifact_delta"){let j=String(w.id),z=typeof w.delta=="string"?w.delta:String((ia=w.delta)!=null?ia:"");n({type:"artifact_delta",id:j,artDelta:z});let Q=de.get(j);Q&&(Q.markdown+=z)}else if(et==="artifact_update"){let j=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:j,component:typeof w.component=="string"?w.component:void 0})}else if(et==="artifact_complete"){let j=String(w.id);n({type:"artifact_complete",id:j});let z=oe.get(j);if(z){z.streaming=!1;try{let Q=JSON.parse((jo=z.rawContent)!=null?jo:"{}");if(Q.props){Q.props.status="complete";let ge=de.get(j);ge!=null&&ge.markdown&&(Q.props.markdown=ge.markdown)}z.rawContent=JSON.stringify(Q)}catch{}de.delete(j),g(z),oe.delete(j)}}}else if(et==="transcript_insert"){let j=w.message;if(!j||typeof j!="object")continue;let z=String((pt=j.id)!=null?pt:`msg-${c()}`),Q=j.role,Fe={id:z,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:c()};if(g(Fe),Fe.rawContent)try{let gt=JSON.parse(Fe.rawContent),ot=(ys=gt==null?void 0:gt.props)==null?void 0:ys.artifactId;typeof ot=="string"&&se.add(ot)}catch{}m=null,v.current=null,X.delete(z),le.delete(z)}else if(et==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let j=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(j)});let z=m;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let j=null;if(w.error instanceof Error)j=w.error;else if(et==="dispatch_error"){let z=(Hn=w.message)!=null?Hn:w.error;z!=null&&z!==""&&(j=new Error(String(z)))}else{let z=w.error;typeof z=="string"&&z!==""?j=new Error(z):z!=null&&typeof z=="object"&&"message"in z&&(j=new Error(String((la=z.message)!=null?la:z)))}if(j){n({type:"error",error:j});let z=m;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}}}}K.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Te=a.split(`
12
12
 
13
- `);a=(fr=ke.pop())!=null?fr:"";for(let Te of ke){let Re=Te.split(`
14
- `),Ye="message",Ke="";for(let U of Re)U.startsWith("event:")?Ye=U.replace("event:","").trim():U.startsWith("data:")&&(Ke+=U.replace("data:","").trim());if(!Ke)continue;let pt;try{pt=JSON.parse(Ke)}catch(U){t({type:"error",error:U instanceof Error?U:new Error("Failed to parse chat stream payload")});continue}let It=Ye!=="message"?Ye:(fn=pt.type)!=null?fn:"message";if((je=this.onSSEEvent)==null||je.call(this,It,pt),this.parseSSEEvent){x.current=u;let U=await this.handleCustomSSEEvent(pt,t,x,g,c,P);if(x.current&&x.current!==u&&(u=x.current),U)continue}X.push({payloadType:It,payload:pt}),le()}}le()}};function wa(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Hs(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ca="[Image]";function Ti(n){return{type:"text",text:n}}var uu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],hf=["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"],$r=[...uu,...hf];function yf(n){return uu.includes(n)||n.startsWith("image/")}function Aa(n){return yf(n.type)}async function mu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Aa(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function gu(n,e=$r,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function bf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function fu(n,e){let t=bf(e).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"}[n]||t||"FILE"}Mi();var hu=16e3,vf=24e3,xf=4096,wf=1380533830;function Cf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===wf?new Uint8Array(n,44):new Uint8Array(n)}function Af(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Bs=class{constructor(e){this.config=e;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(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:hu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let m=window.AudioContext||window.webkitAudioContext,f=new m({sampleRate:hu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ts(vf);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${Af(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(u,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let P=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${P}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}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(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(xf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let m=0;m<d.length;m++){let f=Math.max(-1,Math.min(1,d[m]));c[m]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=Cf(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}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(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var Lo=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ns(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Bs(n.runtype);case"browser":if(!Lo.isSupported())throw new Error("Browser speech recognition not supported");return new Lo(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function yu(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ns({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ns({type:"runtype",runtype:n.runtype});if(Lo.isSupported())return ns({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ei(n){try{return yu(n),!0}catch{return!1}}function Sa(n){var t;let e=["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 r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var rs=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Sa(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,m;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(m=t.onError)==null||m.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Ds=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(t,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function ki(n){if(!n)return"";let e=Sf(n);return bu(e!==null?e:n)}function Sf(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function bu(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
13
+ `);a=(Xt=Te.pop())!=null?Xt:"";for(let Re of Te){let ke=Re.split(`
14
+ `),Be="message",Ve="";for(let bt of ke)bt.startsWith("event:")?Be=bt.replace("event:","").trim():bt.startsWith("data:")&&(Ve+=bt.replace("data:","").trim());if(!Ve)continue;let at;try{at=JSON.parse(Ve)}catch(bt){n({type:"error",error:bt instanceof Error?bt:new Error("Failed to parse chat stream payload")});continue}let Pt=Be!=="message"?Be:(Ir=at.type)!=null?Ir:"message";if((hr=this.onSSEEvent)==null||hr.call(this,Pt,at),this.parseSSEEvent){v.current=m;let bt=await this.handleCustomSSEEvent(at,n,v,g,c,M);if(v.current&&v.current!==m&&(m=v.current),bt)continue}K.push({payloadType:Pt,payload:at}),qe()}}qe()}};function Ta(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Os(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Ea="[Image]";function ki(t){return{type:"text",text:t}}var hu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Tf=["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"],qr=[...hu,...Tf];function Ef(t){return hu.includes(t)||t.startsWith("image/")}function Ma(t){return Ef(t.type)}async function yu(t){return new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ma(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(t)})}function bu(t,e=qr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Mf(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function vu(t,e){let n=Mf(e).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"}[t]||n||"FILE"}Li();var xu=16e3,kf=24e3,Lf=4096,Pf=1380533830;function If(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Pf?new Uint8Array(t,44):new Uint8Array(t)}function Wf(t){var r;let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var _s=class{constructor(e){this.config=e;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(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,f=new u({sampleRate:xu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ss(kf);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(v=>v.stop()),f.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Wf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,x=new WebSocket(m,["runtype.bearer",n]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,x,o))},x.onmessage=v=>this.handleMessage(v,o),x.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let M=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}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(e,n,r,o){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(Lf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let u=0;u<d.length;u++){let f=Math.max(-1,Math.min(1,d[u]));c[u]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,n){var o,s;if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let r=If(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}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(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,r){this.transcriptCallbacks.forEach(o=>o(e,n,r))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Io=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function as(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new _s(t.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;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: ${t.type}`)}}function wu(t){if((t==null?void 0:t.type)==="custom"&&t.custom)return as({type:"custom",custom:t.custom});if((t==null?void 0:t.type)==="runtype"&&t.runtype)return as({type:"runtype",runtype:t.runtype});if(Io.isSupported())return as({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Pi(t){try{return wu(t),!0}catch{return!1}}function ka(t){var n;let e=["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 r of e){let o=t.find(s=>s.name===r);if(o)return o}return(n=t.find(r=>r.lang.startsWith("en")))!=null?n:t[0]}var is=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,n){var a;if(!t.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ka(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,u;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(u=n.onError)==null||u.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var $s=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,n;return(n=(e=this.engine)==null?void 0:e.supportsPause)!=null?n:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,n;this.stop(),(n=(e=this.engine)==null?void 0:e.destroy)==null||n.call(e),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Ii(t){if(!t)return"";let e=Rf(t);return Cu(e!==null?e:t)}function Rf(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Cu(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),e=e.replace(/\n{2,}/g,`
16
- `),e.trim()}var Au=null;var Li=()=>Au?Au():Promise.resolve().then(()=>(Cu(),wu));var Ef=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function kf(n,e){return Ef.some(t=>n[t]!==e[t])}function Su(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);let r="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 t.message?`${r}
16
+ `),e.trim()}var Mu=null;var Wi=()=>Mu?Mu():Promise.resolve().then(()=>(Eu(),Tu));var Df=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Nf(t,e){return Df.some(n=>t[n]!==e[n])}function ku(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let r="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?`${r}
17
17
 
18
- _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]}),Tu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,Mu=n=>Qo(n)||n===_r,Ea=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=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 Ds(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,m,f;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,u=!!(g!=null&&g.name)&&(Qo(g.name)||g.name===_r&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&u&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(m=this.callbacks).onError)==null||f.call(m,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Rs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!t||!r||!this.config.clientToken||Li().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Ei((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=rs.isSupported()?new rs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,m=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&m)return Li().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:u})=>{let v=new g({host:d,agentId:c,clientToken:m,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&t?new u(v,t,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&t)return m&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ns(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let m=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=m.id}if(c){this.pendingVoiceUserMessageId=null;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let m=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=m.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,m,f;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((m=e.browser)==null?void 0:m.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!kf(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Rs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:m,rawContent:f}=e,u={id:a!=null?a:t==="user"?wa():t==="assistant"?Hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};return this.upsertMessage(u),u}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:m,streaming:f=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:o==="user"?wa():o==="assistant"?Hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,m,f,g,u;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=wa(),s=Hs(),a={id:o,role:"user",content:r||Ca,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let P=Su(v,this.config.errorMessage);if(P){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:P,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(m=this.callbacks).onError)==null||f.call(m,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Hs();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){let m=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!m){let f=Su(c,this.config.errorMessage);if(f){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var m,f,g,u,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(m=a==null?void 0:a.createdAt)!=null?m:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(c?x=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),x){let P=null;if(x instanceof Response){if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((g=T==null?void 0:T.error)!=null?g:`Approval request failed: ${x.status}`)}P=x.body}else x instanceof ReadableStream&&(P=x);P?await this.connectStream(P,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.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(x){let P=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,P||(v=(u=this.callbacks).onError)==null||v.call(u,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var m,f,g,u,v,x,P,T,M,N,k,W;let r=this.messages.find(C=>C.id===e.id);if(((m=r==null?void 0:r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let C=(x=e.toolCall)==null?void 0:x.args,I=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(I.length===1){let D=typeof((P=I[0])==null?void 0:P.question)=="string"?I[0].question:"";D&&(a={[D]:t})}}this.markAskUserQuestionResolved(e,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(M=e.toolCall)==null?void 0:M.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([I,D])=>`${I}: ${Array.isArray(D)?D.join(", "):D}`).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!=null?a:{};c.forEach((I,D)=>{let B=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!B)return;let E=C[B],z=Array.isArray(E)?E.join(", "):typeof E=="string"?E:"";this.appendMessage({id:`ask-user-q-${i}-${D}`,role:"assistant",content:B,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${D}`,role:"user",content:z||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:t});if(!C.ok){let I=await C.json().catch(()=>null);throw new Error((N=I==null?void 0:I.error)!=null?N:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let I=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(W=(k=this.callbacks).onError)==null||W.call(k,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==_r)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,m,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async g=>{var W,C,I,D,B,E,z;let u=(W=g.toolCall)==null?void 0:W.name,v=(C=g.toolCall)==null?void 0:C.id;if(!u||!v)return null;let x=`${e}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let P=this.markWebMcpToolRunning(g),T=(D=(I=g.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?D:u;if(u===_r)return{dedupeKey:x,resumeKey:T,output:xi(),toolMessage:g,startedAt:P,completedAt:Date.now()};let M=new AbortController;this.webMcpResolveControllers.add(M),o.push(M);let N=this.client.executeWebMcpToolCall(u,(B=g.toolCall)==null?void 0:B.args,M.signal),k;if(!N)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await N}catch(j){let te=j instanceof Error&&(j.name==="AbortError"||j.message.includes("aborted")||j.message.includes("abort"));return te||(z=(E=this.callbacks).onError)==null||z.call(E,j instanceof Error?j:new Error(String(j))),this.markWebMcpToolComplete(g,Ns(te?"Aborted by cancel()":Tu(j)),P),this.webMcpInflightKeys.delete(x),null}return M.signal.aborted?(this.markWebMcpToolComplete(g,Ns("Aborted by cancel()"),P),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:T,output:k,toolMessage:g,startedAt:P,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let u=await this.client.resumeFlow(e,g,{signal:s.signal});if(!u.ok){let v=await u.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${u.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===_r?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(f=(m=this.callbacks).onError)==null||f.call(m,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,Ns("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,x,P,T,M,N,k,W,C,I,D,B;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(x=e.toolCall)==null?void 0:x.name,o=(P=e.toolCall)==null?void 0:P.id;if(!t){(M=(T=this.callbacks).onError)==null||M.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let E=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(E)||this.webMcpResolvedKeys.has(E))return;this.webMcpInflightKeys.add(E);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(E)}catch(z){(k=(N=this.callbacks).onError)==null||k.call(N,z instanceof Error?z:new Error(String(z)))}finally{this.webMcpInflightKeys.delete(E)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===_r,m=(W=e.toolCall)==null?void 0:W.args,f=c?null:this.client.executeWebMcpToolCall(r,m,d),g="execute",u=a;try{let E;if(c?E=xi():f?E=await f:E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Ns("Aborted by cancel()"),a);return}let z=(I=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?I:r;g="resume",await this.resumeWithToolOutput(t,z,E,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,E,a,u,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(E){let z=E instanceof Error&&(E.name==="AbortError"||E.message.includes("aborted")||E.message.includes("abort"));(g==="execute"||z||d.aborted)&&this.markWebMcpToolComplete(e,Ns(z||d.aborted?"Aborted by cancel()":Tu(E)),a),z||(B=(D=this.callbacks).onError)==null||B.call(D,E instanceof Error?E:new Error(String(E)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=ki(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Sa(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=ki(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var m,f,g,u,v,x,P,T,M,N,k,W,C,I,D;if(s!==r)return o;let a={...o,...t};if(((m=o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let B=o.approval,E=t.approval;a.approval={...B,...E,executionId:E.executionId||B.executionId,toolName:E.toolName||B.toolName,description:E.description||B.description,toolType:(u=E.toolType)!=null?u:B.toolType,reason:(v=E.reason)!=null?v:B.reason,parameters:(x=E.parameters)!=null?x:B.parameters}}let i=(P=t.toolCall)==null?void 0:P.name,d=(T=t.agentMetadata)==null?void 0:T.executionId,c=(M=t.toolCall)==null?void 0:M.id;if(i&&Mu(i)&&d&&c&&((N=t.agentMetadata)==null?void 0:N.awaitingLocalTool)===!0){let B=`${d}:${c}`,E=this.webMcpInflightKeys.has(B),z=this.webMcpResolvedKeys.has(B),j=(k=o.toolCall)==null?void 0:k.name,te=((W=o.agentMetadata)==null?void 0:W.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&j!==void 0&&Mu(j)&&((I=o.toolCall)==null?void 0:I.status)==="complete";(E||z||te)&&(a.agentMetadata={...(D=a.agentMetadata)!=null?D:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};import{Activity as Lf,ArrowDown as Pf,ArrowUp as If,ArrowUpRight as Wf,Bot as Rf,ChevronDown as Hf,ChevronUp as Bf,ChevronRight as Df,ChevronLeft as Nf,Check as Ff,Clipboard as Of,ClipboardCopy as _f,Copy as $f,File as Uf,FileCode as qf,FileSpreadsheet as zf,FileText as jf,ImagePlus as Vf,Loader as Kf,LoaderCircle as Gf,Mic as Qf,Paperclip as Xf,RefreshCw as Jf,Search as Yf,Send as Zf,ShieldAlert as eh,ShieldCheck as th,ShieldX as nh,Square as rh,ThumbsDown as oh,ThumbsUp as sh,Upload as ah,Volume2 as ih,X as lh,User as ch,Mail as dh,Phone as ph,Calendar as uh,Clock as mh,Building as gh,MapPin as fh,Lock as hh,Key as yh,CreditCard as bh,AtSign as vh,Hash as xh,Globe as wh,Link as Ch,CircleCheck as Ah,CircleX as Sh,TriangleAlert as Th,Info as Mh,Ban as Eh,Shield as kh,ArrowLeft as Lh,ArrowRight as Ph,ExternalLink as Ih,Ellipsis as Wh,EllipsisVertical as Rh,Menu as Hh,House as Bh,Plus as Dh,Minus as Nh,Pencil as Fh,Trash as Oh,Trash2 as _h,Save as $h,Download as Uh,Share as qh,Funnel as zh,Settings as jh,RotateCw as Vh,Maximize as Kh,Minimize as Gh,ShoppingCart as Qh,ShoppingBag as Xh,Package as Jh,Truck as Yh,Tag as Zh,Gift as ey,Receipt as ty,Wallet as ny,Store as ry,DollarSign as oy,Percent as sy,Play as ay,Pause as iy,VolumeX as ly,Camera as cy,Image as dy,Film as py,Headphones as uy,MessageCircle as my,MessageSquare as gy,Bell as fy,Heart as hy,Star as yy,Eye as by,EyeOff as vy,Bookmark as xy,CalendarDays as wy,History as Cy,Timer as Ay,Folder as Sy,FolderOpen as Ty,Files as My,Sparkles as Ey,Zap as ky,Sun as Ly,Moon as Py,Flag as Iy,Monitor as Wy,Smartphone as Ry}from"lucide";var Hy={activity:Lf,"arrow-down":Pf,"arrow-up":If,"arrow-up-right":Wf,bot:Rf,"chevron-down":Hf,"chevron-up":Bf,"chevron-right":Df,"chevron-left":Nf,check:Ff,clipboard:Of,"clipboard-copy":_f,copy:$f,file:Uf,"file-code":qf,"file-spreadsheet":zf,"file-text":jf,"image-plus":Vf,loader:Kf,"loader-circle":Gf,mic:Qf,paperclip:Xf,"refresh-cw":Jf,search:Yf,send:Zf,"shield-alert":eh,"shield-check":th,"shield-x":nh,square:rh,"thumbs-down":oh,"thumbs-up":sh,upload:ah,"volume-2":ih,x:lh,user:ch,mail:dh,phone:ph,calendar:uh,clock:mh,building:gh,"map-pin":fh,lock:hh,key:yh,"credit-card":bh,"at-sign":vh,hash:xh,globe:wh,link:Ch,"circle-check":Ah,"circle-x":Sh,"triangle-alert":Th,info:Mh,ban:Eh,shield:kh,"arrow-left":Lh,"arrow-right":Ph,"external-link":Ih,ellipsis:Wh,"ellipsis-vertical":Rh,menu:Hh,house:Bh,plus:Dh,minus:Nh,pencil:Fh,trash:Oh,"trash-2":_h,save:$h,download:Uh,share:qh,funnel:zh,settings:jh,"rotate-cw":Vh,maximize:Kh,minimize:Gh,"shopping-cart":Qh,"shopping-bag":Xh,package:Jh,truck:Yh,tag:Zh,gift:ey,receipt:ty,wallet:ny,store:ry,"dollar-sign":oy,percent:sy,play:ay,pause:iy,"volume-x":ly,camera:cy,image:dy,film:py,headphones:uy,"message-circle":my,"message-square":gy,bell:fy,heart:hy,star:yy,eye:by,"eye-off":vy,bookmark:xy,"calendar-days":wy,history:Cy,timer:Ay,folder:Sy,"folder-open":Ty,files:My,sparkles:Ey,zap:ky,sun:Ly,moon:Py,flag:Iy,monitor:Wy,smartphone:Ry},Ce=(n,e=24,t="currentColor",r=2)=>{let o=Hy[n];return o?By(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function By(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,m])=>{c!=="stroke"&&d.setAttribute(c,String(m))}),o.appendChild(d)}),o}var ka={allowedTypes:$r,maxFileSize:10*1024*1024,maxFiles:4};function Dy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ny(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var Fs=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:ka.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:ka.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:ka.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ka.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let m=gu(c,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let f=(o=m.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await mu(c),g=Aa(c)?URL.createObjectURL(c):null,u={id:Dy(),file:c,previewUrl:g,contentPart:f};this.attachments.push(u),this.renderPreview(u)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Aa(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.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",r.appendChild(a)}else{let a=b("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=Ny(e.file.type),d=Ce(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=fu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ce("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Eu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Os(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];Eu(s)&&Eu(o)?t[r]=Os(s,o):t[r]=o}return t}var Ur="min(440px, calc(100vw - 24px))",Lu="440px",Fy={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:Ur,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)"},Dt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Fy,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:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,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 ku(n,e){if(!(!n&&!e))return n?e?Os(n,e):n:e}function Pu(n){var e,t,r,o,s,a,i,d,c,m,f,g,u,v,x,P,T,M,N,k,W;return n?{...Dt,...n,theme:ku(Dt.theme,n.theme),darkTheme:ku(Dt.darkTheme,n.darkTheme),launcher:{...Dt.launcher,...n.launcher,dock:{...(e=Dt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...n.copy},sendButton:{...Dt.sendButton,...n.sendButton},statusIndicator:{...Dt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...n.voiceRecognition},features:(()=>{var ne,Q,ae,fe,re,V,ee,Ue,J,ie;let C=(ne=Dt.features)==null?void 0:ne.artifacts,I=(Q=n.features)==null?void 0:Q.artifacts,D=(ae=Dt.features)==null?void 0:ae.scrollToBottom,B=(fe=n.features)==null?void 0:fe.scrollToBottom,E=(re=Dt.features)==null?void 0:re.scrollBehavior,z=(V=n.features)==null?void 0:V.scrollBehavior,j=(ee=Dt.features)==null?void 0:ee.streamAnimation,te=(Ue=n.features)==null?void 0:Ue.streamAnimation,We=(J=Dt.features)==null?void 0:J.askUserQuestion,$e=(ie=n.features)==null?void 0:ie.askUserQuestion,ve=C===void 0&&I===void 0?void 0:{...C,...I,layout:{...C==null?void 0:C.layout,...I==null?void 0:I.layout}},Pe=D===void 0&&B===void 0?void 0:{...D,...B},Oe=E===void 0&&z===void 0?void 0:{...E,...z},Ae=j===void 0&&te===void 0?void 0:{...j,...te},be=We===void 0&&$e===void 0?void 0:{...We,...$e,styles:{...We==null?void 0:We.styles,...$e==null?void 0:$e.styles}};return{...Dt.features,...n.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Oe!==void 0?{scrollBehavior:Oe}:{},...ve!==void 0?{artifacts:ve}:{},...Ae!==void 0?{streamAnimation:Ae}:{},...be!==void 0?{askUserQuestion:be}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Dt.layout,...n.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(m=Dt.layout)==null?void 0:m.messages)==null?void 0:f.avatar,...(u=(g=n.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Dt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(P=n.layout)==null?void 0:P.messages)==null?void 0:T.timestamp}},slots:{...(M=Dt.layout)==null?void 0:M.slots,...(N=n.layout)==null?void 0:N.slots}},markdown:{...Dt.markdown,...n.markdown,options:{...(k=Dt.markdown)==null?void 0:k.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...Dt.messageActions,...n.messageActions}}:Dt}var Oy={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"}},_y={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"}},$y={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"}},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:Ur,maxWidth:Lu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},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:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",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 os(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?os(n,r):r}function Iu(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=os(n,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Uy(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function Wu(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Wu(s,o):t[r]=o}return t}function qy(n,e){return e?Wu(n,e):n}function Po(n,e={}){var o,s,a,i,d,c,m,f,g,u,v,x,P;let t={palette:Oy,semantic:_y,components:$y},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(m=n==null?void 0:n.semantic)==null?void 0:m.colors,interactive:{...t.semantic.colors.interactive,...(g=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(u=n==null?void 0:n.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(P=n==null?void 0:n.semantic)==null?void 0:P.typography}},components:qy(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let T=Uy(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(M=>M.message).join(", ")}`)}if(e.plugins)for(let T of e.plugins)r=T.transform(r);return r}function Ru(n){var x,P,T,M,N,k,W,C,I,D,B,E,z,j,te,We,$e,ve,Pe,Oe,Ae,be,ne,Q,ae,fe,re,V,ee,Ue,J,ie,Le,at,it,nt,Me,de,Qe,X,le,xe,ze,Lt,Se,ue,gn,Pt,nn,fr,fn,je,S,pe,ke,Te,Re,Ye,Ke,pt,It,U,rt,K,ce,Ee,bt,Jt,Yt,dn,Rt,Ze,Wt,lt,Vt,Xn,Cn,Zt,Pn,hr,vt,Dn,yr,Lr,ar,ht,co,br,po,In,Bo,zr,Pr,jr,Vr,uo,mo,Kr,wt,Nn,Fn,An,At,Jn,Yn,On,Gr,Ir,Qr,_n,Ht,Sn,Zn,Xr,Wr,Jr,vr,$n;let e=Iu(n),t={};for(let[he,ct]of Object.entries(e)){let Gt=he.replace(/\./g,"-");t[`--persona-${Gt}`]=ct.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(P=t["--persona-semantic-colors-secondary"])!=null?P:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(T=t["--persona-semantic-colors-accent"])!=null?T:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(M=t["--persona-semantic-colors-surface"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(N=t["--persona-semantic-colors-background"])!=null?N:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(k=t["--persona-semantic-colors-container"])!=null?k:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(W=t["--persona-semantic-colors-text"])!=null?W:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(I=t["--persona-semantic-colors-text-inverse"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(D=t["--persona-semantic-colors-border"])!=null?D:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(B=t["--persona-semantic-colors-divider"])!=null?B:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(E=t["--persona-components-voice-recording-indicator"])!=null?E:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(z=t["--persona-components-voice-recording-background"])!=null?z:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(j=t["--persona-components-voice-processing-icon"])!=null?j:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(We=t["--persona-components-approval-requested-background"])!=null?We:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=($e=t["--persona-components-approval-requested-border"])!=null?$e:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ve=t["--persona-components-approval-requested-text"])!=null?ve:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Pe=t["--persona-components-approval-requested-shadow"])!=null?Pe:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(Oe=t["--persona-components-approval-approve-background"])!=null?Oe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Ae=t["--persona-components-approval-deny-background"])!=null?Ae:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(be=t["--persona-components-attachment-image-background"])!=null?be:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ne=t["--persona-components-attachment-image-border"])!=null?ne:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Q=t["--persona-semantic-typography-fontFamily"])!=null?Q:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ae=t["--persona-semantic-typography-fontSize"])!=null?ae:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(fe=t["--persona-semantic-typography-fontWeight"])!=null?fe:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(re=t["--persona-semantic-typography-lineHeight"])!=null?re:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(V=t["--persona-palette-radius-sm"])!=null?V:"0.125rem",t["--persona-radius-md"]=(ee=t["--persona-palette-radius-md"])!=null?ee:"0.375rem",t["--persona-radius-lg"]=(Ue=t["--persona-palette-radius-lg"])!=null?Ue:"0.5rem",t["--persona-radius-xl"]=(J=t["--persona-palette-radius-xl"])!=null?J:"0.75rem",t["--persona-radius-full"]=(ie=t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-launcher-radius"]=(at=(Le=t["--persona-components-launcher-borderRadius"])!=null?Le:t["--persona-palette-radius-full"])!=null?at:"9999px",t["--persona-launcher-bg"]=(it=t["--persona-components-launcher-background"])!=null?it:t["--persona-primary"],t["--persona-launcher-fg"]=(nt=t["--persona-components-launcher-foreground"])!=null?nt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(Me=t["--persona-components-launcher-border"])!=null?Me:t["--persona-border"],t["--persona-button-primary-bg"]=(de=t["--persona-components-button-primary-background"])!=null?de:t["--persona-primary"],t["--persona-button-primary-fg"]=(Qe=t["--persona-components-button-primary-foreground"])!=null?Qe:t["--persona-text-inverse"],t["--persona-button-radius"]=(le=(X=t["--persona-components-button-primary-borderRadius"])!=null?X:t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-panel-radius"]=(ze=(xe=t["--persona-components-panel-borderRadius"])!=null?xe:t["--persona-radius-xl"])!=null?ze:"0.75rem",t["--persona-panel-border"]=(Lt=t["--persona-components-panel-border"])!=null?Lt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(ue=(Se=t["--persona-components-panel-shadow"])!=null?Se:t["--persona-palette-shadows-xl"])!=null?ue:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(gn=t["--persona-components-launcher-shadow"])!=null?gn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(nn=(Pt=t["--persona-components-input-borderRadius"])!=null?Pt:t["--persona-radius-lg"])!=null?nn:"0.5rem",t["--persona-message-user-radius"]=(fn=(fr=t["--persona-components-message-user-borderRadius"])!=null?fr:t["--persona-radius-lg"])!=null?fn:"0.5rem",t["--persona-message-assistant-radius"]=(S=(je=t["--persona-components-message-assistant-borderRadius"])!=null?je:t["--persona-radius-lg"])!=null?S:"0.5rem",t["--persona-header-bg"]=(pe=t["--persona-components-header-background"])!=null?pe:t["--persona-surface"],t["--persona-header-border"]=(ke=t["--persona-components-header-border"])!=null?ke:t["--persona-divider"],t["--persona-header-icon-bg"]=(Te=t["--persona-components-header-iconBackground"])!=null?Te:t["--persona-primary"],t["--persona-header-icon-fg"]=(Re=t["--persona-components-header-iconForeground"])!=null?Re:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ye=t["--persona-components-header-titleForeground"])!=null?Ye:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ke=t["--persona-components-header-subtitleForeground"])!=null?Ke:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(pt=t["--persona-components-header-actionIconForeground"])!=null?pt:t["--persona-muted"];let r=(It=n.components)==null?void 0:It.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(U=n.components)==null?void 0:U.introCard;t["--persona-intro-card-bg"]=(rt=t["--persona-components-introCard-background"])!=null?rt:t["--persona-surface"],t["--persona-intro-card-radius"]=(K=t["--persona-components-introCard-borderRadius"])!=null?K:"1rem",t["--persona-intro-card-padding"]=(ce=t["--persona-components-introCard-padding"])!=null?ce:"1.5rem",t["--persona-intro-card-shadow"]=(bt=(Ee=o==null?void 0:o.shadow)!=null?Ee:t["--persona-components-introCard-shadow"])!=null?bt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Jt=t["--persona-components-input-background"])!=null?Jt:t["--persona-surface"],t["--persona-input-placeholder"]=(Yt=t["--persona-components-input-placeholder"])!=null?Yt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(dn=t["--persona-components-message-user-background"])!=null?dn:t["--persona-accent"],t["--persona-message-user-text"]=(Rt=t["--persona-components-message-user-text"])!=null?Rt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ze=t["--persona-components-message-user-shadow"])!=null?Ze:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Wt=t["--persona-components-message-assistant-background"])!=null?Wt:t["--persona-surface"],t["--persona-message-assistant-text"]=(lt=t["--persona-components-message-assistant-text"])!=null?lt:t["--persona-text"],t["--persona-message-assistant-border"]=(Vt=t["--persona-components-message-assistant-border"])!=null?Vt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Xn=t["--persona-components-message-assistant-shadow"])!=null?Xn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Zt=(Cn=t["--persona-components-scrollToBottom-background"])!=null?Cn:t["--persona-button-primary-bg"])!=null?Zt:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(hr=(Pn=t["--persona-components-scrollToBottom-foreground"])!=null?Pn:t["--persona-button-primary-fg"])!=null?hr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(vt=t["--persona-components-scrollToBottom-border"])!=null?vt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Dn=t["--persona-components-scrollToBottom-size"])!=null?Dn:"40px",t["--persona-scroll-to-bottom-radius"]=(ar=(Lr=(yr=t["--persona-components-scrollToBottom-borderRadius"])!=null?yr:t["--persona-button-radius"])!=null?Lr:t["--persona-radius-full"])!=null?ar:"9999px",t["--persona-scroll-to-bottom-shadow"]=(co=(ht=t["--persona-components-scrollToBottom-shadow"])!=null?ht:t["--persona-palette-shadows-sm"])!=null?co:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(br=t["--persona-components-scrollToBottom-padding"])!=null?br:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(po=t["--persona-components-scrollToBottom-gap"])!=null?po:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Bo=(In=t["--persona-components-scrollToBottom-fontSize"])!=null?In:t["--persona-palette-typography-fontSize-sm"])!=null?Bo:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(zr=t["--persona-components-scrollToBottom-iconSize"])!=null?zr:"14px",t["--persona-tool-bubble-shadow"]=(Pr=t["--persona-components-toolBubble-shadow"])!=null?Pr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(jr=t["--persona-components-reasoningBubble-shadow"])!=null?jr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Vr=t["--persona-components-composer-shadow"])!=null?Vr:"none",t["--persona-md-inline-code-bg"]=(uo=t["--persona-components-markdown-inlineCode-background"])!=null?uo:t["--persona-container"],t["--persona-md-inline-code-color"]=(mo=t["--persona-components-markdown-inlineCode-foreground"])!=null?mo:t["--persona-text"],t["--persona-md-link-color"]=(wt=(Kr=t["--persona-components-markdown-link-foreground"])!=null?Kr:t["--persona-accent"])!=null?wt:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Nn=t["--persona-components-markdown-codeBlock-background"])!=null?Nn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Fn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Fn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(An=t["--persona-components-markdown-codeBlock-textColor"])!=null?An:"inherit",t["--persona-md-table-header-bg"]=(At=t["--persona-components-markdown-table-headerBackground"])!=null?At:t["--persona-container"],t["--persona-md-table-border-color"]=(Jn=t["--persona-components-markdown-table-borderColor"])!=null?Jn:t["--persona-border"],t["--persona-md-hr-color"]=(Yn=t["--persona-components-markdown-hr-color"])!=null?Yn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(On=t["--persona-components-markdown-blockquote-borderColor"])!=null?On:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Gr=t["--persona-components-markdown-blockquote-background"])!=null?Gr:"transparent",t["--persona-md-blockquote-text-color"]=(Ir=t["--persona-components-markdown-blockquote-textColor"])!=null?Ir:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Qr=t["--persona-components-collapsibleWidget-container"])!=null?Qr:t["--persona-surface"],t["--cw-surface"]=(_n=t["--persona-components-collapsibleWidget-surface"])!=null?_n:t["--persona-surface"],t["--cw-border"]=(Ht=t["--persona-components-collapsibleWidget-border"])!=null?Ht:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let m=n.components,f=m==null?void 0:m.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let g=m==null?void 0:m.labelButton;g&&(g.background&&(t["--persona-label-btn-bg"]=g.background),g.border&&(t["--persona-label-btn-border"]=g.border),g.color&&(t["--persona-label-btn-color"]=g.color),g.padding&&(t["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(t["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(t["--persona-label-btn-gap"]=g.gap));let u=m==null?void 0:m.toggleGroup;u&&(u.gap&&(t["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(t["--persona-toggle-group-radius"]=u.borderRadius));let v=m==null?void 0:m.artifact;if(v!=null&&v.toolbar){let he=v.toolbar;he.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,t["--persona-dropdown-bg"]=(Zn=t["--persona-dropdown-bg"])!=null?Zn:he.copyMenuBackground),he.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,t["--persona-dropdown-border"]=(Xr=t["--persona-dropdown-border"])!=null?Xr:he.copyMenuBorder),he.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,t["--persona-dropdown-shadow"]=(Wr=t["--persona-dropdown-shadow"])!=null?Wr:he.copyMenuShadow),he.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Jr=t["--persona-dropdown-radius"])!=null?Jr:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(vr=t["--persona-dropdown-item-hover-bg"])!=null?vr:he.copyMenuItemHoverBackground),he.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(v!=null&&v.tab){let he=v.tab;he.background&&(t["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(t["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(t["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(t["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(t["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(t["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(t["--persona-artifact-tab-list-padding"]=he.listPadding)}if(v!=null&&v.pane){let he=v.pane;if(he.toolbarBackground){let ct=($n=os(n,he.toolbarBackground))!=null?$n:he.toolbarBackground;t["--persona-artifact-toolbar-bg"]=ct}}return t}var zy={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"}}},Hu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Pi=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},jy=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Pi()},Vy=n=>jy(n),Ky=n=>Po(n),Gy=n=>{var t;let e=Po(void 0,{validate:!1});return Po({...n,palette:{...e.palette,colors:{...zy.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},La=n=>{let e=Vy(n),t=Hu(n==null?void 0:n.theme),r=Hu(n==null?void 0:n.darkTheme);return e==="dark"?Gy(Os(t!=null?t:{},r!=null?r:{})):Ky(t)},Qy=n=>Ru(n),ss=(n,e)=>{let t=La(e),r=Qy(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},Bu=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Pi())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Pi());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};import{Idiomorph as Xy}from"idiomorph";var Pa=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Xy.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Du=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Ia={index:-1,draft:""};function Nu(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ia}}}function Fu(n,e){var t,r,o,s,a,i,d,c,m,f,g,u,v,x,P,T,M,N,k,W,C,I,D,B,E,z,j,te,We,$e,ve,Pe,Oe,Ae,be,ne,Q,ae;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(m=(c=n.llmContent)==null?void 0:c.length)!=null?m:0,(g=(f=n.approval)==null?void 0:f.status)!=null?g:"",(v=(u=n.toolCall)==null?void 0:u.status)!=null?v:"",(P=(x=n.toolCall)==null?void 0:x.name)!=null?P:"",(N=(M=(T=n.toolCall)==null?void 0:T.chunks)==null?void 0:M.length)!=null?N:0,(I=(C=(W=(k=n.toolCall)==null?void 0:k.chunks)==null?void 0:W[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?I:"",typeof((D=n.toolCall)==null?void 0:D.args)=="string"?n.toolCall.args.length:(B=n.toolCall)!=null&&B.args?JSON.stringify(n.toolCall.args).length:0,(j=(z=(E=n.reasoning)==null?void 0:E.chunks)==null?void 0:z.length)!=null?j:0,(ve=($e=(We=(te=n.reasoning)==null?void 0:te.chunks)==null?void 0:We[n.reasoning.chunks.length-1])==null?void 0:$e.length)!=null?ve:0,(be=(Ae=(Oe=(Pe=n.reasoning)==null?void 0:Pe.chunks)==null?void 0:Oe[n.reasoning.chunks.length-1])==null?void 0:Ae.slice(-32))!=null?be:"",(Q=(ne=n.contentParts)==null?void 0:ne.length)!=null?Q:0,(ae=n.stopReason)!=null?ae:"",e].join("\0")}function Ou(){return new Map}function _u(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function $u(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Uu(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Wa(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function qr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function Io(n,e){return qr(n)-n.scrollTop<=e}function Ra(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,m=t-r;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:t}:!e&&o&&(!c||m>0)?{action:"resume",delta:m,nextLastScrollTop:t}:e&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:m,nextLastScrollTop:t}:{action:"none",delta:m,nextLastScrollTop:t}}function Ha(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function qu(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function zu(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function ju(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var vn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},xn=1e5,io=xn+1;var _s={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Jy=["pre","code","a","script","style"],Ba=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:_s.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:_s.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:_s.speed,duration:(o=n==null?void 0:n.duration)!=null?o:_s.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:_s.buffer}},Yy=[{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"}],Ku=new Map;for(let n of Yy)Ku.set(n.name,n);var $s=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Ku.get(n))!=null?r:null},Da=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
19
- `);return s<0?"":n.slice(0,s)}return n},Zy=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},eb=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Ii=/\s/,tb=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},nb=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Ii.test(s[i])){let c=i;for(;c<s.length&&Ii.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let m=i;for(;m<s.length&&!Ii.test(s[m]);)c.appendChild(Zy(r,s[m],e,t.value)),t.value+=1,m+=1;a.appendChild(c),i=m}o.replaceChild(a,n)},rb=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(eb(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},Us=(n,e,t,r)=>{var f,g;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:Jy).map(u=>u.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)tb(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},m=e==="char"?nb:rb;for(let u of i)m(u,t,c);return o.innerHTML},Na=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},qs=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Vu=new WeakMap,ob=(n,e)=>{var s;if(!n.styles)return;let t=Vu.get(e);if(t||(t=new Set,Vu.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},Wi=new WeakMap,sb=(n,e)=>{if(!n.onAttach)return;let t=Wi.get(e);if(t||(t=new Map,Wi.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},Gu=n=>{let e=Wi.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Ri=(n,e)=>{ob(n,e),sb(n,e)};function Hi(n,e=xn){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var zs=0,lo=null;function Bi(n=document){var t;if(zs++,zs===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;lo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,zs=Math.max(0,zs-1),zs===0&&lo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=lo.originalOverflow,o.style.position=lo.originalPosition,o.style.top=lo.originalTop,o.style.width=lo.originalWidth,s.scrollTo(0,lo.scrollY),lo=null}}}var js={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},mn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},Vs=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},mr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:js.side,width:(o=e==null?void 0:e.width)!=null?o:js.width,animate:(s=e==null?void 0:e.animate)!=null?s:js.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:js.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:js.maxHeight}};var gr={"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 ab="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Fa=(n,e={})=>{var P,T,M,N,k,W;let{showClose:t=!0,wrapperClassName:r=ab,buttonSize:o,iconSize:s="28px"}=e,a=(P=n==null?void 0:n.launcher)!=null?P:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=b("div",r),c=(M=a.closeButtonTooltipText)!=null?M:"Close chat",m=(N=a.closeButtonShowTooltip)!=null?N:!0,f=(k=a.closeButtonIconName)!=null?k:"x",g=(W=a.closeButtonIconText)!=null?W:"\xD7",u=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Tt("button",{className:Ms("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!u&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||Ln.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:u?`${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}}),x=Ce(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),m&&c){let C=null,I=()=>{if(C)return;let B=v.ownerDocument,E=B.body;if(!E)return;C=kr(B,"div","persona-clear-chat-tooltip"),C.textContent=c;let z=kr(B,"div");z.className="persona-clear-chat-tooltip-arrow",C.appendChild(z);let j=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(io),C.style.left=`${j.left+j.width/2}px`,C.style.top=`${j.top-8}px`,C.style.transform="translate(-50%, -100%)",E.appendChild(C)},D=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",D),v.addEventListener("focus",I),v.addEventListener("blur",D),d._cleanupTooltip=()=>{D(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",D),v.removeEventListener("focus",I),v.removeEventListener("blur",D)}}return{button:v,wrapper:d}},ib="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Oa=(n,e={})=>{var C,I,D,B,E,z,j,te,We,$e,ve,Pe,Oe;let{wrapperClassName:t=ib,buttonSize:r,iconSize:o="20px"}=e,a=(I=((C=n==null?void 0:n.launcher)!=null?C:{}).clearChat)!=null?I:{},i=(D=r!=null?r:a.size)!=null?D:"32px",d=(B=a.iconName)!=null?B:"refresh-cw",c=(E=a.iconColor)!=null?E:"",m=(z=a.backgroundColor)!=null?z:"",f=(j=a.borderWidth)!=null?j:"",g=(te=a.borderColor)!=null?te:"",u=(We=a.borderRadius)!=null?We:"",v=($e=a.paddingX)!=null?$e:"",x=(ve=a.paddingY)!=null?ve:"",P=(Pe=a.tooltipText)!=null?Pe:"Clear chat",T=(Oe=a.showTooltip)!=null?Oe:!0,M=b("div",t),N=!!(f||g),k=Tt("button",{className:Ms("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!m&&"hover:persona-bg-gray-100",!N&&"persona-border-none",!u&&"persona-rounded-full"),attrs:{type:"button","aria-label":P},style:{height:i,width:i,color:c||Ln.actionIconColor,backgroundColor:m||void 0,border:N?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:u||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),W=Ce(d,o,"currentColor",1);if(W&&(W.style.display="block",k.appendChild(W)),M.appendChild(k),T&&P){let Ae=null,be=()=>{if(Ae)return;let Q=k.ownerDocument,ae=Q.body;if(!ae)return;Ae=kr(Q,"div","persona-clear-chat-tooltip"),Ae.textContent=P;let fe=kr(Q,"div");fe.className="persona-clear-chat-tooltip-arrow",Ae.appendChild(fe);let re=k.getBoundingClientRect();Ae.style.position="fixed",Ae.style.zIndex=String(io),Ae.style.left=`${re.left+re.width/2}px`,Ae.style.top=`${re.top-8}px`,Ae.style.transform="translate(-50%, -100%)",ae.appendChild(Ae)},ne=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};M.addEventListener("mouseenter",be),M.addEventListener("mouseleave",ne),k.addEventListener("focus",be),k.addEventListener("blur",ne),M._cleanupTooltip=()=>{ne(),M.removeEventListener("mouseenter",be),M.removeEventListener("mouseleave",ne),k.removeEventListener("focus",be),k.removeEventListener("blur",ne)}}return{button:k,wrapper:M}};var Ln={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))"},Wo=n=>{var W,C,I,D,B,E,z,j,te,We,$e,ve,Pe,Oe,Ae,be;let{config:e,showClose:t=!0}=n,r=Tt("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)))"}}),o=(W=e==null?void 0:e.launcher)!=null?W:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(I=o.closeButtonPlacement)!=null?I:"inline",i=(D=o.headerIconHidden)!=null?D:!1,d=o.headerIconName,c=Tt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let ne=parseFloat(s)||24,Q=Ce(d,ne*.6,"currentColor",1);Q?c.replaceChildren(Q):c.textContent=(E=(B=e==null?void 0:e.launcher)==null?void 0:B.agentIconText)!=null?E:"\u{1F4AC}"}else if((z=e==null?void 0:e.launcher)!=null&&z.iconUrl){let ne=b("img");ne.src=e.launcher.iconUrl,ne.alt="",ne.className="persona-rounded-xl persona-object-cover",ne.style.height=s,ne.style.width=s,c.replaceChildren(ne)}else c.textContent=(te=(j=e==null?void 0:e.launcher)==null?void 0:j.agentIconText)!=null?te:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Tt("span",{className:"persona-text-base persona-font-semibold",text:($e=(We=e==null?void 0:e.launcher)==null?void 0:We.title)!=null?$e:"Chat Assistant",style:{color:Ln.titleColor}}),g=Tt("span",{className:"persona-text-xs",text:(Pe=(ve=e==null?void 0:e.launcher)==null?void 0:ve.subtitle)!=null?Pe:"Here to help you get answers fast",style:{color:Ln.subtitleColor}});m.append(f,g),i?r.append(m):r.append(c,m);let u=(Oe=o.clearChat)!=null?Oe:{},v=(Ae=u.enabled)!=null?Ae:!0,x=(be=u.placement)!=null?be:"inline",P=null,T=null;if(v){let Q=Oa(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});P=Q.button,T=Q.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let M=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:N,wrapper:k}=Fa(e,{showClose:t,wrapperClassName:M});return a!=="top-right"&&r.appendChild(k),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:g,closeButton:N,closeButtonWrapper:k,clearChatButton:P,clearChatButtonWrapper:T}},Ks=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function as(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(io)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of e){if(u.dividerBefore){let P=document.createElement("hr");a.appendChild(P)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let P=Ce(u.icon,16,"currentColor",1.5);P&&v.appendChild(P)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",P=>{P.stopPropagation(),m(),t(u.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&m()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():m()}function g(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:m,toggle:f,destroy:g}}function wn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=Ce(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[m,f]of Object.entries(i))d.setAttribute(m,f);return d}function Di(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let m=b("button",c);if(m.type="button",m.setAttribute("aria-label",t),e){let g=Ce(e,s!=null?s:14,"currentColor",2);g&&m.appendChild(g)}let f=b("span");if(f.textContent=t,m.appendChild(f),i&&m.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))m.setAttribute(g,u);return m}function Qu(n){var u,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let m=b("span","persona-combo-btn-label");m.textContent=e,c.appendChild(m);let f=Ce(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var x,P;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(P=d.border)!=null?P:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=as({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",x=>{x.stopPropagation();let P=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",P?"false":"true"),g.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{m.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var lb=n=>{var r;let e=Wo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function cb(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("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(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Ce(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=as({items:a.menuItems,onSelect:m=>t==null?void 0:t(m),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",m=>{m.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var db=n=>{var M,N,k,W,C,I,D,B,E;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(M=e==null?void 0:e.launcher)!=null?M:{},i=b("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 d=o==null?void 0:o.titleMenu,c,m;if(d)c=Qu({label:(N=a.title)!=null?N:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Ln.titleColor,m=(k=c.querySelector(".persona-combo-btn-label"))!=null?k:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Ln.titleColor,m.textContent=(W=a.title)!=null?W:"Chat Assistant",c.appendChild(m),cb(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let j=o.onTitleClick;c.addEventListener("click",te=>{te.target.closest("button")||j()}),c.addEventListener("keydown",te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),j())})}let z=o==null?void 0:o.titleRowHover;z&&(c.style.borderRadius=(I=z.borderRadius)!=null?I:"10px",c.style.padding=(D=z.padding)!=null?D:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var j,te;c.style.backgroundColor=(j=z.background)!=null?j:"",c.style.borderColor=(te=z.border)!=null?te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(B=a.closeButtonSize)!=null?B:"32px",g=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=f,u.style.width=f,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=t?"":"none",u.style.color=a.closeButtonColor||Ln.actionIconColor;let v=(E=a.closeButtonIconName)!=null?E:"x",x=Ce(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let P=b("div");P.style.display="none";let T=b("span");return T.style.display="none",{header:i,iconHolder:P,headerTitle:m,headerSubtitle:T,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Xu={default:lb,minimal:db},pb=n=>{var e;return(e=Xu[n])!=null?e:Xu.default},_a=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),m=b("div");m.style.display="none";let f=b("span"),g=b("span"),u=b("button");u.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:m,headerTitle:f,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=pb(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var $a=n=>{var a,i;let e=b("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.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",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Ua=n=>{var W,C,I,D,B,E,z,j,te,We,$e,ve;let e=(W=n==null?void 0:n.sendButton)!=null?W:{},t=(C=e.useIcon)!=null?C:!1,r=(I=e.iconText)!=null?I:"\u2191",o=e.iconName,s=(D=e.stopIconName)!=null?D:"square",a=(B=e.tooltipText)!=null?B:"Send message",i=(E=e.stopTooltipText)!=null?E:"Stop generating",d=(j=(z=n==null?void 0:n.copy)==null?void 0:z.sendButtonLabel)!=null?j:"Send",c=(We=(te=n==null?void 0:n.copy)==null?void 0:te.stopButtonLabel)!=null?We:"Stop",m=($e=e.showTooltip)!=null?$e:!1,f=(ve=e.size)!=null?ve:"40px",g=e.backgroundColor,u=e.textColor,v=b("div","persona-send-button-wrapper"),x=Tt("button",{className:Ms("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!g&&"persona-bg-persona-primary",!t&&!u&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?f:void 0,height:t?f:void 0,minWidth:t?f:void 0,minHeight:t?f:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?u||"var(--persona-button-primary-fg, #ffffff)":u||void 0,backgroundColor:t&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),P=null,T=null;if(t){let Pe=parseFloat(f)||24,Oe=(u==null?void 0:u.trim())||"currentColor";o?(P=Ce(o,Pe,Oe,2),P?x.appendChild(P):x.textContent=r):x.textContent=r,T=Ce(s,Pe,Oe,2)}else x.textContent=d;let M=null;m&&a&&(M=b("div","persona-send-button-tooltip"),M.textContent=a,v.appendChild(M)),x.setAttribute("aria-label",a),v.appendChild(x);let N="send";return{button:x,wrapper:v,setMode:Pe=>{if(Pe===N)return;N=Pe;let Oe=Pe==="stop"?i:a;if(x.setAttribute("aria-label",Oe),M&&(M.textContent=Oe),t){if(P&&T){let Ae=Pe==="stop"?T:P;x.replaceChildren(Ae)}}else x.textContent=Pe==="stop"?c:d}}},qa=n=>{var M,N,k,W,C,I,D,B,E,z,j,te;let e=(M=n==null?void 0:n.voiceRecognition)!=null?M:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((N=e.provider)==null?void 0:N.type)==="runtype";if(!(r||o))return null;let a=(W=(k=n==null?void 0:n.sendButton)==null?void 0:k.size)!=null?W:"40px",i=(C=e.iconName)!=null?C:"mic",d=(I=e.iconSize)!=null?I:a,c=parseFloat(d)||24,m=(B=e.backgroundColor)!=null?B:(D=n==null?void 0:n.sendButton)==null?void 0:D.backgroundColor,f=(z=e.iconColor)!=null?z:(E=n==null?void 0:n.sendButton)==null?void 0:E.textColor,g=b("div","persona-send-button-wrapper"),u=Tt("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:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:m||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),x=Ce(i,c,f||"currentColor",1.5);x?u.appendChild(x):u.textContent="\u{1F3A4}",g.appendChild(u);let P=(j=e.tooltipText)!=null?j:"Start voice recognition";if(((te=e.showTooltip)!=null?te:!1)&&P){let We=b("div","persona-send-button-tooltip");We.textContent=P,g.appendChild(We)}return{button:u,wrapper:g}},za=n=>{var v,x,P,T,M,N,k,W;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(P=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?P:"40px",r=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=e.allowedTypes)!=null?T:$r).join(","),o.multiple=((M=e.maxFiles)!=null?M:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(N=e.buttonIconName)!=null?N:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),m=Tt("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":(k=e.buttonTooltipText)!=null?k:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});m.addEventListener("mouseenter",()=>{m.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),m.addEventListener("mouseleave",()=>{m.style.backgroundColor="transparent"});let f=Ce(s,d,"currentColor",1.5);f?m.appendChild(f):m.textContent="\u{1F4CE}",m.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(m);let g=(W=e.buttonTooltipText)!=null?W:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=g,c.appendChild(u),{button:m,wrapper:c,input:o,previewsContainer:r}},ja=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=b("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Va=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ka=n=>{var v,x,P,T,M,N;let{config:e}=n,t=Tt("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"}}),r=Va(),o=Tt("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:s,attachAutoResize:a}=$a(e);a();let i=Ua(e),d=qa(e),c=za(e),m=ja(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Tt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),f.append(g,u),o.append(f),o.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,m),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:m,attachmentButton:(P=c==null?void 0:c.button)!=null?P:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(M=c==null?void 0:c.input)!=null?M:null,attachmentPreviewsContainer:(N=c==null?void 0:c.previewsContainer)!=null?N:null,actionsRow:f,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var Ju=()=>{let n=Tt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=Ce("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=Ce("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},Yu=n=>{var v,x,P,T,M,N;let{config:e}=n,t=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Va();r.style.display="none";let o=ja(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=$a(e);s.style.maxHeight="100px",a();let i=Ua(e),d=qa(e),c=za(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let m=Tt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),m.addEventListener("click",k=>{k.target!==i.button&&k.target!==i.wrapper&&k.target!==(d==null?void 0:d.button)&&k.target!==(d==null?void 0:d.wrapper)&&k.target!==(c==null?void 0:c.button)&&k.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&m.append(c.input),m.append(f,s,g),c&&t.append(c.previewsContainer),t.append(m,r,o);let u=m;return{footer:t,suggestions:r,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(P=c==null?void 0:c.button)!=null?P:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(M=c==null?void 0:c.input)!=null?M:null,attachmentPreviewsContainer:(N=c==null?void 0:c.previewsContainer)!=null?N:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Zu=n=>{var m,f,g,u,v,x,P,T,M,N,k,W,C,I,D,B,E;let e=(f=(m=n==null?void 0:n.launcher)==null?void 0:m.enabled)!=null?f:!0,t=mn(n);if(Vs(n)){let z=(u=(g=n==null?void 0:n.launcher)==null?void 0:g.composerBar)!=null?u:{},j=b("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(v=z.expandedSize)!=null?v:"anchored",j.style.zIndex=String((P=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?P:xn);let te=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");te.style.width="100%",j.appendChild(te);let We=b("div","persona-widget-pill-root");return We.setAttribute("data-persona-composer-bar",""),We.dataset.state="collapsed",We.dataset.expandedSize=(T=z.expandedSize)!=null?T:"anchored",We.style.zIndex=String((N=(M=n==null?void 0:n.launcher)==null?void 0:M.zIndex)!=null?N:xn),{wrapper:j,panel:te,pillRoot:We}}if(t){let z=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return z.appendChild(j),{wrapper:z,panel:j}}if(!e){let z=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),te=(W=(k=n==null?void 0:n.launcher)==null?void 0:k.width)!=null?W:"100%";return z.style.width=te,j.style.width="100%",z.appendChild(j),{wrapper:z,panel:j}}let o=(C=n==null?void 0:n.launcher)!=null?C:{},s=o.position&&gr[o.position]?gr[o.position]:gr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((D=(I=n==null?void 0:n.launcher)==null?void 0:I.zIndex)!=null?D:xn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(E=(B=n==null?void 0:n.launcher)==null?void 0:B.width)!=null?E:n==null?void 0:n.launcherWidth,c=d!=null?d:Ur;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},ub=(n,e)=>{var k,W,C,I,D,B,E,z,j;let t=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Fa(n,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(W=(k=n==null?void 0:n.launcher)==null?void 0:k.clearChat)==null?void 0:W.enabled)!=null?C:!0,a=null,i=null;if(s){let te=Oa(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=te.button,i=te.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Tt("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"}});c.style.setProperty("scrollbar-gutter","stable");let m=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(I=n==null?void 0:n.copy)==null?void 0:I.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),f=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(E=(B=n==null?void 0:n.copy)==null?void 0:B.welcomeSubtitle)!=null?E:"Ask anything about your account or products."}),g=Tt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},m,f),u=b("div","persona-flex persona-flex-col persona-gap-3"),v=(z=n==null?void 0:n.layout)==null?void 0:z.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((j=n==null?void 0:n.copy)==null?void 0:j.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,u);let P=Tt("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"}}),T=Yu({config:n}),{root:M,textNode:N}=Ju();return t.append(d,o,c,P),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:u,composerOverlay:P,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:m,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:M,peekTextNode:N}},em=(n,e=!0)=>{var P,T,M,N,k,W,C,I,D;if(Vs(n))return ub(n,e);let t=Tt("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"}}),r=(P=n==null?void 0:n.layout)==null?void 0:P.header,o=((T=n==null?void 0:n.layout)==null?void 0:T.showHeader)!==!1,s=r?_a(n,r,{showClose:e}):Wo({config:n,showClose:e}),a=Tt("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=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(M=n==null?void 0:n.copy)==null?void 0:M.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),d=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(k=n==null?void 0:n.copy)==null?void 0:k.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),c=Tt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:mn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),m=b("div","persona-flex persona-flex-col persona-gap-3"),f=(C=n==null?void 0:n.layout)==null?void 0:C.contentMaxWidth;f&&(m.style.maxWidth=f,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((I=n==null?void 0:n.copy)==null?void 0:I.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,m);let u=Ka({config:n}),v=((D=n==null?void 0:n.layout)==null?void 0:D.showFooter)!==!1;o?Ks(t,s,n):(s.header.style.display="none",Ks(t,s,n)),t.append(a);let x=Tt("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 v||(u.footer.style.display="none"),t.append(u.footer),t.append(x),{container:t,body:a,messagesWrapper:m,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Ni=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
18
+ _Details: ${n.message}_`:r}var Us=t=>({isError:!0,content:[{type:"text",text:t}]}),Lu=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Pu=t=>es(t)||t===zr,Ia=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=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 $s(()=>this.createSpeechEngine());this.handleEvent=e=>{var n,r,o,s,a,i,d,c,u,f;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,m=!!(g!=null&&g.name)&&(es(g.name)||g.name===zr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(u=this.callbacks).onError)==null||f.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Fs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let n=(o=e.host)!=null?o:this.config.apiUrl,r=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||Wi().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Pi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,n,r;return(r=(n=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:n.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let n=is.isSupported()?new is({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,u=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&u)return Wi().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:m})=>{let x=new g({host:d,agentId:c,clientToken:u,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&n?new m(x,n,{onFallback:v=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${v.message}`)}):x});if(f&&n)return u&&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(e){var n,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=as(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,u,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=e.browser)==null?void 0:u.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(e=this.callbacks).onError)==null||n.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!Nf(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new Fs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:f}=e,m={id:a!=null?a:n==="user"?Ta():n==="assistant"?Os():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:f=!1,voiceProcessing:g,rawContent:m}=r,v={id:d!=null?d:o==="user"?Ta():o==="assistant"?Os():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,n){var c,u,f,g,m;let r=e.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Ta(),s=Os(),a={id:o,role:"user",content:r||Ea,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let M=ku(x,this.config.errorMessage);if(M){let W={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(W)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(f=(u=this.callbacks).onError)==null||f.call(u,x):(m=(g=this.callbacks).onError)==null||m.call(g,new Error(String(x))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Os();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let f=ku(c,this.config.errorMessage);if(f){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,n){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(e,n,r){var u,f,g,m,x;let o=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,r):v=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),v){let M=null;if(v instanceof Response){if(!v.ok){let W=await v.json().catch(()=>null);throw new Error((g=W==null?void 0:W.error)!=null?g:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);M?await this.connectStream(M,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(x=(m=this.callbacks).onError)==null||x.call(m,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){var u,f,g,m,x,v,M,W,T,k,E,P;let r=this.messages.find(C=>C.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(x=(m=this.callbacks).onError)==null||x.call(m,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=(v=e.toolCall)==null?void 0:v.args,L=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(L.length===1){let F=typeof((M=L[0])==null?void 0:M.question)=="string"?L[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(e,a),(W=this.abortController)==null||W.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([L,F])=>`${L}: ${Array.isArray(F)?F.join(", "):F}`).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!=null?a:{};c.forEach((L,F)=>{let O=typeof(L==null?void 0:L.question)=="string"?L.question:"";if(!O)return;let R=C[O],$=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:$||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let L=await C.json().catch(()=>null);throw new Error((k=L==null?void 0:L.error)!=null?k:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let L=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(P=(E=this.callbacks).onError)==null||P.call(E,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let n=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let n=this.messages.find(a=>a.id===e.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let n=this.messages.find(s=>s.id===e.id);return((o=(n!=null?n:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){var d,c,u,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var P,C,L,F,O,R,$;let m=(P=g.toolCall)==null?void 0:P.name,x=(C=g.toolCall)==null?void 0:C.id;if(!m||!x)return null;let v=`${e}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(v),r.push(v);let M=this.markWebMcpToolRunning(g),W=(F=(L=g.agentMetadata)==null?void 0:L.webMcpToolCallId)!=null?F:m;if(m===zr)return{dedupeKey:v,resumeKey:W,output:Ai(),toolMessage:g,startedAt:M,completedAt:Date.now()};let T=new AbortController;this.webMcpResolveControllers.add(T),o.push(T);let k=this.client.executeWebMcpToolCall(m,(O=g.toolCall)==null?void 0:O.args,T.signal),E;if(!k)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await k}catch(N){let Z=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return Z||($=(R=this.callbacks).onError)==null||$.call(R,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(g,Us(Z?"Aborted by cancel()":Lu(N)),M),this.webMcpInflightKeys.delete(v),null}return T.signal.aborted?(this.markWebMcpToolComplete(g,Us("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:W,output:E,toolMessage:g,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let g={};for(let x of i)g[x.resumeKey]=x.output;let m=await this.client.resumeFlow(e,g,{signal:s.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((c=x.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(f=(u=this.callbacks).onError)==null||f.call(u,g instanceof Error?g:new Error(String(g)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Us("Aborted by cancel()"),x.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var x,v,M,W,T,k,E,P,C,L,F,O;let n=(x=e.agentMetadata)==null?void 0:x.executionId,r=(v=e.toolCall)==null?void 0:v.name,o=(M=e.toolCall)==null?void 0:M.id;if(!n){(T=(W=this.callbacks).onError)==null||T.call(W,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch($){(E=(k=this.callbacks).onError)==null||E.call(k,$ instanceof Error?$:new Error(String($)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,u=(P=e.toolCall)==null?void 0:P.args,f=c?null:this.client.executeWebMcpToolCall(r,u,d),g="execute",m=a;try{let R;if(c?R=Ai():f?R=await f:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Us("Aborted by cancel()"),a);return}let $=(L=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?L:r;g="resume",await this.resumeWithToolOutput(n,$,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,R,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let $=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(g==="execute"||$||d.aborted)&&this.markWebMcpToolComplete(e,Us($||d.aborted?"Aborted by cancel()":Lu(R)),a),$||(O=(F=this.callbacks).onError)==null||O.call(F,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,r,o){var a,i;let s=await this.client.resumeFlow(e,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,n;(n=(e=this.callbacks).onArtifactsState)==null||n.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var n,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(n=e.component)!=null?n:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Ii(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ka(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let r=Ii(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var u,f,g,m,x,v,M,W,T,k,E,P,C,L,F;if(s!==r)return o;let a={...o,...n};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let O=o.approval,R=n.approval;a.approval={...O,...R,executionId:R.executionId||O.executionId,toolName:R.toolName||O.toolName,description:R.description||O.description,toolType:(m=R.toolType)!=null?m:O.toolType,reason:(x=R.reason)!=null?x:O.reason,parameters:(v=R.parameters)!=null?v:O.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(W=n.agentMetadata)==null?void 0:W.executionId,c=(T=n.toolCall)==null?void 0:T.id;if(i&&Pu(i)&&d&&c&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let O=`${d}:${c}`,R=this.webMcpInflightKeys.has(O),$=this.webMcpResolvedKeys.has(O),N=(E=o.toolCall)==null?void 0:E.name,Z=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&N!==void 0&&Pu(N)&&((L=o.toolCall)==null?void 0:L.status)==="complete";(R||$||Z)&&(a.agentMetadata={...(F=a.agentMetadata)!=null?F:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as Ff,ArrowDown as Of,ArrowUp as _f,ArrowUpRight as $f,Bot as Uf,ChevronDown as zf,ChevronUp as qf,ChevronRight as jf,ChevronLeft as Vf,Check as Kf,Clipboard as Gf,ClipboardCopy as Qf,Copy as Xf,File as Jf,FileCode as Yf,FileSpreadsheet as Zf,FileText as eh,ImagePlus as th,Loader as nh,LoaderCircle as rh,Mic as oh,Paperclip as sh,RefreshCw as ah,Search as ih,Send as lh,ShieldAlert as ch,ShieldCheck as dh,ShieldX as ph,Square as uh,ThumbsDown as mh,ThumbsUp as gh,Upload as fh,Volume2 as hh,X as yh,User as bh,Mail as vh,Phone as xh,Calendar as wh,Clock as Ch,Building as Ah,MapPin as Sh,Lock as Th,Key as Eh,CreditCard as Mh,AtSign as kh,Hash as Lh,Globe as Ph,Link as Ih,CircleCheck as Wh,CircleX as Rh,TriangleAlert as Hh,Info as Bh,Ban as Dh,Shield as Nh,ArrowLeft as Fh,ArrowRight as Oh,ExternalLink as _h,Ellipsis as $h,EllipsisVertical as Uh,Menu as zh,House as qh,Plus as jh,Minus as Vh,Pencil as Kh,Trash as Gh,Trash2 as Qh,Save as Xh,Download as Jh,Share as Yh,Funnel as Zh,Settings as ey,RotateCw as ty,Maximize as ny,Minimize as ry,ShoppingCart as oy,ShoppingBag as sy,Package as ay,Truck as iy,Tag as ly,Gift as cy,Receipt as dy,Wallet as py,Store as uy,DollarSign as my,Percent as gy,Play as fy,Pause as hy,VolumeX as yy,Camera as by,Image as vy,Film as xy,Headphones as wy,MessageCircle as Cy,MessageSquare as Ay,Bell as Sy,Heart as Ty,Star as Ey,Eye as My,EyeOff as ky,Bookmark as Ly,CalendarDays as Py,History as Iy,Timer as Wy,Folder as Ry,FolderOpen as Hy,Files as By,Sparkles as Dy,Zap as Ny,Sun as Fy,Moon as Oy,Flag as _y,Monitor as $y,Smartphone as Uy}from"lucide";var zy={activity:Ff,"arrow-down":Of,"arrow-up":_f,"arrow-up-right":$f,bot:Uf,"chevron-down":zf,"chevron-up":qf,"chevron-right":jf,"chevron-left":Vf,check:Kf,clipboard:Gf,"clipboard-copy":Qf,copy:Xf,file:Jf,"file-code":Yf,"file-spreadsheet":Zf,"file-text":eh,"image-plus":th,loader:nh,"loader-circle":rh,mic:oh,paperclip:sh,"refresh-cw":ah,search:ih,send:lh,"shield-alert":ch,"shield-check":dh,"shield-x":ph,square:uh,"thumbs-down":mh,"thumbs-up":gh,upload:fh,"volume-2":hh,x:yh,user:bh,mail:vh,phone:xh,calendar:wh,clock:Ch,building:Ah,"map-pin":Sh,lock:Th,key:Eh,"credit-card":Mh,"at-sign":kh,hash:Lh,globe:Ph,link:Ih,"circle-check":Wh,"circle-x":Rh,"triangle-alert":Hh,info:Bh,ban:Dh,shield:Nh,"arrow-left":Fh,"arrow-right":Oh,"external-link":_h,ellipsis:$h,"ellipsis-vertical":Uh,menu:zh,house:qh,plus:jh,minus:Vh,pencil:Kh,trash:Gh,"trash-2":Qh,save:Xh,download:Jh,share:Yh,funnel:Zh,settings:ey,"rotate-cw":ty,maximize:ny,minimize:ry,"shopping-cart":oy,"shopping-bag":sy,package:ay,truck:iy,tag:ly,gift:cy,receipt:dy,wallet:py,store:uy,"dollar-sign":my,percent:gy,play:fy,pause:hy,"volume-x":yy,camera:by,image:vy,film:xy,headphones:wy,"message-circle":Cy,"message-square":Ay,bell:Sy,heart:Ty,star:Ey,eye:My,"eye-off":ky,bookmark:Ly,"calendar-days":Py,history:Iy,timer:Wy,folder:Ry,"folder-open":Hy,files:By,sparkles:Dy,zap:Ny,sun:Fy,moon:Oy,flag:_y,monitor:$y,smartphone:Uy},fe=(t,e=24,n="currentColor",r=2)=>{let o=zy[t];return o?qy(o,e,n,r):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function qy(t,e,n,r){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Wa={allowedTypes:qr,maxFileSize:10*1024*1024,maxFiles:4};function jy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Vy(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var zs=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=e.allowedTypes)!=null?n:Wa.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Wa.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Wa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Wa.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var n,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let u=bu(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let f=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await yu(c),g=Ma(c)?URL.createObjectURL(c):null,m={id:jy(),file:c,previewUrl:g,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let n=this.attachments.findIndex(d=>d.id===e);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(e=this.config).onAttachmentsChange)==null||n.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Ma(e.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",n&&e.previewUrl){let a=y("img");a.src=e.previewUrl,a.alt=e.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",r.appendChild(a)}else{let a=y("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=Vy(e.file.type),d=fe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=vu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:n})}};var Iu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function qs(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];Iu(s)&&Iu(o)?n[r]=qs(s,o):n[r]=o}return n}var jr="min(440px, calc(100vw - 24px))",Ru="440px",Ky={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:jr,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)"},Ht={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ky,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:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,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 Wu(t,e){if(!(!t&&!e))return t?e?qs(t,e):t:e}function Hu(t){var e,n,r,o,s,a,i,d,c,u,f,g,m,x,v,M,W,T,k,E,P;return t?{...Ht,...t,theme:Wu(Ht.theme,t.theme),darkTheme:Wu(Ht.darkTheme,t.darkTheme),launcher:{...Ht.launcher,...t.launcher,dock:{...(e=Ht.launcher)==null?void 0:e.dock,...(n=t.launcher)==null?void 0:n.dock},clearChat:{...(r=Ht.launcher)==null?void 0:r.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...Ht.copy,...t.copy},sendButton:{...Ht.sendButton,...t.sendButton},statusIndicator:{...Ht.statusIndicator,...t.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...t.voiceRecognition},features:(()=>{var oe,se,de,$e,Ne,V,G,be,X,le;let C=(oe=Ht.features)==null?void 0:oe.artifacts,L=(se=t.features)==null?void 0:se.artifacts,F=(de=Ht.features)==null?void 0:de.scrollToBottom,O=($e=t.features)==null?void 0:$e.scrollToBottom,R=(Ne=Ht.features)==null?void 0:Ne.scrollBehavior,$=(V=t.features)==null?void 0:V.scrollBehavior,N=(G=Ht.features)==null?void 0:G.streamAnimation,Z=(be=t.features)==null?void 0:be.streamAnimation,Se=(X=Ht.features)==null?void 0:X.askUserQuestion,pe=(le=t.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&L===void 0?void 0:{...C,...L,layout:{...C==null?void 0:C.layout,...L==null?void 0:L.layout}},ve=F===void 0&&O===void 0?void 0:{...F,...O},Ie=R===void 0&&$===void 0?void 0:{...R,...$},ce=N===void 0&&Z===void 0?void 0:{...N,...Z},ue=Se===void 0&&pe===void 0?void 0:{...Se,...pe,styles:{...Se==null?void 0:Se.styles,...pe==null?void 0:pe.styles}};return{...Ht.features,...t.features,...ve!==void 0?{scrollToBottom:ve}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...ee!==void 0?{artifacts:ee}:{},...ce!==void 0?{streamAnimation:ce}:{},...ue!==void 0?{askUserQuestion:ue}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...Ht.layout,...t.layout,header:{...(a=Ht.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=Ht.layout)==null?void 0:d.messages,...(c=t.layout)==null?void 0:c.messages,avatar:{...(f=(u=Ht.layout)==null?void 0:u.messages)==null?void 0:f.avatar,...(m=(g=t.layout)==null?void 0:g.messages)==null?void 0:m.avatar},timestamp:{...(v=(x=Ht.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(W=(M=t.layout)==null?void 0:M.messages)==null?void 0:W.timestamp}},slots:{...(T=Ht.layout)==null?void 0:T.slots,...(k=t.layout)==null?void 0:k.slots}},markdown:{...Ht.markdown,...t.markdown,options:{...(E=Ht.markdown)==null?void 0:E.options,...(P=t.markdown)==null?void 0:P.options}},messageActions:{...Ht.messageActions,...t.messageActions}}:Ht}var Gy={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"}},Qy={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"}},Xy={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"}},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:jr,maxWidth:Ru,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},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:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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 ls(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),r=t;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ls(t,r):r}function Bu(t){let e={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ls(t,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function Jy(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Du(t,e){let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Du(s,o):n[r]=o}return n}function Yy(t,e){return e?Du(t,e):t}function Wo(t,e={}){var o,s,a,i,d,c,u,f,g,m,x,v,M;let n={palette:Gy,semantic:Qy,components:Xy},r={palette:{...n.palette,...t==null?void 0:t.palette,colors:{...n.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=t==null?void 0:t.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...t==null?void 0:t.semantic,colors:{...n.semantic.colors,...(u=t==null?void 0:t.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(g=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(x=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=t==null?void 0:t.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(M=t==null?void 0:t.semantic)==null?void 0:M.typography}},components:Yy(n.components,t==null?void 0:t.components)};if(e.validate!==!1){let W=Jy(r);if(!W.valid)throw new Error(`Theme validation failed: ${W.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let W of e.plugins)r=W.transform(r);return r}function Nu(t){var v,M,W,T,k,E,P,C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue,oe,se,de,$e,Ne,V,G,be,X,le,Ee,Xe,Ze,wt,dt,Ye,He,K,qe,ze,xe,Ce,tt,Ot,ne,Oe,gn,Bt,Xt,Ir,hr,A,te,Te,Re,ke,Be,Ve,at,Pt,bt,H,J,Ae,it,Qe,Ut,fn,vt,xt,It,Ct,ln,_t,Nn,Sn,Tn,bn,En,ar,At,yr,br,Wr,ir,ut,mo,vr,go,Wn,Oo,Kr,Rr,Gr,Qr,fo,ho,Xr,yt,Fn,On,Mn,St,Xn,Jn,_n,Jr,Hr,Yr,$n,Wt,kn,Yn,Zr,Br,eo;let e=Bu(t),n={};for(let[he,Rn]of Object.entries(e)){let xr=he.replace(/\./g,"-");n[`--persona-${xr}`]=Rn.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(W=n["--persona-semantic-colors-accent"])!=null?W:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(T=n["--persona-semantic-colors-surface"])!=null?T:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(E=n["--persona-semantic-colors-container"])!=null?E:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(L=n["--persona-semantic-colors-text-inverse"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(O=n["--persona-semantic-colors-divider"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=($=n["--persona-components-voice-recording-background"])!=null?$:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(N=n["--persona-components-voice-processing-icon"])!=null?N:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Se=n["--persona-components-approval-requested-background"])!=null?Se:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ve=n["--persona-components-approval-requested-shadow"])!=null?ve:"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"]=(Ie=n["--persona-components-approval-approve-background"])!=null?Ie:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ce=n["--persona-components-approval-deny-background"])!=null?ce:n["--persona-container"],n["--persona-attachment-image-bg"]=(ue=n["--persona-components-attachment-image-background"])!=null?ue:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(oe=n["--persona-components-attachment-image-border"])!=null?oe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(se=n["--persona-semantic-typography-fontFamily"])!=null?se:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(de=n["--persona-semantic-typography-fontSize"])!=null?de:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=($e=n["--persona-semantic-typography-fontWeight"])!=null?$e:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Ne=n["--persona-semantic-typography-lineHeight"])!=null?Ne: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"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(G=n["--persona-palette-radius-md"])!=null?G:"0.375rem",n["--persona-radius-lg"]=(be=n["--persona-palette-radius-lg"])!=null?be:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(Xe=(Ee=n["--persona-components-launcher-borderRadius"])!=null?Ee:n["--persona-palette-radius-full"])!=null?Xe:"9999px",n["--persona-launcher-bg"]=(Ze=n["--persona-components-launcher-background"])!=null?Ze:n["--persona-primary"],n["--persona-launcher-fg"]=(wt=n["--persona-components-launcher-foreground"])!=null?wt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(dt=n["--persona-components-launcher-border"])!=null?dt:n["--persona-border"],n["--persona-button-primary-bg"]=(Ye=n["--persona-components-button-primary-background"])!=null?Ye:n["--persona-primary"],n["--persona-button-primary-fg"]=(He=n["--persona-components-button-primary-foreground"])!=null?He:n["--persona-text-inverse"],n["--persona-button-radius"]=(qe=(K=n["--persona-components-button-primary-borderRadius"])!=null?K:n["--persona-palette-radius-full"])!=null?qe:"9999px",n["--persona-panel-radius"]=(xe=(ze=n["--persona-components-panel-borderRadius"])!=null?ze:n["--persona-radius-xl"])!=null?xe:"0.75rem",n["--persona-panel-border"]=(Ce=n["--persona-components-panel-border"])!=null?Ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ot=(tt=n["--persona-components-panel-shadow"])!=null?tt:n["--persona-palette-shadows-xl"])!=null?Ot:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(ne=n["--persona-components-launcher-shadow"])!=null?ne:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(gn=(Oe=n["--persona-components-input-borderRadius"])!=null?Oe:n["--persona-radius-lg"])!=null?gn:"0.5rem",n["--persona-message-user-radius"]=(Xt=(Bt=n["--persona-components-message-user-borderRadius"])!=null?Bt:n["--persona-radius-lg"])!=null?Xt:"0.5rem",n["--persona-message-assistant-radius"]=(hr=(Ir=n["--persona-components-message-assistant-borderRadius"])!=null?Ir:n["--persona-radius-lg"])!=null?hr:"0.5rem",n["--persona-header-bg"]=(A=n["--persona-components-header-background"])!=null?A:n["--persona-surface"],n["--persona-header-border"]=(te=n["--persona-components-header-border"])!=null?te:n["--persona-divider"],n["--persona-header-icon-bg"]=(Te=n["--persona-components-header-iconBackground"])!=null?Te:n["--persona-primary"],n["--persona-header-icon-fg"]=(Re=n["--persona-components-header-iconForeground"])!=null?Re:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ke=n["--persona-components-header-titleForeground"])!=null?ke:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Be=n["--persona-components-header-subtitleForeground"])!=null?Be:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ve=n["--persona-components-header-actionIconForeground"])!=null?Ve:n["--persona-muted"];let r=(at=t.components)==null?void 0:at.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(Pt=t.components)==null?void 0:Pt.introCard;n["--persona-intro-card-bg"]=(bt=n["--persona-components-introCard-background"])!=null?bt:n["--persona-surface"],n["--persona-intro-card-radius"]=(H=n["--persona-components-introCard-borderRadius"])!=null?H:"1rem",n["--persona-intro-card-padding"]=(J=n["--persona-components-introCard-padding"])!=null?J:"1.5rem",n["--persona-intro-card-shadow"]=(it=(Ae=o==null?void 0:o.shadow)!=null?Ae:n["--persona-components-introCard-shadow"])!=null?it:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Qe=n["--persona-components-input-background"])!=null?Qe:n["--persona-surface"],n["--persona-input-placeholder"]=(Ut=n["--persona-components-input-placeholder"])!=null?Ut:n["--persona-text-muted"],n["--persona-message-user-bg"]=(fn=n["--persona-components-message-user-background"])!=null?fn:n["--persona-accent"],n["--persona-message-user-text"]=(vt=n["--persona-components-message-user-text"])!=null?vt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(xt=n["--persona-components-message-user-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(It=n["--persona-components-message-assistant-background"])!=null?It:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ct=n["--persona-components-message-assistant-text"])!=null?Ct:n["--persona-text"],n["--persona-message-assistant-border"]=(ln=n["--persona-components-message-assistant-border"])!=null?ln:n["--persona-border"],n["--persona-message-assistant-shadow"]=(_t=n["--persona-components-message-assistant-shadow"])!=null?_t:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Sn=(Nn=n["--persona-components-scrollToBottom-background"])!=null?Nn:n["--persona-button-primary-bg"])!=null?Sn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bn=(Tn=n["--persona-components-scrollToBottom-foreground"])!=null?Tn:n["--persona-button-primary-fg"])!=null?bn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(En=n["--persona-components-scrollToBottom-border"])!=null?En:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(br=(yr=(At=n["--persona-components-scrollToBottom-borderRadius"])!=null?At:n["--persona-button-radius"])!=null?yr:n["--persona-radius-full"])!=null?br:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Wr=n["--persona-components-scrollToBottom-shadow"])!=null?Wr:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(ut=n["--persona-components-scrollToBottom-padding"])!=null?ut:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(mo=n["--persona-components-scrollToBottom-gap"])!=null?mo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(go=(vr=n["--persona-components-scrollToBottom-fontSize"])!=null?vr:n["--persona-palette-typography-fontSize-sm"])!=null?go:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Wn=n["--persona-components-scrollToBottom-iconSize"])!=null?Wn:"14px",n["--persona-tool-bubble-shadow"]=(Oo=n["--persona-components-toolBubble-shadow"])!=null?Oo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Kr=n["--persona-components-reasoningBubble-shadow"])!=null?Kr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Rr=n["--persona-components-composer-shadow"])!=null?Rr:"none",n["--persona-md-inline-code-bg"]=(Gr=n["--persona-components-markdown-inlineCode-background"])!=null?Gr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Qr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Qr:n["--persona-text"],n["--persona-md-link-color"]=(ho=(fo=n["--persona-components-markdown-link-foreground"])!=null?fo:n["--persona-accent"])!=null?ho:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Xr=n["--persona-components-markdown-codeBlock-background"])!=null?Xr:n["--persona-container"],n["--persona-md-code-block-border-color"]=(yt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?yt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Fn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Fn:"inherit",n["--persona-md-table-header-bg"]=(On=n["--persona-components-markdown-table-headerBackground"])!=null?On:n["--persona-container"],n["--persona-md-table-border-color"]=(Mn=n["--persona-components-markdown-table-borderColor"])!=null?Mn:n["--persona-border"],n["--persona-md-hr-color"]=(St=n["--persona-components-markdown-hr-color"])!=null?St:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Xn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Xn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Jn=n["--persona-components-markdown-blockquote-background"])!=null?Jn:"transparent",n["--persona-md-blockquote-text-color"]=(_n=n["--persona-components-markdown-blockquote-textColor"])!=null?_n:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Jr=n["--persona-components-collapsibleWidget-container"])!=null?Jr:n["--persona-surface"],n["--cw-surface"]=(Hr=n["--persona-components-collapsibleWidget-surface"])!=null?Hr:n["--persona-surface"],n["--cw-border"]=(Yr=n["--persona-components-collapsibleWidget-border"])!=null?Yr:n["--persona-border"],n["--persona-message-border"]=($n=n["--persona-components-message-border"])!=null?$n:n["--persona-border"];let u=t.components,f=u==null?void 0:u.iconButton;f&&(f.background&&(n["--persona-icon-btn-bg"]=f.background),f.border&&(n["--persona-icon-btn-border"]=f.border),f.color&&(n["--persona-icon-btn-color"]=f.color),f.padding&&(n["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(n["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(n["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(n["--persona-icon-btn-active-border"]=f.activeBorder));let g=u==null?void 0:u.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let he=x.toolbar;he.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,n["--persona-dropdown-bg"]=(Wt=n["--persona-dropdown-bg"])!=null?Wt:he.copyMenuBackground),he.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,n["--persona-dropdown-border"]=(kn=n["--persona-dropdown-border"])!=null?kn:he.copyMenuBorder),he.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,n["--persona-dropdown-shadow"]=(Yn=n["--persona-dropdown-shadow"])!=null?Yn:he.copyMenuShadow),he.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Zr=n["--persona-dropdown-radius"])!=null?Zr:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Br=n["--persona-dropdown-item-hover-bg"])!=null?Br:he.copyMenuItemHoverBackground),he.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(x!=null&&x.tab){let he=x.tab;he.background&&(n["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(n["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(n["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(n["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(n["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(n["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(n["--persona-artifact-tab-list-padding"]=he.listPadding)}if(x!=null&&x.pane){let he=x.pane;if(he.toolbarBackground){let Rn=(eo=ls(t,he.toolbarBackground))!=null?eo:he.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Rn}}return n}var Zy={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"}}},Fu=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ri=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},eb=t=>{var n;let e=(n=t==null?void 0:t.colorScheme)!=null?n:"light";return e==="light"?"light":e==="dark"?"dark":Ri()},tb=t=>eb(t),nb=t=>Wo(t),rb=t=>{var n;let e=Wo(void 0,{validate:!1});return Wo({...t,palette:{...e.palette,colors:{...Zy.colors,...(n=t==null?void 0:t.palette)==null?void 0:n.colors}}},{validate:!1})},Ra=t=>{let e=tb(t),n=Fu(t==null?void 0:t.theme),r=Fu(t==null?void 0:t.darkTheme);return e==="dark"?rb(qs(n!=null?n:{},r!=null?r:{})):nb(n)},ob=t=>Nu(t),cs=(t,e)=>{let n=Ra(e),r=ob(n);for(let[o,s]of Object.entries(r))t.style.setProperty(o,s)},Ou=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{t(Ri())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>t(Ri());n.addEventListener?(n.addEventListener("change",r),e.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),e.push(()=>n.removeListener(r)))}return()=>{e.forEach(n=>n())}};import{Idiomorph as sb}from"idiomorph";var Ha=(t,e,n={})=>{let{preserveTypingAnimation:r=!0}=n;sb.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var _u=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Ba={index:-1,draft:""};function $u(t){let{direction:e,history:n,currentValue:r,atStart:o,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ba}}}function Uu(t,e){var n,r,o,s,a,i,d,c,u,f,g,m,x,v,M,W,T,k,E,P,C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue,oe,se,de;return[t.id,t.role,(r=(n=t.content)==null?void 0:n.length)!=null?r:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=t.llmContent)==null?void 0:c.length)!=null?u:0,(g=(f=t.approval)==null?void 0:f.status)!=null?g:"",(x=(m=t.toolCall)==null?void 0:m.status)!=null?x:"",(M=(v=t.toolCall)==null?void 0:v.name)!=null?M:"",(k=(T=(W=t.toolCall)==null?void 0:W.chunks)==null?void 0:T.length)!=null?k:0,(L=(C=(P=(E=t.toolCall)==null?void 0:E.chunks)==null?void 0:P[t.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?L:"",typeof((F=t.toolCall)==null?void 0:F.args)=="string"?t.toolCall.args.length:(O=t.toolCall)!=null&&O.args?JSON.stringify(t.toolCall.args).length:0,(N=($=(R=t.reasoning)==null?void 0:R.chunks)==null?void 0:$.length)!=null?N:0,(ee=(pe=(Se=(Z=t.reasoning)==null?void 0:Z.chunks)==null?void 0:Se[t.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(ue=(ce=(Ie=(ve=t.reasoning)==null?void 0:ve.chunks)==null?void 0:Ie[t.reasoning.chunks.length-1])==null?void 0:ce.slice(-32))!=null?ue:"",(se=(oe=t.contentParts)==null?void 0:oe.length)!=null?se:0,(de=t.stopReason)!=null?de:"",e].join("\0")}function zu(){return new Map}function qu(t,e,n){let r=t.get(e);return r&&r.fingerprint===n?r.wrapper:null}function ju(t,e,n,r){t.set(e,{fingerprint:n,wrapper:r})}function Vu(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Da(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Vr(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Ro(t,e){return Vr(t)-t.scrollTop<=e}function Na(t){let{following:e,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=t,u=n-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Fa(t){let{following:e,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=t;return e&&n<0?"pause":!e&&o&&n>0&&r?"resume":"none"}function Ku(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Gu(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Qu(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var wn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cn=1e5,po=Cn+1;var js={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ab=["pre","code","a","script","style"],Oa=t=>{var e,n,r,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:js.type,placeholder:(n=t==null?void 0:t.placeholder)!=null?n:js.placeholder,speed:(r=t==null?void 0:t.speed)!=null?r:js.speed,duration:(o=t==null?void 0:t.duration)!=null?o:js.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:js.buffer}},ib=[{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"}],Ju=new Map;for(let t of ib)Ju.set(t.name,t);var Vs=(t,e)=>{var n,r;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(n=e[t])!=null?n:null:(r=Ju.get(t))!=null?r:null},_a=(t,e,n,r,o)=>{if(!o)return t;if(n!=null&&n.bufferContent)return n.bufferContent(t,r);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
19
+ `);return s<0?"":t.slice(0,s)}return t},lb=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},cb=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Hi=/\s/,db=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(e.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},pb=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Hi.test(s[i])){let c=i;for(;c<s.length&&Hi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Hi.test(s[u]);)c.appendChild(lb(r,s[u],e,n.value)),n.value+=1,u+=1;a.appendChild(c),i=u}o.replaceChild(a,t)},ub=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(cb(r,c,e,n.value)),n.value+=1));o.replaceChild(a,t)},Ks=(t,e,n,r)=>{var f,g;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:ab).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)db(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},u=e==="char"?pb:ub;for(let m of i)u(m,n,c);return o.innerHTML},$a=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Gs=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Xu=new WeakMap,mb=(t,e)=>{var s;if(!t.styles)return;let n=Xu.get(e);if(n||(n=new Set,Xu.set(e,n)),n.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(t.name)}n.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},Bi=new WeakMap,gb=(t,e)=>{if(!t.onAttach)return;let n=Bi.get(e);if(n||(n=new Map,Bi.set(e,n)),n.has(t.name))return;let r=t.onAttach(e);n.set(t.name,r)},Yu=t=>{let e=Bi.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Di=(t,e)=>{mb(t,e),gb(t,e)};function Ni(t,e=Cn){let n=t.style.position,r=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=r,t.style.isolation=o}}var Qs=0,uo=null;function Fi(t=document){var n;if(Qs++,Qs===1){let r=t.body,s=((n=t.defaultView)!=null?n:window).scrollY||t.documentElement.scrollTop;uo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,Qs=Math.max(0,Qs-1),Qs===0&&uo)){let o=t.body,s=(r=t.defaultView)!=null?r:window;o.style.overflow=uo.originalOverflow,o.style.position=uo.originalPosition,o.style.top=uo.originalTop,o.style.width=uo.originalWidth,s.scrollTo(0,uo.scrollY),uo=null}}}var Xs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},yn=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="docked"},Js=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="composer-bar"},gr=t=>{var n,r,o,s,a,i;let e=(n=t==null?void 0:t.launcher)==null?void 0:n.dock;return{side:(r=e==null?void 0:e.side)!=null?r:Xs.side,width:(o=e==null?void 0:e.width)!=null?o:Xs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Xs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Xs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Xs.maxHeight}};var fr={"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 fb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ua=(t,e={})=>{var M,W,T,k,E,P;let{showClose:n=!0,wrapperClassName:r=fb,buttonSize:o,iconSize:s="28px"}=e,a=(M=t==null?void 0:t.launcher)!=null?M:{},i=(W=o!=null?o:a.closeButtonSize)!=null?W:"32px",d=y("div",r),c=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(k=a.closeButtonShowTooltip)!=null?k:!0,f=(E=a.closeButtonIconName)!=null?E:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Et("button",{className:Is("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||In.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${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}}),v=fe(f,s,"currentColor",1);if(v?(v.style.display="block",x.appendChild(v)):x.textContent=g,d.appendChild(x),u&&c){let C=null,L=()=>{if(C)return;let O=x.ownerDocument,R=O.body;if(!R)return;C=Pr(O,"div","persona-clear-chat-tooltip"),C.textContent=c;let $=Pr(O,"div");$.className="persona-clear-chat-tooltip-arrow",C.appendChild($);let N=x.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(po),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",L),d.addEventListener("mouseleave",F),x.addEventListener("focus",L),x.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",L),d.removeEventListener("mouseleave",F),x.removeEventListener("focus",L),x.removeEventListener("blur",F)}}return{button:x,wrapper:d}},hb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",za=(t,e={})=>{var C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie;let{wrapperClassName:n=hb,buttonSize:r,iconSize:o="20px"}=e,a=(L=((C=t==null?void 0:t.launcher)!=null?C:{}).clearChat)!=null?L:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",c=(R=a.iconColor)!=null?R:"",u=($=a.backgroundColor)!=null?$:"",f=(N=a.borderWidth)!=null?N:"",g=(Z=a.borderColor)!=null?Z:"",m=(Se=a.borderRadius)!=null?Se:"",x=(pe=a.paddingX)!=null?pe:"",v=(ee=a.paddingY)!=null?ee:"",M=(ve=a.tooltipText)!=null?ve:"Clear chat",W=(Ie=a.showTooltip)!=null?Ie:!0,T=y("div",n),k=!!(f||g),E=Et("button",{className:Is("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:c||In.actionIconColor,backgroundColor:u||void 0,border:k?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),P=fe(d,o,"currentColor",1);if(P&&(P.style.display="block",E.appendChild(P)),T.appendChild(E),W&&M){let ce=null,ue=()=>{if(ce)return;let se=E.ownerDocument,de=se.body;if(!de)return;ce=Pr(se,"div","persona-clear-chat-tooltip"),ce.textContent=M;let $e=Pr(se,"div");$e.className="persona-clear-chat-tooltip-arrow",ce.appendChild($e);let Ne=E.getBoundingClientRect();ce.style.position="fixed",ce.style.zIndex=String(po),ce.style.left=`${Ne.left+Ne.width/2}px`,ce.style.top=`${Ne.top-8}px`,ce.style.transform="translate(-50%, -100%)",de.appendChild(ce)},oe=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};T.addEventListener("mouseenter",ue),T.addEventListener("mouseleave",oe),E.addEventListener("focus",ue),E.addEventListener("blur",oe),T._cleanupTooltip=()=>{oe(),T.removeEventListener("mouseenter",ue),T.removeEventListener("mouseleave",oe),E.removeEventListener("focus",ue),E.removeEventListener("blur",oe)}}return{button:E,wrapper:T}};var In={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))"},Ho=t=>{var P,C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue;let{config:e,showClose:n=!0}=t,r=Et("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)))"}}),o=(P=e==null?void 0:e.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(L=o.closeButtonPlacement)!=null?L:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let oe=parseFloat(s)||24,se=fe(d,oe*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(R=(O=e==null?void 0:e.launcher)==null?void 0:O.agentIconText)!=null?R:"\u{1F4AC}"}else if(($=e==null?void 0:e.launcher)!=null&&$.iconUrl){let oe=y("img");oe.src=e.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(Z=(N=e==null?void 0:e.launcher)==null?void 0:N.agentIconText)!=null?Z:"\u{1F4AC}";let u=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Et("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Se=e==null?void 0:e.launcher)==null?void 0:Se.title)!=null?pe:"Chat Assistant",style:{color:In.titleColor}}),g=Et("span",{className:"persona-text-xs",text:(ve=(ee=e==null?void 0:e.launcher)==null?void 0:ee.subtitle)!=null?ve:"Here to help you get answers fast",style:{color:In.subtitleColor}});u.append(f,g),i?r.append(u):r.append(c,u);let m=(Ie=o.clearChat)!=null?Ie:{},x=(ce=m.enabled)!=null?ce:!0,v=(ue=m.placement)!=null?ue:"inline",M=null,W=null;if(x){let se=za(e,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=se.button,W=se.wrapper,v==="top-right"&&(W.style.right="48px"),v==="inline"&&r.appendChild(W)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="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:k,wrapper:E}=Ua(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:g,closeButton:k,closeButtonWrapper:E,clearChatButton:M,clearChatButtonWrapper:W}},Ys=(t,e,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function ds(t){let{items:e,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=t,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(po)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let M=fe(m.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let v=document.createElement("span");v.textContent=m.label,x.appendChild(v),x.addEventListener("click",M=>{M.stopPropagation(),u(),n(m.id)}),a.appendChild(x)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!a.contains(x.target)&&!r.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():u()}function g(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:f,destroy:g}}function An(t){let{icon:e,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=fe(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,f]of Object.entries(i))d.setAttribute(u,f);return d}function Oi(t){let{icon:e,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=y("button",c);if(u.type="button",u.setAttribute("aria-label",n),e){let g=fe(e,s!=null?s:14,"currentColor",2);g&&u.appendChild(g)}let f=y("span");if(f.textContent=n,u.appendChild(f),i&&u.addEventListener("click",i),d)for(let[g,m]of Object.entries(d))u.setAttribute(g,m);return u}function Zu(t){var m,x;let{label:e,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=y("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let f=fe(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,M;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(M=d.border)!=null?M:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=ds({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",v=>{v.stopPropagation();let M=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{u.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var yb=t=>{var r;let e=Ho({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=(r=t.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=e.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 e};function bb(t,e,n){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=y("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(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=fe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=ds({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),t.appendChild(i)}}var vb=t=>{var T,k,E,P,C,L,F,O,R;let{config:e,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=y("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 d=o==null?void 0:o.titleMenu,c,u;if(d)c=Zu({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=In.titleColor,u=(E=c.querySelector(".persona-combo-btn-label"))!=null?E:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=y("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=In.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(u),bb(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let N=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||N()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),N())})}let $=o==null?void 0:o.titleRowHover;$&&(c.style.borderRadius=(L=$.borderRadius)!=null?L:"10px",c.style.padding=(F=$.padding)!=null?F:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var N,Z;c.style.backgroundColor=(N=$.background)!=null?N:"",c.style.borderColor=(Z=$.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(O=a.closeButtonSize)!=null?O:"32px",g=y("div",""),m=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||In.actionIconColor;let x=(R=a.closeButtonIconName)!=null?R:"x",v=fe(x,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",r&&m.addEventListener("click",r),g.appendChild(m),i.appendChild(g);let M=y("div");M.style.display="none";let W=y("span");return W.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:W,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},em={default:yb,minimal:vb},xb=t=>{var e;return(e=em[t])!=null?e:em.default},qa=(t,e,n)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:t,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=y("div");u.style.display="none";let f=y("span"),g=y("span"),m=y("button");m.style.display="none";let x=y("div");return x.style.display="none",{header:c,iconHolder:u,headerTitle:f,headerSubtitle:g,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=xb(r)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ja=t=>{var a,i;let e=y("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.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",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;e.style.maxHeight=`${n*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Va=t=>{var P,C,L,F,O,R,$,N,Z,Se,pe,ee;let e=(P=t==null?void 0:t.sendButton)!=null?P:{},n=(C=e.useIcon)!=null?C:!1,r=(L=e.iconText)!=null?L:"\u2191",o=e.iconName,s=(F=e.stopIconName)!=null?F:"square",a=(O=e.tooltipText)!=null?O:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(N=($=t==null?void 0:t.copy)==null?void 0:$.sendButtonLabel)!=null?N:"Send",c=(Se=(Z=t==null?void 0:t.copy)==null?void 0:Z.stopButtonLabel)!=null?Se:"Stop",u=(pe=e.showTooltip)!=null?pe:!1,f=(ee=e.size)!=null?ee:"40px",g=e.backgroundColor,m=e.textColor,x=y("div","persona-send-button-wrapper"),v=Et("button",{className:Is("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&&!g&&"persona-bg-persona-primary",!n&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:n&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),M=null,W=null;if(n){let ve=parseFloat(f)||24,Ie=(m==null?void 0:m.trim())||"currentColor";o?(M=fe(o,ve,Ie,2),M?v.appendChild(M):v.textContent=r):v.textContent=r,W=fe(s,ve,Ie,2)}else v.textContent=d;let T=null;u&&a&&(T=y("div","persona-send-button-tooltip"),T.textContent=a,x.appendChild(T)),v.setAttribute("aria-label",a),x.appendChild(v);let k="send";return{button:v,wrapper:x,setMode:ve=>{if(ve===k)return;k=ve;let Ie=ve==="stop"?i:a;if(v.setAttribute("aria-label",Ie),T&&(T.textContent=Ie),n){if(M&&W){let ce=ve==="stop"?W:M;v.replaceChildren(ce)}}else v.textContent=ve==="stop"?c:d}}},Ka=t=>{var T,k,E,P,C,L,F,O,R,$,N,Z;let e=(T=t==null?void 0:t.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=e.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(E=t==null?void 0:t.sendButton)==null?void 0:E.size)!=null?P:"40px",i=(C=e.iconName)!=null?C:"mic",d=(L=e.iconSize)!=null?L:a,c=parseFloat(d)||24,u=(O=e.backgroundColor)!=null?O:(F=t==null?void 0:t.sendButton)==null?void 0:F.backgroundColor,f=($=e.iconColor)!=null?$:(R=t==null?void 0:t.sendButton)==null?void 0:R.textColor,g=y("div","persona-send-button-wrapper"),m=Et("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:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),v=fe(i,c,f||"currentColor",1.5);v?m.appendChild(v):m.textContent="\u{1F3A4}",g.appendChild(m);let M=(N=e.tooltipText)!=null?N:"Start voice recognition";if(((Z=e.showTooltip)!=null?Z:!1)&&M){let Se=y("div","persona-send-button-tooltip");Se.textContent=M,g.appendChild(Se)}return{button:m,wrapper:g}},Ga=t=>{var x,v,M,W,T,k,E,P;let e=(x=t==null?void 0:t.attachments)!=null?x:{};if(e.enabled!==!0)return null;let n=(M=(v=t==null?void 0:t.sendButton)==null?void 0:v.size)!=null?M:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((W=e.allowedTypes)!=null?W:qr).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=e.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),u=Et("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":(E=e.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let f=fe(s,d,"currentColor",1.5);f?u.appendChild(f):u.textContent="\u{1F4CE}",u.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(u);let g=(P=e.buttonTooltipText)!=null?P:"Attach file",m=y("div","persona-send-button-tooltip");return m.textContent=g,c.appendChild(m),{button:u,wrapper:c,input:o,previewsContainer:r}},Qa=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=y("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Xa=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ja=t=>{var x,v,M,W,T,k;let{config:e}=t,n=Et("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"}}),r=Xa(),o=Et("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:s,attachAutoResize:a}=ja(e);a();let i=Va(e),d=Ka(e),c=Ga(e),u=Qa(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(g,m),o.append(f),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,u),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:f,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var tm=()=>{let t=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=y("span","persona-pill-peek__icon"),n=fe("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=fe("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,r,o),{root:t,textNode:r}},nm=t=>{var x,v,M,W,T,k;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa();r.style.display="none";let o=Qa(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ja(e);s.style.maxHeight="100px",a();let i=Va(e),d=Ka(e),c=Ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),u.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(f,s,g),c&&n.append(c.previewsContainer),n.append(u,r,o);let m=u;return{footer:n,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:m,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var rm=t=>{var u,f,g,m,x,v,M,W,T,k,E,P,C,L,F,O,R;let e=(f=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?f:!0,n=yn(t);if(Js(t)){let $=(m=(g=t==null?void 0:t.launcher)==null?void 0:g.composerBar)!=null?m:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(x=$.expandedSize)!=null?x:"anchored",N.style.zIndex=String((M=(v=t==null?void 0:t.launcher)==null?void 0:v.zIndex)!=null?M:Cn);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",N.appendChild(Z);let Se=y("div","persona-widget-pill-root");return Se.setAttribute("data-persona-composer-bar",""),Se.dataset.state="collapsed",Se.dataset.expandedSize=(W=$.expandedSize)!=null?W:"anchored",Se.style.zIndex=String((k=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?k:Cn),{wrapper:N,panel:Z,pillRoot:Se}}if(n){let $=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return $.appendChild(N),{wrapper:$,panel:N}}if(!e){let $=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(E=t==null?void 0:t.launcher)==null?void 0:E.width)!=null?P:"100%";return $.style.width=Z,N.style.width="100%",$.appendChild(N),{wrapper:$,panel:N}}let o=(C=t==null?void 0:t.launcher)!=null?C:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(L=t==null?void 0:t.launcher)==null?void 0:L.zIndex)!=null?F:Cn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(O=t==null?void 0:t.launcher)==null?void 0:O.width)!=null?R:t==null?void 0:t.launcherWidth,c=d!=null?d:jr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},wb=(t,e)=>{var E,P,C,L,F,O,R,$,N;let n=y("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:r,wrapper:o}=Ua(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(P=(E=t==null?void 0:t.launcher)==null?void 0:E.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=za(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("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"}});c.style.setProperty("scrollbar-gutter","stable");let u=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(L=t==null?void 0:t.copy)==null?void 0:L.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),f=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(O=t==null?void 0:t.copy)==null?void 0:O.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),g=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,f),m=y("div","persona-flex persona-flex-col persona-gap-3"),x=($=t==null?void 0:t.layout)==null?void 0:$.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((N=t==null?void 0:t.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,m);let M=Et("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"}}),W=nm({config:t}),{root:T,textNode:k}=tm();return n.append(d,o,c,M),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:m,composerOverlay:M,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:u,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:T,peekTextNode:k}},om=(t,e=!0)=>{var M,W,T,k,E,P,C,L,F;if(Js(t))return wb(t,e);let n=Et("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"}}),r=(M=t==null?void 0:t.layout)==null?void 0:M.header,o=((W=t==null?void 0:t.layout)==null?void 0:W.showHeader)!==!1,s=r?qa(t,r,{showClose:e}):Ho({config:t,showClose:e}),a=Et("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=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),c=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:yn(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),u=y("div","persona-flex persona-flex-col persona-gap-3"),f=(C=t==null?void 0:t.layout)==null?void 0:C.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((L=t==null?void 0:t.copy)==null?void 0:L.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let m=Ja({config:t}),x=((F=t==null?void 0:t.layout)==null?void 0:F.showFooter)!==!1;o?Ys(n,s,t):(s.header.style.display="none",Ys(n,s,t)),n.append(a);let v=Et("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 x||(m.footer.style.display="none"),n.append(m.footer),n.append(v),{container:n,body:a,messagesWrapper:u,composerOverlay:v,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var _i=(t,e)=>{let n=y("button");n.type="button",n.innerHTML=`
20
20
  <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>
21
21
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
22
22
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -24,14 +24,14 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
24
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
25
25
  </span>
26
26
  <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>
27
- `,t.addEventListener("click",e);let r=s=>{var N,k,W,C,I,D,B,E,z,j,te,We,$e;let a=(N=s.launcher)!=null?N:{},i=mn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let ve=(k=a.title)!=null?k:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ve=(W=a.subtitle)!=null?W:"Here to help you get answers fast";c.textContent=ve,c.setAttribute("title",ve)}let m=t.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let ve=(C=a.agentIconSize)!=null?C:"40px";if(f.style.height=ve,f.style.width=ve,f.innerHTML="",a.agentIconName){let Pe=parseFloat(ve)||24,Oe=Ce(a.agentIconName,Pe*.6,"var(--persona-text-inverse, #ffffff)",2);Oe?(f.appendChild(Oe),f.style.display=""):(f.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(D=a.agentIconText)!=null?D:"\u{1F4AC}",f.style.display="")}let g=t.querySelector("[data-role='launcher-image']");if(g){let ve=(B=a.agentIconSize)!=null?B:"40px";g.style.height=ve,g.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=t.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let ve=(E=a.callToActionIconSize)!=null?E:"32px";u.style.height=ve,u.style.width=ve,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let Pe=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,Pe=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let Oe=parseFloat(ve)||24,Ae=Math.max(Oe-Pe,8),be=Ce(a.callToActionIconName,Ae,"currentColor",2);be?u.appendChild(be):u.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else u.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}let v=a.position&&gr[a.position]?gr[a.position]:gr["bottom-right"],x="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",P="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";t.className=i?P:`${x} ${v}`,i||(t.style.zIndex=String((te=a.zIndex)!=null?te:xn));let T="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(We=a.border)!=null?We:T,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:M,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=($e=a.collapsedMaxWidth)!=null?$e:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return n&&r(n),{element:t,update:r,destroy:o}};var tm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=Zu(n),s=em(n,e),a={wrapper:t,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},Fi=({config:n,plugins:e,onToggle:t})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>Ni(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=Ni(n,t);return{instance:o,element:o.element}};var mb=n=>{switch(n){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}},gb=(n,e)=>{if(!n)return null;let t=mb(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},fb=(n,e)=>{let t=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",n),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},hb=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},Oi=n=>{let e=n.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:")||!n.includes(":"))},_i=320,rm=320,yb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),bb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),vb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),xb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),wb=(n,e,t)=>{if(n.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return n.forEach((i,d)=>{var f;let c=b("img");c.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${_i}px`,c.style.maxHeight=`${rm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let m=!1;o+=1,c.addEventListener("error",()=>{m||(m=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{m=!0}),hb(i.image)?(c.src=i.image,r.appendChild(c)):(m=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},Cb=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!Oi(r.audio))return;let o=b("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${_i}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Ab=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!Oi(r.video))return;let o=b("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${_i}px`,o.style.maxHeight=`${rm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Sb=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!Oi(r.data))return;let o=b("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Gs=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(t),n.appendChild(r),n.appendChild(o),n},Tb=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:Gs};if(e){let o=e(r);if(o!==null)return o}return Gs()},Mb=(n,e)=>{let t=b("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"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},nm=(n,e,t="div")=>{let r=b(t,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Eb=(n,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.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 t},kb=(n,e,t)=>{var v,x,P,T,M,N,k;let r=(v=e.showCopy)!=null?v:!0,o=(x=e.showUpvote)!=null?x:!0,s=(P=e.showDownvote)!=null?P:!0,a=(T=e.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let W=b("div");return W.style.display="none",W.id=`actions-${n.id}`,W.setAttribute("data-actions-for",n.id),W}let i=(M=e.visibility)!=null?M:"hover",d=(N=e.align)!=null?N:"right",c=(k=e.layout)!=null?k:"pill-inside",m={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${m} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${n.id}`,g.setAttribute("data-actions-for",n.id);let u=(W,C,I)=>{let D=wn({icon:W,label:C,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",I),D};return r&&g.appendChild(u("copy","Copy message","copy")),a&&g.appendChild(u("volume-2","Read aloud","read-aloud")),o&&g.appendChild(u("thumbs-up","Upvote","upvote")),s&&g.appendChild(u("thumbs-down","Downvote","downvote")),g},$i=(n,e,t,r,o,s)=>{var ne,Q,ae,fe,re,V,ee,Ue,J,ie,Le,at,it,nt,Me,de,Qe;let a=t!=null?t:{},i=(ne=a.layout)!=null?ne:"bubble",d=a.avatar,c=a.timestamp,m=(Q=d==null?void 0:d.show)!=null?Q:!1,f=(ae=c==null?void 0:c.show)!=null?ae:!1,g=(fe=d==null?void 0:d.position)!=null?fe:"left",u=(re=c==null?void 0:c.position)!=null?re:"below",v=Eb(n.role,i),x=b("div",v.join(" "));x.id=`bubble-${n.id}`,x.setAttribute("data-message-id",n.id),x.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=yb(n),T=(ee=(V=n.content)==null?void 0:V.trim())!=null?ee:"",N=P.length>0&&T===Ca,k=Ba((J=(Ue=s==null?void 0:s.widgetConfig)==null?void 0:Ue.features)==null?void 0:J.streamAnimation),W=(at=(Le=(ie=s==null?void 0:s.widgetConfig)==null?void 0:ie.features)==null?void 0:Le.streamAnimation)==null?void 0:at.plugins,C=n.role==="assistant"&&k.type!=="none"?$s(k.type,W):null,I=n.role==="assistant"&&((it=C==null?void 0:C.isAnimating)==null?void 0:it.call(C,n))===!0,D=n.role==="assistant"&&C!==null&&(!!n.streaming||I);D&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let B=document.createElement("div");B.classList.add("persona-message-content"),n.streaming&&B.classList.add("persona-content-streaming"),D&&C&&(C.containerClass&&B.classList.add(C.containerClass),B.style.setProperty("--persona-stream-step",`${k.speed}ms`),B.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let E=D?Da((nt=n.content)!=null?nt:"",k.buffer,C,n,!!n.streaming):(Me=n.content)!=null?Me:"",z=e({text:E,message:n,streaming:!!n.streaming,raw:n.rawContent}),j=z;D&&(C==null?void 0:C.wrap)==="char"?j=Us(z,"char",n.id,{skipTags:C.skipTags}):D&&(C==null?void 0:C.wrap)==="word"&&(j=Us(z,"word",n.id,{skipTags:C.skipTags}));let te=null;if(N?(te=document.createElement("div"),te.innerHTML=j,te.style.display="none",B.appendChild(te)):B.innerHTML=j,D&&(C!=null&&C.useCaret)&&!N&&T){let X=Na(),le=B.querySelectorAll(".persona-stream-char, .persona-stream-word"),xe=le[le.length-1];if(xe!=null&&xe.parentNode)xe.parentNode.insertBefore(X,xe.nextSibling);else{let ze=B.lastElementChild;ze?ze.appendChild(X):B.appendChild(X)}}if(f&&u==="inline"&&n.createdAt){let X=nm(n,c,"span");X.classList.add("persona-timestamp-inline");let le=B.lastElementChild;le?le.appendChild(X):B.appendChild(X)}if(P.length>0){let X=wb(P,!N&&!!T,()=>{N&&te&&(te.style.display="")});X?x.appendChild(X):N&&te&&(te.style.display="")}let We=bb(n);if(We.length>0){let X=Cb(We);X&&x.appendChild(X)}let $e=vb(n);if($e.length>0){let X=Ab($e);X&&x.appendChild(X)}let ve=xb(n);if(ve.length>0){let X=Sb(ve);X&&x.appendChild(X)}if(x.appendChild(B),f&&u==="below"&&n.createdAt){let X=nm(n,c);X.classList.add("persona-mt-1"),x.appendChild(X)}let Pe=n.role==="assistant"?gb(n.stopReason,(Qe=(de=s==null?void 0:s.widgetConfig)==null?void 0:de.copy)==null?void 0:Qe.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let X=!!(E&&E.trim()),le=k.placeholder==="skeleton",xe=le&&k.buffer==="line"&&X;if(X)xe&&x.appendChild(qs());else if(le)x.appendChild(qs());else{let ze=Tb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);ze&&x.appendChild(ze)}}if(Pe&&n.stopReason&&!n.streaming&&(T||(B.style.display="none"),x.appendChild(fb(n.stopReason,Pe))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=kb(n,r,o);x.appendChild(X)}if(!m||n.role==="system")return x;let Ae=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),be=Mb(d,n.role);return g==="right"||g==="left"&&n.role==="user"?Ae.append(x,be):Ae.append(be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ae};var is=new Set,Lb=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Pb=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
28
- `):""},om=(n,e)=>{let t=is.has(n),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=Ce(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},Ui=(n,e)=>{var $e,ve,Pe,Oe,Ae,be,ne,Q,ae,fe,re;let t=n.reasoning,r=b("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(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let o=(ve=($e=e==null?void 0:e.features)==null?void 0:$e.reasoningDisplay)!=null?ve:{},s=o.expandable!==!1,a=s&&is.has(n.id),i=t.status!=="complete",d=Pb(n,(Pe=o.previewMaxLines)!=null?Pe:3),c=b("button",s?"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");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let m=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(Oe=e==null?void 0:e.reasoning)!=null?Oe:{},v=String((Ae=t.startedAt)!=null?Ae:Date.now()),x=()=>{let V=b("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=ba(t),V},P=(be=u.renderCollapsedSummary)==null?void 0:be.call(u,{message:n,reasoning:t,defaultSummary:g,previewText:d,isActive:i,config:e!=null?e:{},elapsed:ba(t),createElapsedElement:x});typeof P=="string"&&P.trim()?(f.textContent=P,m.appendChild(f)):P instanceof HTMLElement?m.appendChild(P):(f.textContent=g,m.appendChild(f));let T=b("span","persona-text-xs persona-text-persona-primary");T.textContent=ou(t),m.appendChild(T);let M=(ne=o.loadingAnimation)!=null?ne:"none",N=u.activeTextTemplate,k=u.completeTextTemplate,W=i?N:k,C=P instanceof HTMLElement,I=(V,ee,Ue)=>{let J=Ue;for(let ie of ee){let Le=b("span","persona-tool-char");Le.style.setProperty("--char-index",String(J)),Le.textContent=ie===" "?"\xA0":ie,V.appendChild(Le),J++}return J},D=(V,ee)=>{f.textContent="";let Ue=va(V,""),J=0;for(let ie of Ue){let Le=ie.styles.length>0?(()=>{let at=b("span",ie.styles.map(it=>`persona-tool-text-${it}`).join(" "));return f.appendChild(at),at})():f;if(ie.isDuration&&i)Le.appendChild(x());else{let at=ie.isDuration?ba(t):ie.text;ee?J=I(Le,at,J):Le.appendChild(document.createTextNode(at))}}};if(!C&&W)if(T.style.display="none",f.style.display="",i&&M!=="none"){let V=(Q=u.loadingAnimationDuration)!=null?Q:2e3;f.setAttribute("data-preserve-animation","true"),M==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),D(W,!1)):(f.classList.add(`persona-tool-loading-${M}`),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),M==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),D(W,!0))}else D(W,!1);else if(!C&&i&&M!=="none"){f.style.display="";let V=(ae=u.loadingAnimationDuration)!=null?ae:2e3;if(f.setAttribute("data-preserve-animation","true"),M==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{f.classList.add(`persona-tool-loading-${M}`),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),M==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let ee=f.textContent||g;f.textContent="",I(f,ee,0)}t.status==="complete"&&(f.style.display="none")}else C||(t.status==="complete"?f.style.display="none":f.style.display="");let B=null;if(s){B=b("div","persona-flex persona-items-center");let ee=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);ee?B.appendChild(ee):B.textContent=a?"Hide":"Show";let Ue=b("div","persona-flex persona-items-center persona-ml-auto");Ue.append(B),c.append(m,Ue)}else c.append(m);let E=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(E.setAttribute("data-persona-collapsed-preview","reasoning"),E.style.display="none",E.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(re=(fe=e==null?void 0:e.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:re.call(fe,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});Lb(E,V)||(E.textContent=d),E.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,E),r;let z=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");z.style.display=a?"":"none";let j=t.chunks.join(""),te=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return te.textContent=j||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),z.appendChild(te),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),B){B.innerHTML="";let ee=Ce(a?"chevron-up":"chevron-down",16,"currentColor",2);ee?B.appendChild(ee):B.textContent=a?"Hide":"Show"}z.style.display=a?"":"none",E.style.display=a?"none":E.textContent||E.childNodes.length?"":"none"})(),r.append(c,E,z),r};var ls=new Set,Ib=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Wb=(n,e)=>{var s;let t=n.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
29
- `);let o=es(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
30
- `):""},qi=(n,e)=>{var t,r,o;n.style.backgroundColor=(t=e.codeBlockBackgroundColor)!=null?t:"var(--persona-container, #f3f4f6)",n.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",n.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Rb=(n,e)=>{var m,f,g,u,v;let t=n.toolCall,r=(m=e==null?void 0:e.features)==null?void 0:m.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=Wb(n,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?su(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(u=e==null?void 0:e.toolCall)!=null?u:{},c=a;return o==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Ai(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Ai(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},sm=(n,e,t)=>{var m;let r=ls.has(n),o=(m=t==null?void 0:t.toolCall)!=null?m:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=Ce(r?"chevron-up":"chevron-down",16,f,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},zi=(n,e)=>{var j,te,We,$e,ve,Pe,Oe,Ae,be;let t=n.toolCall,r=(j=e==null?void 0:e.toolCall)!=null?j:{},o=b("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(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let s=(We=(te=e==null?void 0:e.features)==null?void 0:te.toolCallDisplay)!=null?We:{},a=s.expandable!==!1,i=a&&ls.has(n.id),{summary:d,previewText:c,isActive:m}=Rb(n,e),f=b("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");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String(($e=t.startedAt)!=null?$e:Date.now()),x=()=>{let ne=b("span","");return ne.setAttribute("data-tool-elapsed",v),ne.textContent=Ps(t),ne},P=(Pe=r.renderCollapsedSummary)==null?void 0:Pe.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(ve=s.collapsedMode)!=null?ve:"tool-call",isActive:m,config:e!=null?e:{},elapsed:Ps(t),createElapsedElement:x});typeof P=="string"&&P.trim()?(u.textContent=P,g.appendChild(u)):P instanceof HTMLElement?g.appendChild(P):(u.textContent=d,g.appendChild(u));let T=(Oe=s.loadingAnimation)!=null?Oe:"none",M=r.activeTextTemplate,N=r.completeTextTemplate,k=m?M:N,W=P instanceof HTMLElement,C=(ne,Q,ae)=>{let fe=ae;for(let re of Q){let V=b("span","persona-tool-char");V.style.setProperty("--char-index",String(fe)),V.textContent=re===" "?"\xA0":re,ne.appendChild(V),fe++}return fe},I=(ne,Q)=>{var V;u.textContent="";let ae=((V=t.name)==null?void 0:V.trim())||"tool",fe=va(ne,ae),re=0;for(let ee of fe){let Ue=ee.styles.length>0?(()=>{let J=b("span",ee.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return u.appendChild(J),J})():u;if(ee.isDuration&&m)Ue.appendChild(x());else{let J=ee.isDuration?Ps(t):ee.text;Q?re=C(Ue,J,re):Ue.appendChild(document.createTextNode(J))}}};if(!W)if(m&&T!=="none"){let ne=(Ae=r.loadingAnimationDuration)!=null?Ae:2e3;if(u.setAttribute("data-preserve-animation","true"),T==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),k&&I(k,!1);else if(u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),k)I(k,!0);else{let Q=u.textContent||d;u.textContent="",C(u,Q,0)}}else k&&I(k,!1);let D=null;if(a){D=b("div","persona-flex persona-items-center");let ne=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",Q=Ce(i?"chevron-up":"chevron-down",16,ne,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show";let ae=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(D),f.append(g,ae)}else f.append(g);let B=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","tool"),B.style.display="none",B.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&c){let ne=(be=r.renderCollapsedPreview)==null?void 0:be.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:m,config:e!=null?e:{}});Ib(B,ne)||(B.textContent=c),B.style.display=""}if(!i&&m&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,B),o;let E=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(E.style.display=i?"":"none",r.contentBackgroundColor&&(E.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(E.style.color=r.contentTextColor),r.contentPaddingX&&(E.style.paddingLeft=r.contentPaddingX,E.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(E.style.paddingTop=r.contentPaddingY,E.style.paddingBottom=r.contentPaddingY),t.name){let ne=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ne.style.color=r.contentTextColor:r.headerTextColor&&(ne.style.color=r.headerTextColor),ne.textContent=t.name,E.appendChild(ne)}if(t.args!==void 0){let ne=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let ae=b("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",qi(ae,r),ae.textContent=es(t.args),ne.append(Q,ae),E.appendChild(ne)}if(t.chunks&&t.chunks.length){let ne=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let ae=b("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",qi(ae,r),ae.textContent=t.chunks.join(""),ne.append(Q,ae),E.appendChild(ne)}if(t.status==="complete"&&t.result!==void 0){let ne=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let ae=b("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",qi(ae,r),ae.textContent=es(t.result),ne.append(Q,ae),E.appendChild(ne)}if(t.status==="complete"&&typeof t.duration=="number"){let ne=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ne.style.color=r.contentTextColor),ne.textContent=`Duration: ${t.duration}ms`,E.appendChild(ne)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),D){D.innerHTML="";let ne=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",Q=Ce(i?"chevron-up":"chevron-down",16,ne,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show"}E.style.display=i?"":"none",B.style.display=i?"none":B.textContent||B.childNodes.length?"":"none"})(),o.append(f,B,E),o};var Ga=new Map,Hb=n=>{let t=(n.startsWith(Mo)?n.slice(Mo.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return n;let r=t.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},am=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,im=(n,e)=>{var r,o,s;let t=(o=(r=am(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ga.get(n))!=null?s:t==="expanded"},lm=(n,e,t)=>{var a,i;let r=am(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ce(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},cm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=im(n,t);lm(r,s,t),o.style.display=s?"":"none"};var Qa=(n,e)=>{var I,D,B,E,z,j,te,We,$e,ve,Pe,Oe,Ae,be,ne;let t=n.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(D=r==null?void 0:r.borderColor)!=null?D:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(B=r==null?void 0:r.titleColor)!=null?B:"currentColor",m=Ce(d,20,c,2);m&&i.appendChild(m);let f=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(E=r==null?void 0:r.title)!=null?E:"Approval Required",g.appendChild(u),!o){let Q=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",t.status),t.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):t.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):t.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),g.appendChild(Q)}f.appendChild(g);let x=t.toolType==="webmcp"||t.toolName.startsWith(Mo)?ui(t.toolName):void 0,P=(z=r==null?void 0:r.formatDescription)==null?void 0:z.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),T=!t.toolName,M=P||(T?t.description:`The assistant wants to use \u201C${x!=null?x:Hb(t.toolName)}\u201D.`),N=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(N.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(N.style.color=r.descriptionColor),N.textContent=M,f.appendChild(N),t.reason){let Q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let ae=b("span","persona-font-medium");ae.textContent=`${(j=r==null?void 0:r.reasonLabel)!=null?j:"Agent's stated reason:"} `,Q.appendChild(ae),Q.appendChild(document.createTextNode(t.reason)),f.appendChild(Q)}let k=(te=r==null?void 0:r.detailsDisplay)!=null?te:"collapsed",W=!!t.description&&!T,C=W||!!t.parameters;if(k!=="hidden"&&C){let Q=im(n.id,e),ae=b("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");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let fe=b("span");fe.setAttribute("data-approval-details-label","true");let re=b("span","persona-inline-flex persona-items-center");re.setAttribute("data-approval-details-chevron","true"),ae.append(fe,re),lm(ae,Q,e),f.appendChild(ae);let V=b("div");if(V.setAttribute("data-approval-details","true"),V.style.display=Q?"":"none",W){let ee=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=t.description,V.appendChild(ee)}if(t.parameters){let ee=b("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");r!=null&&r.parameterBackgroundColor&&(ee.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.style.fontSize="0.75rem",ee.style.lineHeight="1rem",ee.textContent=es(t.parameters),V.appendChild(ee)}f.appendChild(V)}if(o){let Q=b("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let ae=b("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");ae.type="button",ae.style.backgroundColor=(We=r==null?void 0:r.approveButtonColor)!=null?We:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=($e=r==null?void 0:r.approveButtonTextColor)!=null?$e:"#ffffff",ae.setAttribute("data-approval-action","approve");let fe=Ce("shield-check",14,(ve=r==null?void 0:r.approveButtonTextColor)!=null?ve:"#ffffff",2);fe&&(fe.style.marginRight="4px",ae.appendChild(fe));let re=document.createTextNode((Pe=r==null?void 0:r.approveLabel)!=null?Pe:"Approve");ae.appendChild(re);let V=b("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");V.type="button",V.style.backgroundColor=(Oe=r==null?void 0:r.denyButtonColor)!=null?Oe:"transparent",V.style.color=(Ae=r==null?void 0:r.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let ee=Ce("shield-x",14,(be=r==null?void 0:r.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",V.appendChild(ee));let Ue=document.createTextNode((ne=r==null?void 0:r.denyLabel)!=null?ne:"Deny");V.appendChild(Ue),Q.append(ae,V),f.appendChild(Q)}return a.append(i,f),s.appendChild(a),s};var dm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let m=(c==null?void 0:c.agentPushed)===!0;if(m||(t=null),!o||!o.length||!m&&(i!=null?i:s?s.getMessages():[]).some(P=>P.role==="user"))return;let f=document.createDocumentFragment(),g=s?s.isStreaming():!1,u=v=>{switch(v){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(o.forEach(v=>{let x=b("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");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=u(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",m&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),e.push(x)}),n.appendChild(f),m){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Qs=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var Bb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Db=new Set(["step_start","execution_start"]),Nb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Fb=new Set(["step_complete","agent_turn_complete"]),Ob=new Set(["flow_complete","agent_complete"]),pm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),mm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Qn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Ro=(n,e)=>{let t=n[e];return mm(t)?t:void 0};function ji(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function Xa(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function _b(n,e){return typeof e.type=="string"?e.type:n}function $b(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function Ub(n,e){return n==="step_delta"||n==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function um(n){var r,o,s,a,i;let e=Ro(n,"result"),t=[Ro(n,"tokens"),Ro(n,"totalTokens"),e?Ro(e,"tokens"):void 0,Ro(n,"usage"),e?Ro(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?o:Qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Qn(n.outputTokens))!=null?s:Qn(n.completionTokens))!=null?i:e?(a=Qn(e.outputTokens))!=null?a:Qn(e.completionTokens):void 0}function qb(n){var t,r,o,s,a;let e=Ro(n,"result");return(a=(o=(r=(t=Qn(n.executionTime))!=null?t:Qn(n.executionTimeMs))!=null?r:Qn(n.execution_time))!=null?o:Qn(n.duration))!=null?a:e?(s=Qn(e.executionTime))!=null?s:Qn(e.executionTimeMs):void 0}function zb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Js=class{constructor(e=zb){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:Xa(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var s;if(!mm(t)){pm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=_b(e,t),o=this.now();if(Bb.has(r)){this.startRun(o);return}if(Db.has(r)){this.run||this.startRun(o);return}if(Nb.has(r)){if(!Ub(r,t))return;let a=$b(t);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+ji(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Xa(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Fb.has(r)){if(!this.run)return;let a=this.run,i=um(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+ji(a.visibleCharCount),m=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:Xa(c,m),outputTokens:c,durationMs:m,source:d?"usage":"estimate"};return}if(Ob.has(r)){if(!this.run)return;let a=this.run,i=um(t),d=i!=null?i:a.exactOutputTokens+ji(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:Xa(d,m),outputTokens:d,durationMs:m,source:c},this.run=null;return}if(pm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=qb(t);return s!=null?s:r-e.startedAt}};function cs(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var jb={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)"}},Vb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Kb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Gb=100;function Qb(n,e){let t={...jb,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Vb}function Xb(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function Jb(n){let e=new Date(n),t=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function Yb(n,e){try{let t=JSON.parse(n);if(typeof t!="object"||t===null)return null;for(let r of e){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Zb(n){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(n):new Promise(t=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function ev(n){let e;try{e=JSON.parse(n.payload)}catch{e=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:e},null,2)}function tv(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function nv(n){let e=[];return n.outputTokens!==void 0&&e.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&e.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&e.push(n.source),e.join(" \xB7 ")}function rv(n,e,t){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=b("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]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Vi(n,e,t,r,o,s,a,i){var g;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");cs(c,(g=r.classNames)==null?void 0:g.eventRow);let m=a.find(u=>u.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let u=m.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(u)return c.appendChild(u),c}return c.appendChild(f()),c;function f(){var j,te;let u=b("div",""),v=b("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");v.setAttribute("data-event-id",n.id);let x=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),P=Ce(d?"chevron-down":"chevron-right","14px","currentColor",2);P&&x.appendChild(P);let T=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(j=r.timestampFormat)!=null?j:"relative";T.textContent=M==="relative"?Xb(n.timestamp,t):Jb(n.timestamp);let N=null;r.showSequenceNumbers!==!1&&(N=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),N.textContent=String(e+1));let k=Qb(n.type,r.badgeColors),W=b("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");W.style.backgroundColor=k.bg,W.style.color=k.text,W.style.borderColor=k.text+"50",W.textContent=n.type;let C=(te=r.descriptionFields)!=null?te:Kb,I=Yb(n.payload,C),D=null;I&&(D=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),D.textContent=I);let B=b("div","persona-flex-1 persona-min-w-0"),E=b("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"),z=Ce("clipboard","12px","currentColor",1.5);return z&&E.appendChild(z),E.addEventListener("click",async We=>{We.stopPropagation(),await Zb(ev(n)),E.innerHTML="";let $e=Ce("check","12px","currentColor",1.5);$e&&E.appendChild($e),setTimeout(()=>{E.innerHTML="";let ve=Ce("clipboard","12px","currentColor",1.5);ve&&E.appendChild(ve)},1500)}),v.appendChild(x),v.appendChild(T),N&&v.appendChild(N),v.appendChild(W),D&&v.appendChild(D),v.appendChild(B),v.appendChild(E),u.appendChild(v),d&&u.appendChild(rv(n,a,i)),u}}function gm(n){var v,x,P,T,M;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",m=(P=i==null?void 0:i.label)!=null?P:"",f=(M=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?M:{},g=s.find(N=>N.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let N=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>u().element,onClose:r});if(N)return{element:N,update:()=>{},destroy:()=>{}}}return u();function u(){let N=f.classNames,k=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");cs(k,N==null?void 0:N.panel);let W=[],C="",I="",D=null,B=[],E={},z=0,j=Wa(),te=0,We=0,$e=!1,ve=null,Pe=!1,Oe=0,Ae=new Set,be=new Map,ne="",Q="",ae=null,fe,re,V,ee,Ue,J=null,ie=null,Le=null;function at(){let K=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ce=b("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");cs(ce,N==null?void 0:N.headerBar);let Ee=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ee.textContent="Events",fe=b("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"),fe.textContent="0",a){ie=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ie.style.cursor="help";let Xn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Xn.textContent="Throughput",J=b("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"),J.textContent="-- tok/s",Le=b("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"),Le.style.display="none",Le.style.pointerEvents="none";let Cn=ie,Zt=Le,Pn=()=>{if(!Zt.textContent)return;let vt=Cn.getBoundingClientRect(),Dn=K.getBoundingClientRect();Zt.style.left=`${vt.left-Dn.left}px`,Zt.style.top=`${vt.bottom-Dn.top+4}px`,Zt.style.display="block"},hr=()=>{Zt.style.display="none"};ie.addEventListener("mouseenter",Pn),ie.addEventListener("mouseleave",hr),ie.appendChild(Xn),ie.appendChild(J)}let bt=b("div","persona-flex-1");re=b("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 Jt=b("option","");Jt.value="",Jt.textContent="All events",re.appendChild(Jt),V=b("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"),V.type="button",V.title="Copy All";let dn=Ce("clipboard-copy","12px","currentColor",1.5);dn&&V.appendChild(dn);let Rt=b("span","persona-text-xs");Rt.textContent="Copy All",V.appendChild(Rt),ce.appendChild(Ee),ce.appendChild(fe),ie&&ce.appendChild(ie),ce.appendChild(bt),ce.appendChild(re),ce.appendChild(V);let Ze=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");cs(Ze,N==null?void 0:N.searchBar);let Wt=Ce("search","14px","var(--persona-muted, #9ca3af)",1.5),lt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Wt&&lt.appendChild(Wt),ee=b("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"),cs(ee,N==null?void 0:N.searchInput),ee.type="text",ee.placeholder="Search event payloads...",Ue=b("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"),Ue.type="button",Ue.style.display="none";let Vt=Ce("x","12px","currentColor",2);return Vt&&Ue.appendChild(Vt),Ze.appendChild(lt),Ze.appendChild(ee),Ze.appendChild(Ue),K.appendChild(ce),K.appendChild(Ze),Le&&K.appendChild(Le),K}let it,nt=s.find(K=>K.renderEventStreamToolbar);if(nt!=null&&nt.renderEventStreamToolbar&&o){let K=nt.renderEventStreamToolbar({config:o,defaultRenderer:()=>at(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ce=>{C=ce,Pt(),fn()},onSearchChange:ce=>{I=ce,Pt(),fn()}});it=K!=null?K:at()}else it=at();let Me=b("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");Me.style.display="none";function de(){if(!a||!J||!ie)return;let K=a();J.textContent=tv(K);let ce=nv(K);Le&&(Le.textContent=ce,ce||(Le.style.display="none")),ce?ie.setAttribute("aria-label",ce):ie.removeAttribute("aria-label")}let Qe=b("div","persona-flex-1 persona-min-h-0 persona-relative"),X=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let le=b("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");cs(le,N==null?void 0:N.scrollIndicator),le.style.display="none",le.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let xe=Ce(c,"14px","currentColor",2);xe&&le.appendChild(xe);let ze=b("span","");ze.textContent=m,le.appendChild(ze);let Lt=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Lt.style.display="none",Qe.appendChild(X),Qe.appendChild(Lt),Qe.appendChild(le),k.setAttribute("tabindex","0"),k.appendChild(it),k.appendChild(Me),k.appendChild(Qe);function Se(){let K=e.getAll(),ce={};for(let Rt of K)ce[Rt.type]=(ce[Rt.type]||0)+1;let Ee=Object.keys(ce).sort(),bt=Ee.length!==B.length||!Ee.every((Rt,Ze)=>Rt===B[Ze]),Jt=!bt&&Ee.some(Rt=>ce[Rt]!==E[Rt]),Yt=K.length!==Object.values(E).reduce((Rt,Ze)=>Rt+Ze,0);if(!bt&&!Jt&&!Yt||(B=Ee,E=ce,!re))return;let dn=re.value;if(re.options[0].textContent="All events",bt){for(;re.options.length>1;)re.remove(1);for(let Rt of Ee){let Ze=b("option","");Ze.value=Rt,Ze.textContent=`${Rt} (${ce[Rt]||0})`,re.appendChild(Ze)}dn&&Ee.includes(dn)?re.value=dn:dn&&(re.value="",C="")}else for(let Rt=1;Rt<re.options.length;Rt++){let Ze=re.options[Rt];Ze.textContent=`${Ze.value} (${ce[Ze.value]||0})`}}function ue(){let K=e.getAll();if(C&&(K=K.filter(ce=>ce.type===C)),I){let ce=I.toLowerCase();K=K.filter(Ee=>Ee.type.toLowerCase().includes(ce)||Ee.payload.toLowerCase().includes(ce))}return K}function gn(){return C!==""||I!==""}function Pt(){z=0,te=0,j.resume(),le.style.display="none"}function nn(K){Ae.has(K)?Ae.delete(K):Ae.add(K),ae=K;let ce=X.scrollTop,Ee=j.isFollowing();Pe=!0,j.pause(),fn(),X.scrollTop=ce,Ee&&j.resume(),Pe=!1}function fr(){return Io(X,50)}function fn(){We=Date.now(),$e=!1,de(),Se();let K=e.getEvictedCount();K>0?(Me.textContent=`${K.toLocaleString()} older events truncated`,Me.style.display=""):Me.style.display="none",W=ue();let ce=W.length,Ee=e.getSize()>0;fe&&(fe.textContent=String(e.getSize())),ce===0&&Ee&&gn()?(Lt.textContent=I?`No events matching '${I}'`:"No events matching filter",Lt.style.display="",X.style.display="none"):(Lt.style.display="none",X.style.display=""),V&&(V.title=gn()?`Copy Filtered (${ce})`:"Copy All"),d&&!j.isFollowing()&&ce>z&&(te+=ce-z,ze.textContent=m?`${m}${te>0?` (${te})`:""}`:"",le.style.display=""),z=ce;let bt=e.getAll(),Jt=bt.length>0?bt[0].timestamp:0,Yt=new Set(W.map(Ze=>Ze.id));for(let Ze of Ae)Yt.has(Ze)||Ae.delete(Ze);let dn=C!==ne||I!==Q,Rt=be.size===0&&W.length>0;if(dn||Rt||W.length===0){X.innerHTML="",be.clear();let Ze=document.createDocumentFragment();for(let Wt=0;Wt<W.length;Wt++){let lt=Vi(W[Wt],Wt,Jt,f,Ae,nn,s,o);be.set(W[Wt].id,lt),Ze.appendChild(lt)}X.appendChild(Ze),ne=C,Q=I,ae=null}else{if(ae!==null){let Wt=be.get(ae);if(Wt&&Wt.parentNode===X){let lt=W.findIndex(Vt=>Vt.id===ae);if(lt>=0){let Vt=Vi(W[lt],lt,Jt,f,Ae,nn,s,o);X.insertBefore(Vt,Wt),Wt.remove(),be.set(ae,Vt)}}ae=null}let Ze=new Set(W.map(Wt=>Wt.id));for(let[Wt,lt]of be)Ze.has(Wt)||(lt.remove(),be.delete(Wt));for(let Wt=0;Wt<W.length;Wt++){let lt=W[Wt];if(!be.has(lt.id)){let Vt=Vi(lt,Wt,Jt,f,Ae,nn,s,o);be.set(lt.id,Vt),X.appendChild(Vt)}}}j.isFollowing()&&(X.scrollTop=X.scrollHeight)}function je(){if(Date.now()-We>=Gb){ve!==null&&(cancelAnimationFrame(ve),ve=null),fn();return}$e||($e=!0,ve=requestAnimationFrame(()=>{ve=null,fn()}))}let S=(K,ce)=>{if(!V)return;V.innerHTML="";let Ee=Ce(K,"12px","currentColor",1.5);Ee&&V.appendChild(Ee);let bt=b("span","persona-text-xs");bt.textContent="Copy All",V.appendChild(bt),setTimeout(()=>{V.innerHTML="";let Jt=Ce("clipboard-copy","12px","currentColor",1.5);Jt&&V.appendChild(Jt);let Yt=b("span","persona-text-xs");Yt.textContent="Copy All",V.appendChild(Yt),V.disabled=!1},ce)},pe=async()=>{if(V){V.disabled=!0;try{let K;gn()?K=W:t?(K=await t(),K.length===0&&(K=e.getAll())):K=e.getAll();let ce=K.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(ce,null,2)),S("check",1500)}catch{S("x",1500)}}},ke=()=>{re&&(C=re.value,Pt(),fn())},Te=()=>{!ee||!Ue||(Ue.style.display=ee.value?"":"none",D&&clearTimeout(D),D=setTimeout(()=>{I=ee.value,Pt(),fn()},150))},Re=()=>{!ee||!Ue||(ee.value="",I="",Ue.style.display="none",D&&clearTimeout(D),Pt(),fn())},Ye=()=>{if(Pe)return;let K=X.scrollTop,{action:ce,nextLastScrollTop:Ee}=Ra({following:j.isFollowing(),currentScrollTop:K,lastScrollTop:Oe,nearBottom:fr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Oe=Ee,ce==="resume"?(j.resume(),te=0,le.style.display="none"):ce==="pause"&&(j.pause(),d&&(ze.textContent=m,le.style.display=""))},Ke=K=>{let ce=Ha({following:j.isFollowing(),deltaY:K.deltaY,nearBottom:fr(),resumeWhenNearBottom:!0});ce==="pause"?(j.pause(),d&&(ze.textContent=m,le.style.display="")):ce==="resume"&&(j.resume(),te=0,le.style.display="none")},pt=()=>{d&&(X.scrollTop=X.scrollHeight,j.resume(),te=0,le.style.display="none")},It=K=>{let ce=K.target;if(!ce||ce.closest("button"))return;let Ee=ce.closest("[data-event-id]");if(!Ee)return;let bt=Ee.getAttribute("data-event-id");bt&&nn(bt)},U=K=>{if((K.metaKey||K.ctrlKey)&&K.key==="f"){K.preventDefault(),ee==null||ee.focus(),ee==null||ee.select();return}K.key==="Escape"&&(ee&&document.activeElement===ee?(Re(),ee.blur(),k.focus()):r&&r())};V&&V.addEventListener("click",pe),re&&re.addEventListener("change",ke),ee&&ee.addEventListener("input",Te),Ue&&Ue.addEventListener("click",Re),X.addEventListener("scroll",Ye),X.addEventListener("wheel",Ke,{passive:!0}),X.addEventListener("click",It),le.addEventListener("click",pt),k.addEventListener("keydown",U);function rt(){D&&clearTimeout(D),ve!==null&&(cancelAnimationFrame(ve),ve=null),$e=!1,be.clear(),V&&V.removeEventListener("click",pe),re&&re.removeEventListener("change",ke),ee&&ee.removeEventListener("input",Te),Ue&&Ue.removeEventListener("click",Re),X.removeEventListener("scroll",Ye),X.removeEventListener("wheel",Ke),X.removeEventListener("click",It),le.removeEventListener("click",pt),k.removeEventListener("keydown",U)}return{element:k,update:je,destroy:rt}}}function fm(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=t;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)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(u)}else f.textContent=a;if(c.append(m,f),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${t}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var hm=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",m=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>fm(n,e)});if(m)return m}return fm(n,e)};var Ki=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,r])=>{this.register(t,r)})}},Ho=new Ki;Ho.register("PersonaArtifactCard",hm);function ov(n){var o;let e=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=b("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(r),e}function ym(n,e){var re,V,ee,Ue;let t=(V=(re=n.features)==null?void 0:re.artifacts)==null?void 0:V.layout,o=((ee=t==null?void 0:t.toolbarPreset)!=null?ee:"default")==="document",s=(Ue=t==null?void 0:t.panePadding)==null?void 0:Ue.trim(),a=n.markdown?da(n.markdown):null,i=pa(n.sanitize),d=J=>{let ie=a?a(J):oo(J);return i?i(ie):ie},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var J;m(),(J=e.onDismiss)==null||J.call(e)});let f=b("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");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let g=b("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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var J;m(),(J=e.onDismiss)==null||J.call(e)});let x="rendered",P=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?wn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):wn({icon:"eye",label:"Rendered view"}),M=o?wn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):wn({icon:"code-2",label:"Source"}),N=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),k=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,W=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,C=t==null?void 0:t.documentToolbarCopyMenuItems,I=!!(W&&C&&C.length>0),D=null,B,E=null,z=null;if(o&&(k||W)&&!I){if(B=k?Di({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let J=Ce("chevron-down",14,"currentColor",2);J&&B.appendChild(J)}}else o&&I?(D=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),B=k?Di({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=wn({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"}}),D.append(B,E)):o?B=wn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):B=wn({icon:"copy",label:"Copy"});let j=o?wn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):wn({icon:"refresh-cw",label:"Refresh"}),te=o?wn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):wn({icon:"x",label:"Close"}),We=()=>{var it,nt,Me;let J=(it=be.find(de=>de.id===ne))!=null?it:be[be.length-1],ie=(nt=J==null?void 0:J.id)!=null?nt:null,Le=(J==null?void 0:J.artifactType)==="markdown"&&(Me=J.markdown)!=null?Me:"",at=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Le,jsonPayload:at,id:ie}},$e=async()=>{var it;let{markdown:J,jsonPayload:ie}=We(),Le=(it=be.find(nt=>nt.id===ne))!=null?it:be[be.length-1],at=(Le==null?void 0:Le.artifactType)==="markdown"?J:Le?ie:"";try{await navigator.clipboard.writeText(at)}catch{}};if(B.addEventListener("click",async()=>{let J=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(J&&I){let{markdown:ie,jsonPayload:Le,id:at}=We();try{await J({actionId:"primary",artifactId:at,markdown:ie,jsonPayload:Le})}catch{}return}await $e()}),E&&(C!=null&&C.length)){let J=()=>{var Le;return(Le=f.closest("[data-persona-root]"))!=null?Le:document.body},ie=()=>{z=as({items:C.map(Le=>({id:Le.id,label:Le.label})),onSelect:async Le=>{let{markdown:at,jsonPayload:it,id:nt}=We(),Me=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Me?await Me({actionId:Le,artifactId:nt,markdown:at,jsonPayload:it}):Le==="markdown"||Le==="md"?await navigator.clipboard.writeText(at):Le==="json"||Le==="source"?await navigator.clipboard.writeText(it):await navigator.clipboard.writeText(at||it)}catch{}},anchor:D!=null?D:E,position:"bottom-right",portal:J()})};f.isConnected?ie():requestAnimationFrame(ie),E.addEventListener("click",Le=>{Le.stopPropagation(),z==null||z.toggle()})}j.addEventListener("click",async()=>{var J;try{await((J=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:J.call(t))}catch{}ae()}),te.addEventListener("click",()=>{var J;m(),(J=e.onDismiss)==null||J.call(e)});let ve=()=>{o&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),M.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",ve(),ae()}),M.addEventListener("click",()=>{x="source",ve(),ae()});let Pe=b("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");o?(g.replaceChildren(),P.append(T,M),D?N.append(D,j,te):N.append(B,j,te),g.append(P,Pe,N),ve()):(g.appendChild(u),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Oe=b("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"),Ae=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Oe.style.paddingLeft=s,Oe.style.paddingRight=s,Ae.style.padding=s),f.appendChild(g),f.appendChild(Oe),f.appendChild(Ae);let be=[],ne=null,Q=!1,ae=()=>{var at,it,nt,Me;let J=o&&be.length<=1;Oe.classList.toggle("persona-hidden",J),Oe.replaceChildren();for(let de of be){let Qe=b("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");Qe.type="button",Qe.textContent=de.title||de.id.slice(0,8),de.id===ne&&Qe.classList.add("persona-bg-persona-container","persona-border-persona-border"),Qe.addEventListener("click",()=>e.onSelect(de.id)),Oe.appendChild(Qe)}Ae.replaceChildren();let ie=ne&&be.find(de=>de.id===ne)||be[be.length-1];if(!ie)return;if(o){let de=ie.artifactType==="markdown"?"MD":(at=ie.component)!=null?at:"Component",X=(ie.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Pe.textContent=`${X} \xB7 ${de}`}else u.textContent="Artifacts";if(ie.artifactType==="markdown"){if(o&&x==="source"){let Qe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Qe.textContent=(it=ie.markdown)!=null?it:"",Ae.appendChild(Qe);return}let de=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");de.innerHTML=d((nt=ie.markdown)!=null?nt:""),Ae.appendChild(de);return}let Le=ie.component?Ho.get(ie.component):void 0;if(Le){let Qe={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let X=Le((Me=ie.props)!=null?Me:{},Qe);if(X){Ae.appendChild(X);return}}catch{}}Ae.appendChild(ov(ie))},fe=()=>{var ie;let J=be.length>0;if(f.classList.toggle("persona-hidden",!J),c){let Le=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,it=((ie=Le==null?void 0:Le.classList.contains("persona-artifact-narrow-host"))!=null?ie:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&it&&Q?(c.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:c,update(J){var ie,Le,at;be=J.artifacts,ne=(at=(Le=J.selectedId)!=null?Le:(ie=J.artifacts[J.artifacts.length-1])==null?void 0:ie.id)!=null?at:null,be.length>0&&(Q=!0),ae(),fe()},setMobileOpen(J){Q=J,!J&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):fe()}}}function sr(n){var e,t;return((t=(e=n==null?void 0:n.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function bm(n,e){var s,a,i,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!sr(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function sv(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ja(n,e){var d,c,m,f,g,u,v,x,P,T;if(!sr(e)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),sv(n),bm(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(m=t==null?void 0:t.splitGap)!=null?m:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=t==null?void 0:t.paneBackground)==null?void 0:u.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(P=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:P.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),bm(n,e)}var vm=["panel","seamless"];function Ya(n,e){var i,d,c,m,f,g;for(let u of vm)n.classList.remove(`persona-artifact-appearance-${u}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!sr(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=vm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(m=t==null?void 0:t.paneBorderRadius)==null?void 0:m.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let u=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;u&&n.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function xm(n,e){var t,r,o;return!e||!sr(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function av(n,e){if(!(n!=null&&n.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):e}function iv(n){if(!(n!=null&&n.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):null}function lv(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function cv(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function wm(n,e){var a;let r=(a=(e.getComputedStyle(n).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Cm(n,e,t,r,o,s){let a=av(o,200),i=cv(e,t,r,200);i=Math.max(a,i);let d=iv(s);return d!==null&&(i=Math.min(i,d)),lv(n,a,i)}var Am={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"}},Gi=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,P;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Am[a])!=null?x:Am.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let T=b("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,I;let M=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${e.id}-${a}-${T.name}`;let N=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");N.textContent=T.label,M.appendChild(N);let k=(C=T.type)!=null?C:"text",W;k==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=k),W.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",W.id=`${e.id}-${a}-${T.name}`,W.name=T.name,W.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(W.required=!0),M.appendChild(W),m.appendChild(M)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("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");u.type="submit",u.textContent=(P=i.submitLabel)!=null?P:"Submit",f.appendChild(g),f.appendChild(u),m.appendChild(f),s.replaceChildren(d,m),m.addEventListener("submit",async T=>{var W,C;T.preventDefault();let M=(W=t.formEndpoint)!=null?W:"/form",N=new FormData(m),k={};N.forEach((I,D)=>{k[D]=I}),k.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let I=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let D=await I.json();g.textContent=(C=D.message)!=null?C:"Thanks! We'll be in touch soon.",D.success&&D.nextPrompt&&await r.sendMessage(String(D.nextPrompt))}catch(I){g.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var Qi=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var r;let t=this.plugins.get(e);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let r=new Set(e.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},Xi=new Qi;var Sm=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:e,off:t,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var dv=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},pv=n=>{let e=n.trim(),t=e.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(t,o+1)}return null},Yi=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=dv(n),t=pv(e);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Ji=n=>typeof n=="string"?n:n==null?"":String(n),Ys={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Ji(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=Ji(t.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Ji(t.text)}}},Tm=n=>Array.isArray(n)?n.map(e=>String(e)):[],Zi=n=>{let e=new Set(Tm(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Tm(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,m)=>c||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let m=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:m});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:t}};var uv=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},mv=n=>n.map(e=>({...e,streaming:!1})),gv=n=>n.map(e=>({...e,status:"complete"})),Mm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?uv(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?mv(t.messages):void 0,artifacts:t.artifacts?gv(t.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as AA,STR as SA,OBJ as TA}from"partial-json";function Em(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Ho.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(n.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,i),null}}function km(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let e=n.content.trim();if(e.startsWith("{")||e.startsWith("["))return n.content}return null}function Lm(n){let e=km(n);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Pm(n){let e=km(n);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var fv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Im(n){let{onSubmit:e,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=fv}=n,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,u.appendChild(x),g.appendChild(u);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-csat",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let C=1;C<=5;C++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),I.title=c[C-1],I.dataset.rating=String(C),I.innerHTML=`
27
+ `,n.addEventListener("click",e);let r=s=>{var k,E,P,C,L,F,O,R,$,N,Z,Se,pe;let a=(k=s.launcher)!=null?k:{},i=yn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(E=a.title)!=null?E:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(P=a.subtitle)!=null?P:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(f.style.height=ee,f.style.width=ee,f.innerHTML="",a.agentIconName){let ve=parseFloat(ee)||24,Ie=fe(a.agentIconName,ve*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(f.appendChild(Ie),f.style.display=""):(f.textContent=(L=a.agentIconText)!=null?L:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",f.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ee=(O=a.agentIconSize)!=null?O:"40px";g.style.height=ee,g.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ee=(R=a.callToActionIconSize)!=null?R:"32px";m.style.height=ee,m.style.width=ee,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let ve=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ve=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Ie=parseFloat(ee)||24,ce=Math.max(Ie-ve,8),ue=fe(a.callToActionIconName,ce,"currentColor",2);ue?m.appendChild(ue):m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let x=a.position&&fr[a.position]?fr[a.position]:fr["bottom-right"],v="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",M="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?M:`${v} ${x}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:Cn));let W="1px solid var(--persona-border, #e5e7eb)",T="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=(Se=a.border)!=null?Se:W,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:T,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=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",e),n.remove()};return t&&r(t),{element:n,update:r,destroy:o}};var sm=({config:t,showClose:e})=>{let{wrapper:n,panel:r,pillRoot:o}=rm(t),s=om(t,e),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},$i=({config:t,plugins:e,onToggle:n})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:t,defaultRenderer:()=>_i(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=_i(t,n);return{instance:o,element:o.element}};var Cb=t=>{switch(t){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}},Ab=(t,e)=>{if(!t)return null;let n=Cb(t);if(n===null)return null;let r=e==null?void 0:e[t],o=r!==void 0?r:n;return o||null},Sb=(t,e)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},Tb=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Ui=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},zi=320,im=320,Eb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Mb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),kb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Lb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Pb=(t,e,n)=>{if(t.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return t.forEach((i,d)=>{var f;let c=y("img");c.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${zi}px`,c.style.maxHeight=`${im}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),Tb(i.image)?(c.src=i.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Ib=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(r=>{if(!Ui(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${zi}px`,e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Wb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(r=>{if(!Ui(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${zi}px`,o.style.maxHeight=`${im}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Rb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(r=>{if(!Ui(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Zs=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.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 r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(r),t.appendChild(o),t},Hb=(t,e,n)=>{let r={config:n!=null?n:{},streaming:!0,location:t,defaultRenderer:Zs};if(e){let o=e(r);if(o!==null)return o}return Zs()},Bb=(t,e)=>{let n=y("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"),r=e==="user"?t.userAvatar:t.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},am=(t,e,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(t.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Db=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="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"),t==="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"),t==="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},Nb=(t,e,n)=>{var x,v,M,W,T,k,E;let r=(x=e.showCopy)!=null?x:!0,o=(v=e.showUpvote)!=null?v:!0,s=(M=e.showDownvote)!=null?M:!0,a=(W=e.showReadAloud)!=null?W:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${t.id}`,P.setAttribute("data-actions-for",t.id),P}let i=(T=e.visibility)!=null?T:"hover",d=(k=e.align)!=null?k:"right",c=(E=e.layout)!=null?E:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${t.id}`,g.setAttribute("data-actions-for",t.id);let m=(P,C,L)=>{let F=An({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",L),F};return r&&g.appendChild(m("copy","Copy message","copy")),a&&g.appendChild(m("volume-2","Read aloud","read-aloud")),o&&g.appendChild(m("thumbs-up","Upvote","upvote")),s&&g.appendChild(m("thumbs-down","Downvote","downvote")),g},qi=(t,e,n,r,o,s)=>{var oe,se,de,$e,Ne,V,G,be,X,le,Ee,Xe,Ze,wt,dt,Ye,He;let a=n!=null?n:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,u=(se=d==null?void 0:d.show)!=null?se:!1,f=(de=c==null?void 0:c.show)!=null?de:!1,g=($e=d==null?void 0:d.position)!=null?$e:"left",m=(Ne=c==null?void 0:c.position)!=null?Ne:"below",x=Db(t.role,i),v=y("div",x.join(" "));v.id=`bubble-${t.id}`,v.setAttribute("data-message-id",t.id),v.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Eb(t),W=(G=(V=t.content)==null?void 0:V.trim())!=null?G:"",k=M.length>0&&W===Ea,E=Oa((X=(be=s==null?void 0:s.widgetConfig)==null?void 0:be.features)==null?void 0:X.streamAnimation),P=(Xe=(Ee=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Ee.streamAnimation)==null?void 0:Xe.plugins,C=t.role==="assistant"&&E.type!=="none"?Vs(E.type,P):null,L=t.role==="assistant"&&((Ze=C==null?void 0:C.isAnimating)==null?void 0:Ze.call(C,t))===!0,F=t.role==="assistant"&&C!==null&&(!!t.streaming||L);F&&(C!=null&&C.bubbleClass)&&v.classList.add(C.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),t.streaming&&O.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&O.classList.add(C.containerClass),O.style.setProperty("--persona-stream-step",`${E.speed}ms`),O.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let R=F?_a((wt=t.content)!=null?wt:"",E.buffer,C,t,!!t.streaming):(dt=t.content)!=null?dt:"",$=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent}),N=$;F&&(C==null?void 0:C.wrap)==="char"?N=Ks($,"char",t.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=Ks($,"word",t.id,{skipTags:C.skipTags}));let Z=null;if(k?(Z=document.createElement("div"),Z.innerHTML=N,Z.style.display="none",O.appendChild(Z)):O.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&W){let K=$a(),qe=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=qe[qe.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(K,ze.nextSibling);else{let xe=O.lastElementChild;xe?xe.appendChild(K):O.appendChild(K)}}if(f&&m==="inline"&&t.createdAt){let K=am(t,c,"span");K.classList.add("persona-timestamp-inline");let qe=O.lastElementChild;qe?qe.appendChild(K):O.appendChild(K)}if(M.length>0){let K=Pb(M,!k&&!!W,()=>{k&&Z&&(Z.style.display="")});K?v.appendChild(K):k&&Z&&(Z.style.display="")}let Se=Mb(t);if(Se.length>0){let K=Ib(Se);K&&v.appendChild(K)}let pe=kb(t);if(pe.length>0){let K=Wb(pe);K&&v.appendChild(K)}let ee=Lb(t);if(ee.length>0){let K=Rb(ee);K&&v.appendChild(K)}if(v.appendChild(O),f&&m==="below"&&t.createdAt){let K=am(t,c);K.classList.add("persona-mt-1"),v.appendChild(K)}let ve=t.role==="assistant"?Ab(t.stopReason,(He=(Ye=s==null?void 0:s.widgetConfig)==null?void 0:Ye.copy)==null?void 0:He.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let K=!!(R&&R.trim()),qe=E.placeholder==="skeleton",ze=qe&&E.buffer==="line"&&K;if(K)ze&&v.appendChild(Gs());else if(qe)v.appendChild(Gs());else{let xe=Hb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);xe&&v.appendChild(xe)}}if(ve&&t.stopReason&&!t.streaming&&(W||(O.style.display="none"),v.appendChild(Sb(t.stopReason,ve))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let K=Nb(t,r,o);v.appendChild(K)}if(!u||t.role==="system")return v;let ce=y("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ue=Bb(d,t.role);return g==="right"||g==="left"&&t.role==="user"?ce.append(v,ue):ce.append(ue,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ce};var ps=new Set,Fb=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Ob=(t,e)=>{var r,o;let n=(o=(r=t.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
28
+ `):""},lm=(t,e)=>{let n=ps.has(t),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=fe(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ji=(t,e)=>{var pe,ee,ve,Ie,ce,ue,oe,se,de,$e,Ne;let n=t.reasoning,r=y("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(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),!n)return r;let o=(ee=(pe=e==null?void 0:e.features)==null?void 0:pe.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&ps.has(t.id),i=n.status!=="complete",d=Ob(t,(ve=o.previewMaxLines)!=null?ve:3),c=y("button",s?"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");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let u=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=(Ie=e==null?void 0:e.reasoning)!=null?Ie:{},x=String((ce=n.startedAt)!=null?ce:Date.now()),v=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",x),V.textContent=Ca(n),V},M=(ue=m.renderCollapsedSummary)==null?void 0:ue.call(m,{message:t,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ca(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(f.textContent=M,u.appendChild(f)):M instanceof HTMLElement?u.appendChild(M):(f.textContent=g,u.appendChild(f));let W=y("span","persona-text-xs persona-text-persona-primary");W.textContent=lu(n),u.appendChild(W);let T=(oe=o.loadingAnimation)!=null?oe:"none",k=m.activeTextTemplate,E=m.completeTextTemplate,P=i?k:E,C=M instanceof HTMLElement,L=(V,G,be)=>{let X=be;for(let le of G){let Ee=y("span","persona-tool-char");Ee.style.setProperty("--char-index",String(X)),Ee.textContent=le===" "?"\xA0":le,V.appendChild(Ee),X++}return X},F=(V,G)=>{f.textContent="";let be=Aa(V,""),X=0;for(let le of be){let Ee=le.styles.length>0?(()=>{let Xe=y("span",le.styles.map(Ze=>`persona-tool-text-${Ze}`).join(" "));return f.appendChild(Xe),Xe})():f;if(le.isDuration&&i)Ee.appendChild(v());else{let Xe=le.isDuration?Ca(n):le.text;G?X=L(Ee,Xe,X):Ee.appendChild(document.createTextNode(Xe))}}};if(!C&&P)if(W.style.display="none",f.style.display="",i&&T!=="none"){let V=(se=m.loadingAnimationDuration)!=null?se:2e3;f.setAttribute("data-preserve-animation","true"),T==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),F(P,!1)):(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),T==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),F(P,!0))}else F(P,!1);else if(!C&&i&&T!=="none"){f.style.display="";let V=(de=m.loadingAnimationDuration)!=null?de:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),T==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let G=f.textContent||g;f.textContent="",L(f,G,0)}n.status==="complete"&&(f.style.display="none")}else C||(n.status==="complete"?f.style.display="none":f.style.display="");let O=null;if(s){O=y("div","persona-flex persona-items-center");let G=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);G?O.appendChild(G):O.textContent=a?"Hide":"Show";let be=y("div","persona-flex persona-items-center persona-ml-auto");be.append(O),c.append(u,be)}else c.append(u);let R=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(Ne=($e=e==null?void 0:e.reasoning)==null?void 0:$e.renderCollapsedPreview)==null?void 0:Ne.call($e,{message:t,reasoning:n,defaultPreview:d,isActive:i,config:e!=null?e:{}});Fb(R,V)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,R),r;let $=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=a?"":"none";let N=n.chunks.join(""),Z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(Z),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),O){O.innerHTML="";let G=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);G?O.appendChild(G):O.textContent=a?"Hide":"Show"}$.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(c,R,$),r};var us=new Set,_b=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),$b=(t,e)=>{var s;let n=t.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
29
+ `);let o=co(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
30
+ `):""},Vi=(t,e)=>{var n,r,o;t.style.backgroundColor=(n=e.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",t.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",t.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Ub=(t,e)=>{var u,f,g,m,x;let n=t.toolCall,r=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=$b(t,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?cu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((x=n.name)==null?void 0:x.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Ei(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Ei(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},cm=(t,e,n)=>{var u;let r=us.has(t),o=(u=n==null?void 0:n.toolCall)!=null?u:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=fe(r?"chevron-up":"chevron-down",16,f,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Ki=(t,e)=>{var N,Z,Se,pe,ee,ve,Ie,ce,ue;let n=t.toolCall,r=(N=e==null?void 0:e.toolCall)!=null?N:{},o=y("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(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Se=(Z=e==null?void 0:e.features)==null?void 0:Z.toolCallDisplay)!=null?Se:{},a=s.expandable!==!1,i=a&&us.has(t.id),{summary:d,previewText:c,isActive:u}=Ub(t,e),f=y("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");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let x=String((pe=n.startedAt)!=null?pe:Date.now()),v=()=>{let oe=y("span","");return oe.setAttribute("data-tool-elapsed",x),oe.textContent=Bs(n),oe},M=(ve=r.renderCollapsedSummary)==null?void 0:ve.call(r,{message:t,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:u,config:e!=null?e:{},elapsed:Bs(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(m.textContent=M,g.appendChild(m)):M instanceof HTMLElement?g.appendChild(M):(m.textContent=d,g.appendChild(m));let W=(Ie=s.loadingAnimation)!=null?Ie:"none",T=r.activeTextTemplate,k=r.completeTextTemplate,E=u?T:k,P=M instanceof HTMLElement,C=(oe,se,de)=>{let $e=de;for(let Ne of se){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String($e)),V.textContent=Ne===" "?"\xA0":Ne,oe.appendChild(V),$e++}return $e},L=(oe,se)=>{var V;m.textContent="";let de=((V=n.name)==null?void 0:V.trim())||"tool",$e=Aa(oe,de),Ne=0;for(let G of $e){let be=G.styles.length>0?(()=>{let X=y("span",G.styles.map(le=>`persona-tool-text-${le}`).join(" "));return m.appendChild(X),X})():m;if(G.isDuration&&u)be.appendChild(v());else{let X=G.isDuration?Bs(n):G.text;se?Ne=C(be,X,Ne):be.appendChild(document.createTextNode(X))}}};if(!P)if(u&&W!=="none"){let oe=(ce=r.loadingAnimationDuration)!=null?ce:2e3;if(m.setAttribute("data-preserve-animation","true"),W==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),E&&L(E,!1);else if(m.classList.add(`persona-tool-loading-${W}`),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),W==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),E)L(E,!0);else{let se=m.textContent||d;m.textContent="",C(m,se,0)}}else E&&L(E,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=fe(i?"chevron-up":"chevron-down",16,oe,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show";let de=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(F),f.append(g,de)}else f.append(g);let O=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&c){let oe=(ue=r.renderCollapsedPreview)==null?void 0:ue.call(r,{message:t,toolCall:n,defaultPreview:c,isActive:u,config:e!=null?e:{}});_b(O,oe)||(O.textContent=c),O.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,O),o;let R=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let oe=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?oe.style.color=r.contentTextColor:r.headerTextColor&&(oe.style.color=r.headerTextColor),oe.textContent=n.name,R.appendChild(oe)}if(n.args!==void 0){let oe=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Arguments";let de=y("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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Vi(de,r),de.textContent=co(n.args),oe.append(se,de),R.appendChild(oe)}if(n.chunks&&n.chunks.length){let oe=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Activity";let de=y("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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Vi(de,r),de.textContent=n.chunks.join(""),oe.append(se,de),R.appendChild(oe)}if(n.status==="complete"&&n.result!==void 0){let oe=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Result";let de=y("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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Vi(de,r),de.textContent=co(n.result),oe.append(se,de),R.appendChild(oe)}if(n.status==="complete"&&typeof n.duration=="number"){let oe=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${n.duration}ms`,R.appendChild(oe)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=fe(i?"chevron-up":"chevron-down",16,oe,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",O.style.display=i?"none":O.textContent||O.childNodes.length?"":"none"})(),o.append(f,O,R),o};var Bo=new Map,Ya=t=>{let n=(t.startsWith(Ur)?t.slice(Ur.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},dm=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,pm=(t,e)=>{var r,o,s;let n=(o=(r=dm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Bo.get(t))!=null?s:n==="expanded"},um=(t,e,n)=>{var a,i;let r=dm(n);t.setAttribute("aria-expanded",e?"true":"false");let o=t.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=fe(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},mm=(t,e,n)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=pm(t,n);um(r,s,n),o.style.display=s?"":"none"};var Za=(t,e)=>{var L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue,oe;let n=t.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(L=r==null?void 0:r.backgroundColor)!=null?L:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(F=r==null?void 0:r.borderColor)!=null?F:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=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=r==null?void 0:r.titleColor)!=null?O:"currentColor",u=fe(d,20,c,2);u&&i.appendChild(u);let f=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),m=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(R=r==null?void 0:r.title)!=null?R:"Approval Required",g.appendChild(m),!o){let se=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",n.status),n.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):n.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):n.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),g.appendChild(se)}f.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Ur)?Ps(n.toolName):void 0,M=($=r==null?void 0:r.formatDescription)==null?void 0:$.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),W=!n.toolName,T=M||(W?n.description:`The assistant wants to use \u201C${v!=null?v:Ya(n.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=T,f.appendChild(k),n.reason){let se=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?se.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let de=y("span","persona-font-medium");de.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,se.appendChild(de),se.appendChild(document.createTextNode(n.reason)),f.appendChild(se)}let E=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",P=!!n.description&&!W,C=P||!!n.parameters;if(E!=="hidden"&&C){let se=pm(t.id,e),de=y("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");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let $e=y("span");$e.setAttribute("data-approval-details-label","true");let Ne=y("span","persona-inline-flex persona-items-center");Ne.setAttribute("data-approval-details-chevron","true"),de.append($e,Ne),um(de,se,e),f.appendChild(de);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"none",P){let G=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(G.style.color=r.descriptionColor),G.textContent=n.description,V.appendChild(G)}if(n.parameters){let G=y("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");r!=null&&r.parameterBackgroundColor&&(G.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(G.style.color=r.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=co(n.parameters),V.appendChild(G)}f.appendChild(V)}if(o){let se=y("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let de=y("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");de.type="button",de.style.backgroundColor=(Se=r==null?void 0:r.approveButtonColor)!=null?Se:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",de.setAttribute("data-approval-action","approve");let $e=fe("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);$e&&($e.style.marginRight="4px",de.appendChild($e));let Ne=document.createTextNode((ve=r==null?void 0:r.approveLabel)!=null?ve:"Approve");de.appendChild(Ne);let V=y("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");V.type="button",V.style.backgroundColor=(Ie=r==null?void 0:r.denyButtonColor)!=null?Ie:"transparent",V.style.color=(ce=r==null?void 0:r.denyButtonTextColor)!=null?ce:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let G=fe("shield-x",14,(ue=r==null?void 0:r.denyButtonTextColor)!=null?ue:"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",V.appendChild(G));let be=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");V.appendChild(be),se.append(de,V),f.appendChild(se)}return a.append(i,f),s.appendChild(a),s};function zb(t){var n,r;let e=(n=t.getRootNode)==null?void 0:n.call(t);return e instanceof ShadowRoot?e:((r=t.ownerDocument)!=null?r:document).body}function gm(t){var v;let{anchor:e,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=t,c=(v=t.container)!=null?v:zb(e),u=!1,f=null,g=()=>{if(!u)return;let M=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${M.width}px`);let W=r==="top-start"||r==="top-end"?M.top-o-n.getBoundingClientRect().height:M.bottom+o,T=r==="bottom-end"||r==="top-end"?M.right-n.getBoundingClientRect().width:M.left;n.style.top=`${W}px`,n.style.left=`${T}px`},m=()=>{u&&(u=!1,f&&(f(),f=null),n.remove())},x=()=>{var P,C,L;if(u)return;u=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),g();let M=(C=((P=e.ownerDocument)!=null?P:document).defaultView)!=null?C:window,W=(L=e.ownerDocument)!=null?L:document,T=()=>{if(!e.isConnected){m(),d==null||d("anchor-removed");return}g()},k=F=>{let O=typeof F.composedPath=="function"?F.composedPath():[];O.includes(n)||O.includes(e)||(m(),d==null||d("outside"))},E=M.setTimeout(()=>{W.addEventListener("pointerdown",k,!0)},0);M.addEventListener("scroll",T,!0),M.addEventListener("resize",T),f=()=>{M.clearTimeout(E),W.removeEventListener("pointerdown",k,!0),M.removeEventListener("scroll",T,!0),M.removeEventListener("resize",T)},i==null||i()};return{get isOpen(){return u},open:x,close:m,toggle:()=>u?m():x(),reposition:g,destroy:m}}function fm(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var qb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),hm=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let r=t.popovers.get(e);r&&(r.destroy(),t.popovers.delete(e))},Do=(t,e)=>{hm(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},jb=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,Vb=(t,e)=>{var r,o;let n=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=Bo.get(t))!=null?o:n==="expanded"},Gi=t=>{let e=y("span","persona-approval-kbd");return e.textContent=t,e},Kb=(t,e)=>{var c,u;let n=y("span","persona-approval-title");e!=null&&e.titleColor&&(n.style.color=e.titleColor);let o=t.toolType==="webmcp"||t.toolName.startsWith(Ur)?Ps(t.toolName):void 0,s=(u=e==null?void 0:e.formatDescription)==null?void 0:u.call(e,{toolName:t.toolName,toolType:t.toolType,description:(c=t.description)!=null?c:"",parameters:t.parameters,...o?{displayTitle:o}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:Ya(t.toolName),i=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let f=document.createElement("strong");f.textContent=i,n.appendChild(f)}return n},Gb=t=>{let e=y("div","persona-approval-resolved"),n=fe("ban",15,"currentColor",2);n&&e.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=t.toolName?Ya(t.toolName):"Tool",e.append(r,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Qb=(t,e,n,r,o,s,a)=>{var F,O,R,$,N,Z,Se;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(F=r==null?void 0:r.detailsDisplay)!=null?F:"collapsed",c=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",f=c||u,g=f&&Vb(e.id,r),m=(O=r==null?void 0:r.showDetailsLabel)!=null?O:"Show details",x=(R=r==null?void 0:r.hideDetailsLabel)!=null?R:"Hide details",v=y("button","persona-approval-head");v.type="button",f?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",g?"true":"false"),v.setAttribute("aria-label",g?x:m)):v.setAttribute("data-static","true");let M=y("span","persona-approval-logo"),W=fe("shield-check",16,"currentColor",2);W&&M.appendChild(W),v.appendChild(M);let T=Kb(n,r);if(f){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let ee=fe("chevron-down",14,"currentColor",2);ee&&pe.appendChild(ee),T.append(" "),T.appendChild(pe)}v.appendChild(T),i.appendChild(v);let k=y("div","persona-approval-body");if(f){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,c){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,pe.appendChild(ee)}if(u){let ee=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=co(n.parameters),pe.appendChild(ee)}k.appendChild(pe)}if(n.reason){let pe=y("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let ee=y("span","persona-approval-reason-label");ee.textContent=`${($=r==null?void 0:r.reasonLabel)!=null?$:"Agent's stated reason:"} `,pe.append(ee,document.createTextNode(n.reason)),k.appendChild(pe)}let E=y("div","persona-approval-actions"),P=null,C=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},L=y("button","persona-approval-deny");if(L.type="button",L.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(L.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(L.style.color=r.denyButtonTextColor),L.append((N=r==null?void 0:r.denyLabel)!=null?N:"Deny"),a){let pe=y("div","persona-approval-split"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Gi("\u23CE"));let ve=y("button","persona-approval-caret");ve.type="button",ve.setAttribute("data-action","toggle-menu"),ve.setAttribute("aria-label","More options"),C(ve);let Ie=fe("chevron-down",15,"currentColor",2);Ie&&ve.appendChild(Ie),pe.append(ee,ve),E.append(pe,L),L.append(Gi("Esc"));let ce=y("div","persona-approval-menu"),ue=y("button","persona-approval-menu-item");ue.type="button",ue.append("Allow once",Gi("\u2318\u23CE")),ce.appendChild(ue),P=gm({anchor:pe,content:ce,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,P),ue.addEventListener("click",()=>{Do(t,e.id),o()})}else{let pe=y("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),C(pe),pe.append((Se=r==null?void 0:r.approveLabel)!=null?Se:"Allow"),E.append(pe,L)}return k.appendChild(E),i.appendChild(k),i.addEventListener("click",pe=>{let ee=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!ee)return;let ve=ee.getAttribute("data-action");if(ve==="toggle-params"){let Ie=i.querySelector('[data-role="params"]');if(Ie){let ce=Ie.hidden;Ie.hidden=!ce,v.setAttribute("aria-expanded",ce?"true":"false"),v.setAttribute("aria-label",ce?x:m),Bo.set(e.id,ce)}return}if(ve==="toggle-menu"){P==null||P.toggle();return}if(ve==="always"){Do(t,e.id),o({remember:!0});return}if(ve==="allow"){Do(t,e.id),o();return}if(ve==="deny"){Do(t,e.id),s();return}}),i},ym=()=>{let t=qb();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=jb(a);if(i.status!=="pending"){if(Do(t,r.id),i.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return Gb(i)}hm(t,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,u=Qb(t,r,i,d,o,s,c);if(c){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let f=g=>{fm(g)||r.id===t.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Do(t,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};t.keyHandlers.set(r.id,f),document.addEventListener("keydown",f)}return u}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Do(t,r);t.latestPendingApprovalId=null}}};var bm=t=>{let e=[],n=null;return{buttons:e,render:(o,s,a,i,d,c)=>{t.innerHTML="",e.length=0;let u=(c==null?void 0:c.agentPushed)===!0;if(u||(n=null),!o||!o.length||!u&&(i!=null?i:s?s.getMessages():[]).some(M=>M.role==="user"))return;let f=document.createDocumentFragment(),g=s?s.isStreaming():!1,m=x=>{switch(x){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(o.forEach(x=>{let v=y("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");v.type="button",v.textContent=x,v.disabled=g,d!=null&&d.fontFamily&&(v.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),s.sendMessage(x))}),f.appendChild(v),e.push(v)}),t.appendChild(f),u){let x=JSON.stringify(o);x!==n&&(n=x,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ea=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){var n;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(n=this.store)==null||n.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ta=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var Xb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Jb=new Set(["step_start","execution_start"]),Yb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Zb=new Set(["step_complete","agent_turn_complete"]),ev=new Set(["flow_complete","agent_complete"]),vm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),wm=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Qn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,No=(t,e)=>{let n=t[e];return wm(n)?n:void 0};function Qi(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ei(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function tv(t,e){return typeof e.type=="string"?e.type:t}function nv(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function rv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function xm(t){var r,o,s,a,i;let e=No(t,"result"),n=[No(t,"tokens"),No(t,"totalTokens"),e?No(e,"tokens"):void 0,No(t,"usage"),e?No(e,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?o:Qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Qn(t.outputTokens))!=null?s:Qn(t.completionTokens))!=null?i:e?(a=Qn(e.outputTokens))!=null?a:Qn(e.completionTokens):void 0}function ov(t){var n,r,o,s,a;let e=No(t,"result");return(a=(o=(r=(n=Qn(t.executionTime))!=null?n:Qn(t.executionTimeMs))!=null?r:Qn(t.execution_time))!=null?o:Qn(t.duration))!=null?a:e?(s=Qn(e.executionTime))!=null?s:Qn(e.executionTimeMs):void 0}function sv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var na=class{constructor(e=sv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ei(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){var s;if(!wm(n)){vm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=tv(e,n),o=this.now();if(Xb.has(r)){this.startRun(o);return}if(Jb.has(r)){this.run||this.startRun(o);return}if(Yb.has(r)){if(!rv(r,n))return;let a=nv(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Qi(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ei(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Zb.has(r)){if(!this.run)return;let a=this.run,i=xm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Qi(a.visibleCharCount),u=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:ei(c,u),outputTokens:c,durationMs:u,source:d?"usage":"estimate"};return}if(ev.has(r)){if(!this.run)return;let a=this.run,i=xm(n),d=i!=null?i:a.exactOutputTokens+Qi(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:ei(d,u),outputTokens:d,durationMs:u,source:c},this.run=null;return}if(vm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=ov(n);return s!=null?s:r-e.startedAt}};function ms(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var av={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)"}},iv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},lv=["flowName","stepName","reasoningText","text","name","tool","toolName"],cv=100;function dv(t,e){let n={...av,...e};if(n[t])return n[t];for(let r of Object.keys(n))if(r.endsWith("_")&&t.startsWith(r))return n[r];return iv}function pv(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function uv(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function mv(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let r of e){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function gv(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(n=>{let r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function fv(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function hv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function yv(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function bv(t,e,n){let r,o;try{o=JSON.parse(t.payload),r=JSON.stringify(o,null,2)}catch{o=t.payload,r=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("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]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Xi(t,e,n,r,o,s,a,i){var g;let d=o.has(t.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");ms(c,(g=r.classNames)==null?void 0:g.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var N,Z;let m=y("div",""),x=y("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");x.setAttribute("data-event-id",t.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=fe(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.appendChild(M);let W=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(N=r.timestampFormat)!=null?N:"relative";W.textContent=T==="relative"?pv(t.timestamp,n):uv(t.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(e+1));let E=dv(t.type,r.badgeColors),P=y("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");P.style.backgroundColor=E.bg,P.style.color=E.text,P.style.borderColor=E.text+"50",P.textContent=t.type;let C=(Z=r.descriptionFields)!=null?Z:lv,L=mv(t.payload,C),F=null;L&&(F=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=L);let O=y("div","persona-flex-1 persona-min-w-0"),R=y("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"),$=fe("clipboard","12px","currentColor",1.5);return $&&R.appendChild($),R.addEventListener("click",async Se=>{Se.stopPropagation(),await gv(fv(t)),R.innerHTML="";let pe=fe("check","12px","currentColor",1.5);pe&&R.appendChild(pe),setTimeout(()=>{R.innerHTML="";let ee=fe("clipboard","12px","currentColor",1.5);ee&&R.appendChild(ee)},1500)}),x.appendChild(v),x.appendChild(W),k&&x.appendChild(k),x.appendChild(P),F&&x.appendChild(F),x.appendChild(O),x.appendChild(R),m.appendChild(x),d&&m.appendChild(bv(t,a,i)),m}}function Cm(t){var x,v,M,W,T;let{buffer:e,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=t,i=(x=o==null?void 0:o.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(M=i==null?void 0:i.label)!=null?M:"",f=(T=(W=o==null?void 0:o.features)==null?void 0:W.eventStream)!=null?T:{},g=s.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let k=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return m();function m(){let k=f.classNames,E=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ms(E,k==null?void 0:k.panel);let P=[],C="",L="",F=null,O=[],R={},$=0,N=Da(),Z=0,Se=0,pe=!1,ee=null,ve=!1,Ie=0,ce=new Set,ue=new Map,oe="",se="",de=null,$e,Ne,V,G,be,X=null,le=null,Ee=null;function Xe(){let H=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),J=y("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");ms(J,k==null?void 0:k.headerBar);let Ae=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ae.textContent="Events",$e=y("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"),$e.textContent="0",a){le=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let _t=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");_t.textContent="Throughput",X=y("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"),X.textContent="-- tok/s",Ee=y("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"),Ee.style.display="none",Ee.style.pointerEvents="none";let Nn=le,Sn=Ee,Tn=()=>{if(!Sn.textContent)return;let En=Nn.getBoundingClientRect(),ar=H.getBoundingClientRect();Sn.style.left=`${En.left-ar.left}px`,Sn.style.top=`${En.bottom-ar.top+4}px`,Sn.style.display="block"},bn=()=>{Sn.style.display="none"};le.addEventListener("mouseenter",Tn),le.addEventListener("mouseleave",bn),le.appendChild(_t),le.appendChild(X)}let it=y("div","persona-flex-1");Ne=y("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 Qe=y("option","");Qe.value="",Qe.textContent="All events",Ne.appendChild(Qe),V=y("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"),V.type="button",V.title="Copy All";let fn=fe("clipboard-copy","12px","currentColor",1.5);fn&&V.appendChild(fn);let vt=y("span","persona-text-xs");vt.textContent="Copy All",V.appendChild(vt),J.appendChild(Ae),J.appendChild($e),le&&J.appendChild(le),J.appendChild(it),J.appendChild(Ne),J.appendChild(V);let xt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ms(xt,k==null?void 0:k.searchBar);let It=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),Ct=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");It&&Ct.appendChild(It),G=y("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"),ms(G,k==null?void 0:k.searchInput),G.type="text",G.placeholder="Search event payloads...",be=y("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"),be.type="button",be.style.display="none";let ln=fe("x","12px","currentColor",2);return ln&&be.appendChild(ln),xt.appendChild(Ct),xt.appendChild(G),xt.appendChild(be),H.appendChild(J),H.appendChild(xt),Ee&&H.appendChild(Ee),H}let Ze,wt=s.find(H=>H.renderEventStreamToolbar);if(wt!=null&&wt.renderEventStreamToolbar&&o){let H=wt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Xe(),eventCount:e.getSize(),filteredCount:0,onFilterChange:J=>{C=J,Oe(),Xt()},onSearchChange:J=>{L=J,Oe(),Xt()}});Ze=H!=null?H:Xe()}else Ze=Xe();let dt=y("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");dt.style.display="none";function Ye(){if(!a||!X||!le)return;let H=a();X.textContent=hv(H);let J=yv(H);Ee&&(Ee.textContent=J,J||(Ee.style.display="none")),J?le.setAttribute("aria-label",J):le.removeAttribute("aria-label")}let He=y("div","persona-flex-1 persona-min-h-0 persona-relative"),K=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");K.style.height="100%";let qe=y("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");ms(qe,k==null?void 0:k.scrollIndicator),qe.style.display="none",qe.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let ze=fe(c,"14px","currentColor",2);ze&&qe.appendChild(ze);let xe=y("span","");xe.textContent=u,qe.appendChild(xe);let Ce=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ce.style.display="none",He.appendChild(K),He.appendChild(Ce),He.appendChild(qe),E.setAttribute("tabindex","0"),E.appendChild(Ze),E.appendChild(dt),E.appendChild(He);function tt(){let H=e.getAll(),J={};for(let vt of H)J[vt.type]=(J[vt.type]||0)+1;let Ae=Object.keys(J).sort(),it=Ae.length!==O.length||!Ae.every((vt,xt)=>vt===O[xt]),Qe=!it&&Ae.some(vt=>J[vt]!==R[vt]),Ut=H.length!==Object.values(R).reduce((vt,xt)=>vt+xt,0);if(!it&&!Qe&&!Ut||(O=Ae,R=J,!Ne))return;let fn=Ne.value;if(Ne.options[0].textContent="All events",it){for(;Ne.options.length>1;)Ne.remove(1);for(let vt of Ae){let xt=y("option","");xt.value=vt,xt.textContent=`${vt} (${J[vt]||0})`,Ne.appendChild(xt)}fn&&Ae.includes(fn)?Ne.value=fn:fn&&(Ne.value="",C="")}else for(let vt=1;vt<Ne.options.length;vt++){let xt=Ne.options[vt];xt.textContent=`${xt.value} (${J[xt.value]||0})`}}function Ot(){let H=e.getAll();if(C&&(H=H.filter(J=>J.type===C)),L){let J=L.toLowerCase();H=H.filter(Ae=>Ae.type.toLowerCase().includes(J)||Ae.payload.toLowerCase().includes(J))}return H}function ne(){return C!==""||L!==""}function Oe(){$=0,Z=0,N.resume(),qe.style.display="none"}function gn(H){ce.has(H)?ce.delete(H):ce.add(H),de=H;let J=K.scrollTop,Ae=N.isFollowing();ve=!0,N.pause(),Xt(),K.scrollTop=J,Ae&&N.resume(),ve=!1}function Bt(){return Ro(K,50)}function Xt(){Se=Date.now(),pe=!1,Ye(),tt();let H=e.getEvictedCount();H>0?(dt.textContent=`${H.toLocaleString()} older events truncated`,dt.style.display=""):dt.style.display="none",P=Ot();let J=P.length,Ae=e.getSize()>0;$e&&($e.textContent=String(e.getSize())),J===0&&Ae&&ne()?(Ce.textContent=L?`No events matching '${L}'`:"No events matching filter",Ce.style.display="",K.style.display="none"):(Ce.style.display="none",K.style.display=""),V&&(V.title=ne()?`Copy Filtered (${J})`:"Copy All"),d&&!N.isFollowing()&&J>$&&(Z+=J-$,xe.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",qe.style.display=""),$=J;let it=e.getAll(),Qe=it.length>0?it[0].timestamp:0,Ut=new Set(P.map(xt=>xt.id));for(let xt of ce)Ut.has(xt)||ce.delete(xt);let fn=C!==oe||L!==se,vt=ue.size===0&&P.length>0;if(fn||vt||P.length===0){K.innerHTML="",ue.clear();let xt=document.createDocumentFragment();for(let It=0;It<P.length;It++){let Ct=Xi(P[It],It,Qe,f,ce,gn,s,o);ue.set(P[It].id,Ct),xt.appendChild(Ct)}K.appendChild(xt),oe=C,se=L,de=null}else{if(de!==null){let It=ue.get(de);if(It&&It.parentNode===K){let Ct=P.findIndex(ln=>ln.id===de);if(Ct>=0){let ln=Xi(P[Ct],Ct,Qe,f,ce,gn,s,o);K.insertBefore(ln,It),It.remove(),ue.set(de,ln)}}de=null}let xt=new Set(P.map(It=>It.id));for(let[It,Ct]of ue)xt.has(It)||(Ct.remove(),ue.delete(It));for(let It=0;It<P.length;It++){let Ct=P[It];if(!ue.has(Ct.id)){let ln=Xi(Ct,It,Qe,f,ce,gn,s,o);ue.set(Ct.id,ln),K.appendChild(ln)}}}N.isFollowing()&&(K.scrollTop=K.scrollHeight)}function Ir(){if(Date.now()-Se>=cv){ee!==null&&(cancelAnimationFrame(ee),ee=null),Xt();return}pe||(pe=!0,ee=requestAnimationFrame(()=>{ee=null,Xt()}))}let hr=(H,J)=>{if(!V)return;V.innerHTML="";let Ae=fe(H,"12px","currentColor",1.5);Ae&&V.appendChild(Ae);let it=y("span","persona-text-xs");it.textContent="Copy All",V.appendChild(it),setTimeout(()=>{V.innerHTML="";let Qe=fe("clipboard-copy","12px","currentColor",1.5);Qe&&V.appendChild(Qe);let Ut=y("span","persona-text-xs");Ut.textContent="Copy All",V.appendChild(Ut),V.disabled=!1},J)},A=async()=>{if(V){V.disabled=!0;try{let H;ne()?H=P:n?(H=await n(),H.length===0&&(H=e.getAll())):H=e.getAll();let J=H.map(Ae=>{try{return JSON.parse(Ae.payload)}catch{return Ae.payload}});await navigator.clipboard.writeText(JSON.stringify(J,null,2)),hr("check",1500)}catch{hr("x",1500)}}},te=()=>{Ne&&(C=Ne.value,Oe(),Xt())},Te=()=>{!G||!be||(be.style.display=G.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{L=G.value,Oe(),Xt()},150))},Re=()=>{!G||!be||(G.value="",L="",be.style.display="none",F&&clearTimeout(F),Oe(),Xt())},ke=()=>{if(ve)return;let H=K.scrollTop,{action:J,nextLastScrollTop:Ae}=Na({following:N.isFollowing(),currentScrollTop:H,lastScrollTop:Ie,nearBottom:Bt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=Ae,J==="resume"?(N.resume(),Z=0,qe.style.display="none"):J==="pause"&&(N.pause(),d&&(xe.textContent=u,qe.style.display=""))},Be=H=>{let J=Fa({following:N.isFollowing(),deltaY:H.deltaY,nearBottom:Bt(),resumeWhenNearBottom:!0});J==="pause"?(N.pause(),d&&(xe.textContent=u,qe.style.display="")):J==="resume"&&(N.resume(),Z=0,qe.style.display="none")},Ve=()=>{d&&(K.scrollTop=K.scrollHeight,N.resume(),Z=0,qe.style.display="none")},at=H=>{let J=H.target;if(!J||J.closest("button"))return;let Ae=J.closest("[data-event-id]");if(!Ae)return;let it=Ae.getAttribute("data-event-id");it&&gn(it)},Pt=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),G==null||G.focus(),G==null||G.select();return}H.key==="Escape"&&(G&&document.activeElement===G?(Re(),G.blur(),E.focus()):r&&r())};V&&V.addEventListener("click",A),Ne&&Ne.addEventListener("change",te),G&&G.addEventListener("input",Te),be&&be.addEventListener("click",Re),K.addEventListener("scroll",ke),K.addEventListener("wheel",Be,{passive:!0}),K.addEventListener("click",at),qe.addEventListener("click",Ve),E.addEventListener("keydown",Pt);function bt(){F&&clearTimeout(F),ee!==null&&(cancelAnimationFrame(ee),ee=null),pe=!1,ue.clear(),V&&V.removeEventListener("click",A),Ne&&Ne.removeEventListener("change",te),G&&G.removeEventListener("input",Te),be&&be.removeEventListener("click",Re),K.removeEventListener("scroll",ke),K.removeEventListener("wheel",Be),K.removeEventListener("click",at),qe.removeEventListener("click",Ve),E.removeEventListener("keydown",Pt)}return{element:E,update:Ir,destroy:bt}}}function Am(t,e){let n=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;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)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(g);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(u,f),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Sm=(t,e)=>{var r,o,s;let n=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",c=typeof t.artifactType=="string"?t.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Am(t,e)});if(u)return u}return Am(t,e)};var Ji=class{constructor(){this.components=new Map}register(e,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([n,r])=>{this.register(n,r)})}},Fo=new Ji;Fo.register("PersonaArtifactCard",Sm);function vv(t){var o;let e=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=t.props)!=null?o:{},null,2),e.appendChild(n),e.appendChild(r),e}function Tm(t,e){var Ne,V,G,be;let n=(V=(Ne=t.features)==null?void 0:Ne.artifacts)==null?void 0:V.layout,o=((G=n==null?void 0:n.toolbarPreset)!=null?G:"default")==="document",s=(be=n==null?void 0:n.panePadding)==null?void 0:be.trim(),a=t.markdown?ga(t.markdown):null,i=fa(t.sanitize),d=X=>{let le=a?a(X):ao(X);return i?i(le):le},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var X;u(),(X=e.onDismiss)==null||X.call(e)});let f=y("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");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let g=y("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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let m=y("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var X;u(),(X=e.onDismiss)==null||X.call(e)});let v="rendered",M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),W=o?An({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):An({icon:"eye",label:"Rendered view"}),T=o?An({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):An({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,L=!!(P&&C&&C.length>0),F=null,O,R=null,$=null;if(o&&(E||P)&&!L){if(O=E?Oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):An({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let X=fe("chevron-down",14,"currentColor",2);X&&O.appendChild(X)}}else o&&L?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),O=E?Oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):An({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=An({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"}}),F.append(O,R)):o?O=An({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):O=An({icon:"copy",label:"Copy"});let N=o?An({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):An({icon:"refresh-cw",label:"Refresh"}),Z=o?An({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):An({icon:"x",label:"Close"}),Se=()=>{var Ze,wt,dt;let X=(Ze=ue.find(Ye=>Ye.id===oe))!=null?Ze:ue[ue.length-1],le=(wt=X==null?void 0:X.id)!=null?wt:null,Ee=(X==null?void 0:X.artifactType)==="markdown"&&(dt=X.markdown)!=null?dt:"",Xe=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:Ee,jsonPayload:Xe,id:le}},pe=async()=>{var Ze;let{markdown:X,jsonPayload:le}=Se(),Ee=(Ze=ue.find(wt=>wt.id===oe))!=null?Ze:ue[ue.length-1],Xe=(Ee==null?void 0:Ee.artifactType)==="markdown"?X:Ee?le:"";try{await navigator.clipboard.writeText(Xe)}catch{}};if(O.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&L){let{markdown:le,jsonPayload:Ee,id:Xe}=Se();try{await X({actionId:"primary",artifactId:Xe,markdown:le,jsonPayload:Ee})}catch{}return}await pe()}),R&&(C!=null&&C.length)){let X=()=>{var Ee;return(Ee=f.closest("[data-persona-root]"))!=null?Ee:document.body},le=()=>{$=ds({items:C.map(Ee=>({id:Ee.id,label:Ee.label})),onSelect:async Ee=>{let{markdown:Xe,jsonPayload:Ze,id:wt}=Se(),dt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{dt?await dt({actionId:Ee,artifactId:wt,markdown:Xe,jsonPayload:Ze}):Ee==="markdown"||Ee==="md"?await navigator.clipboard.writeText(Xe):Ee==="json"||Ee==="source"?await navigator.clipboard.writeText(Ze):await navigator.clipboard.writeText(Xe||Ze)}catch{}},anchor:F!=null?F:R,position:"bottom-right",portal:X()})};f.isConnected?le():requestAnimationFrame(le),R.addEventListener("click",Ee=>{Ee.stopPropagation(),$==null||$.toggle()})}N.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}de()}),Z.addEventListener("click",()=>{var X;u(),(X=e.onDismiss)==null||X.call(e)});let ee=()=>{o&&(W.setAttribute("aria-pressed",v==="rendered"?"true":"false"),T.setAttribute("aria-pressed",v==="source"?"true":"false"))};W.addEventListener("click",()=>{v="rendered",ee(),de()}),T.addEventListener("click",()=>{v="source",ee(),de()});let ve=y("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");o?(g.replaceChildren(),M.append(W,T),F?k.append(F,N,Z):k.append(O,N,Z),g.append(M,ve,k),ee()):(g.appendChild(m),g.appendChild(x)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Ie=y("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"),ce=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ie.style.paddingLeft=s,Ie.style.paddingRight=s,ce.style.padding=s),f.appendChild(g),f.appendChild(Ie),f.appendChild(ce);let ue=[],oe=null,se=!1,de=()=>{var Xe,Ze,wt,dt;let X=o&&ue.length<=1;Ie.classList.toggle("persona-hidden",X),Ie.replaceChildren();for(let Ye of ue){let He=y("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");He.type="button",He.textContent=Ye.title||Ye.id.slice(0,8),Ye.id===oe&&He.classList.add("persona-bg-persona-container","persona-border-persona-border"),He.addEventListener("click",()=>e.onSelect(Ye.id)),Ie.appendChild(He)}ce.replaceChildren();let le=oe&&ue.find(Ye=>Ye.id===oe)||ue[ue.length-1];if(!le)return;if(o){let Ye=le.artifactType==="markdown"?"MD":(Xe=le.component)!=null?Xe:"Component",K=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ve.textContent=`${K} \xB7 ${Ye}`}else m.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&v==="source"){let He=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");He.textContent=(Ze=le.markdown)!=null?Ze:"",ce.appendChild(He);return}let Ye=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ye.innerHTML=d((wt=le.markdown)!=null?wt:""),ce.appendChild(Ye);return}let Ee=le.component?Fo.get(le.component):void 0;if(Ee){let He={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let K=Ee((dt=le.props)!=null?dt:{},He);if(K){ce.appendChild(K);return}}catch{}}ce.appendChild(vv(le))},$e=()=>{var le;let X=ue.length>0;if(f.classList.toggle("persona-hidden",!X),c){let Ee=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,Ze=((le=Ee==null?void 0:Ee.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;X&&Ze&&se?(c.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:c,update(X){var le,Ee,Xe;ue=X.artifacts,oe=(Xe=(Ee=X.selectedId)!=null?Ee:(le=X.artifacts[X.artifacts.length-1])==null?void 0:le.id)!=null?Xe:null,ue.length>0&&(se=!0),de(),$e()},setMobileOpen(X){se=X,!X&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):$e()}}}function sr(t){var e,n;return((n=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:n.enabled)===!0}function Em(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!sr(e))return;let n=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",r)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function xv(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ti(t,e){var d,c,u,f,g,m,x,v,M,W;if(!sr(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),xv(t),Em(t,e);return}let n=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;t.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(f=n==null?void 0:n.paneWidth)!=null?f:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let o=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(W=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:W.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Em(t,e)}var Mm=["panel","seamless"];function ni(t,e){var i,d,c,u,f,g;for(let m of Mm)t.classList.remove(`persona-artifact-appearance-${m}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!sr(e))return;let n=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Mm.includes(r)?r:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=n==null?void 0:n.paneShadow)==null?void 0:f.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let m=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;m&&t.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function km(t,e){var n,r,o;return!e||!sr(t)?!1:((o=(r=(n=t.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function wv(t,e){if(!(t!=null&&t.trim()))return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Cv(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Av(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Sv(t,e,n,r){let o=t-r-2*e-n;return Math.max(0,o)}function Lm(t,e){var a;let r=(a=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Pm(t,e,n,r,o,s){let a=wv(o,200),i=Sv(e,n,r,200);i=Math.max(a,i);let d=Cv(s);return d!==null&&(i=Math.min(i,d)),Av(t,a,i)}var Im={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"}},Yi=(t,e,n,r)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,v,M;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(v=Im[a])!=null?v:Im.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let W=y("p","persona-text-sm persona-text-persona-muted");W.textContent=i.description,d.appendChild(W)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(W=>{var C,L;let T=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${e.id}-${a}-${W.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=W.label,T.appendChild(k);let E=(C=W.type)!=null?C:"text",P;E==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=E),P.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",P.id=`${e.id}-${a}-${W.name}`,P.name=W.name,P.placeholder=(L=W.placeholder)!=null?L:"",W.required&&(P.required=!0),T.appendChild(P),u.appendChild(T)});let f=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=y("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");m.type="submit",m.textContent=(M=i.submitLabel)!=null?M:"Submit",f.appendChild(g),f.appendChild(m),u.appendChild(f),s.replaceChildren(d,u),u.addEventListener("submit",async W=>{var P,C;W.preventDefault();let T=(P=n.formEndpoint)!=null?P:"/form",k=new FormData(u),E={};k.forEach((L,F)=>{E[F]=L}),E.type=a,m.disabled=!0,g.textContent="Submitting\u2026";try{let L=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let F=await L.json();g.textContent=(C=F.message)!=null?C:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(L){g.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Zi=class{constructor(){this.plugins=new Map}register(e){var n;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(n=e.onRegister)==null||n.call(e)}unregister(e){var r;let n=this.plugins.get(e);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let r=new Set(e.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var n;return(n=e.onUnregister)==null?void 0:n.call(e)}),this.plugins.clear()}},el=new Zi;var Wm=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:n,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Tv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Ev=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(n,o+1)}return null},nl=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Tv(t),n=Ev(e);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},tl=t=>typeof t=="string"?t:t==null?"":String(t),ra={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:tl(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let n=t.payload,r=tl(n.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:tl(n.text)}}},Rm=t=>Array.isArray(t)?t.map(e=>String(e)):[],rl=t=>{let e=new Set(Rm(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Rm(t.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};t.emit("action:detected",d);for(let c of t.handlers)if(c)try{let u=()=>{t.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var Mv=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},kv=t=>t.map(e=>({...e,streaming:!1})),Lv=t=>t.map(e=>({...e,status:"complete"})),Hm=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Mv(n.getItem(t)):null},save:n=>{let r=e();if(r)try{let o={...n,messages:n.messages?kv(n.messages):void 0,artifacts:n.artifacts?Lv(n.artifacts):void 0};r.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as VA,STR as KA,OBJ as GA}from"partial-json";function Bm(t,e){let{config:n,message:r,onPropsUpdate:o}=e,s=Fo.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function Dm(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Nm(t){let e=Dm(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Fm(t){let e=Dm(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var Pv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Om(t){let{onSubmit:e,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Pv}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,m.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,m.appendChild(v),g.appendChild(m);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let W=[];for(let C=1;C<=5;C++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),L.title=c[C-1],L.dataset.rating=String(C),L.innerHTML=`
31
31
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
32
32
  <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>
33
33
  </svg>
34
- `,I.addEventListener("click",()=>{f=C,T.forEach((D,B)=>{let E=B<C;D.classList.toggle("selected",E),D.setAttribute("aria-checked",B===C-1?"true":"false")})}),T.push(I),P.appendChild(I)}g.appendChild(P);let M=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=s,M.rows=3,M.setAttribute("aria-label","Additional comments"),C.appendChild(M),g.appendChild(C)}let N=document.createElement("div");N.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=i,k.addEventListener("click",()=>{t==null||t(),m.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let C=(M==null?void 0:M.value.trim())||void 0;await e(f,C),m.remove()}catch(C){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),N.appendChild(k),N.appendChild(W),g.appendChild(N),m.appendChild(g),m}function Wm(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:m="Very likely"}=n,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let P=document.createElement("p");P.className="persona-feedback-subtitle",P.textContent=o,v.appendChild(P),u.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let N=document.createElement("span");N.className="persona-feedback-label-low",N.textContent=c;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=m,M.appendChild(N),M.appendChild(k);let W=document.createElement("div");W.className="persona-feedback-numbers";let C=[];for(let z=0;z<=10;z++){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 ${z} out of 10`),j.textContent=String(z),j.dataset.rating=String(z),z<=6?j.classList.add("persona-feedback-detractor"):z<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{g=z,C.forEach((te,We)=>{te.classList.toggle("selected",We===z),te.setAttribute("aria-checked",We===z?"true":"false")})}),C.push(j),W.appendChild(j)}T.appendChild(M),T.appendChild(W),u.appendChild(T);let I=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),z.appendChild(I),u.appendChild(z)}let D=document.createElement("div");D.className="persona-feedback-actions";let B=document.createElement("button");B.type="button",B.className="persona-feedback-btn persona-feedback-btn-skip",B.textContent=i,B.addEventListener("click",()=>{t==null||t(),f.remove()});let E=document.createElement("button");return E.type="button",E.className="persona-feedback-btn persona-feedback-btn-submit",E.textContent=a,E.addEventListener("click",async()=>{if(g===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}E.disabled=!0,E.textContent="Submitting...";try{let z=(I==null?void 0:I.value.trim())||void 0;await e(g,z),f.remove()}catch(z){E.disabled=!1,E.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),D.appendChild(B),D.appendChild(E),u.appendChild(D),f.appendChild(u),f}var ds="persona-chat-history",hv=30*1e3,yv={"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 bv(n){var r,o,s;if(!n)return[];let e=[],t=Array.from((r=n.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=yv[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function Za(n){if(!n)return!1;let e=n.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function vv(n){var e,t,r,o,s,a,i,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=n.storage)!=null?e:"session",keyPrefix:(t=n.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=n.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function xv(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var el=n=>!n||typeof n!="object"?{}:{...n},Rm=n=>n.map(e=>({...e,streaming:!1})),Hm=(n,e,t)=>{let r=n!=null&&n.markdown?da(n.markdown):null,o=pa(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.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."),s=>{var m,f,g;let a=(m=s.text)!=null?m:"",i=(f=s.message.rawContent)!=null?f:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&t&&t())}let d=To()!==null,c;if(n!=null&&n.postprocessMessage){let u=n.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});c=o?o(u):u}else if(r){let u=s.streaming?Np(a):a,v=r(u);c=o&&d?o(v):v}else c=oo(a);return c}};function Bm(n){var i,d,c,m;let e=b("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(m=n==null?void 0:n.iconStrokeWidth)!=null?m:.5,a=Ce(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let f=b("span","persona-drop-overlay-label");f.textContent=n.label,e.appendChild(f)}return e}var Dm=(n,e,t)=>{var Hl,Bl,Dl,Nl,Fl,Ol,_l,$l,Ul,ql,zl,jl,Vl,Kl,Gl,Ql,Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=Pu(e),o=Xi.getForInstance(r.plugins);r.components&&Ho.registerAll(r.components);let s=Sm(),i=r.persistState===!1?null:(Hl=r.storageAdapter)!=null?Hl:Mm(),d={},c=null,m=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(m=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(d=el(h.metadata)),(Bl=h.messages)!=null&&Bl.length&&(r={...r,initialMessages:h.messages}),(Dl=h.artifacts)!=null&&Dl.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Nl=h.selectedArtifactId)!=null?Nl:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(Fl=l.messages)!=null&&Fl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>d,u=l=>{var h;d=(h=l({...d}))!=null?h:{},Yr()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Yi],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ys.message,Ys.messageAndClick],P=Zi({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});P.syncFromMetadata();let T=(_l=(Ol=r.launcher)==null?void 0:Ol.enabled)!=null?_l:!0,M=(Ul=($l=r.launcher)==null?void 0:$l.autoExpand)!=null?Ul:!1,N=(ql=r.autoFocusInput)!=null?ql:!1,k=M,W=T,C=(jl=(zl=r.layout)==null?void 0:zl.header)==null?void 0:jl.layout,I=!1,D=()=>Vs(r),B=()=>T||D(),E=D()?!1:T?M:!0,z=!1,j=null,te=()=>{z=!0,j&&clearTimeout(j),j=setTimeout(()=>{z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),z=!1)},1e4)},We=Hm(r,P,te),$e=(Kl=(Vl=r.features)==null?void 0:Vl.showReasoning)!=null?Kl:!0,ve=(Ql=(Gl=r.features)==null?void 0:Gl.showToolCalls)!=null?Ql:!0,Pe=(Jl=(Xl=r.features)==null?void 0:Xl.showEventStreamToggle)!=null?Jl:!1,Oe=(Zl=(Yl=r.features)==null?void 0:Yl.scrollToBottom)!=null?Zl:{},Ae=(tc=(ec=r.features)==null?void 0:ec.scrollBehavior)!=null?tc:{},ne=`${(rc=typeof r.persistState=="object"?(nc=r.persistState)==null?void 0:nc.keyPrefix:void 0)!=null?rc:"persona-"}event-stream`,Q=Pe?new Xs(ne):null,ae=(ac=(sc=(oc=r.features)==null?void 0:oc.eventStream)==null?void 0:sc.maxEvents)!=null?ac:2e3,fe=Pe?new Qs(ae,Q):null,re=Pe?new Js:null,V=null,ee=!1,Ue=null,J=0;Q==null||Q.open().then(()=>fe==null?void 0:fe.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ie={onCopy:l=>{var p,h;s.emit("message:copy",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;s.emit("message:feedback",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.messageId,l.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},Le=(ic=r.statusIndicator)!=null?ic:{},at=l=>{var p,h,y,A;return l==="idle"?(p=Le.idleText)!=null?p:vn.idle:l==="connecting"?(h=Le.connectingText)!=null?h:vn.connecting:l==="connected"?(y=Le.connectedText)!=null?y:vn.connected:l==="error"?(A=Le.errorText)!=null?A:vn.error:vn[l]};function it(l,p,h,y){if(y==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=p,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=p}let nt=tm({config:r,showClose:B()}),{wrapper:Me,panel:de,pillRoot:Qe}=nt.shell,X=nt.panelElements,{container:le,body:xe,messagesWrapper:ze,suggestions:Lt,textarea:Se,sendButton:ue,sendButtonWrapper:gn,composerForm:Pt,statusText:nn,introTitle:fr,introSubtitle:fn,closeButton:je,iconHolder:S,headerTitle:pe,headerSubtitle:ke,header:Te,footer:Re,actionsRow:Ye,leftActions:Ke,rightActions:pt}=X,It=X.setSendButtonMode,U=X.micButton,rt=X.micButtonWrapper,K=X.attachmentButton,ce=X.attachmentButtonWrapper,Ee=X.attachmentInput,bt=X.attachmentPreviewsContainer;le.classList.add("persona-relative"),xe.classList.add("persona-relative");let Jt=12,Yt=()=>{var l;return(l=Oe.label)!=null?l:""},dn=()=>{var l;return(l=Oe.iconName)!=null?l:"arrow-down"},Rt=()=>Oe.enabled!==!1,Ze=()=>{var l;return(l=Ae.mode)!=null?l:"follow"},Wt=()=>{var l;return(l=Ae.anchorTopOffset)!=null?l:16},lt=b("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");lt.type="button",lt.style.display="none",lt.setAttribute("data-persona-scroll-to-bottom","true");let Vt=b("span","persona-flex persona-items-center"),Xn=b("span",""),Cn=b("span","");Cn.setAttribute("data-persona-scroll-to-bottom-count",""),Cn.style.display="none",lt.append(Vt,Xn,Cn),le.appendChild(lt);let Zt=b("div","persona-stream-anchor-spacer");Zt.setAttribute("aria-hidden","true"),Zt.setAttribute("data-persona-anchor-spacer",""),Zt.style.flexShrink="0",Zt.style.pointerEvents="none",Zt.style.height="0px",xe.appendChild(Zt);let Pn=()=>{let p=Re.style.display==="none"?0:Re.offsetHeight;lt.style.bottom=`${p+Jt}px`};Pn();let hr=()=>{let l=!!Yt();lt.setAttribute("aria-label",Yt()||"Jump to latest"),lt.title=Yt(),lt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Vt.innerHTML="";let p=Ce(dn(),"14px","currentColor",2);p?(Vt.appendChild(p),Vt.style.display=""):Vt.style.display="none",Xn.textContent=Yt(),Xn.style.display=l?"":"none"};hr();let vt=null,Dn=null,yr=o.find(l=>l.renderHeader);if(yr!=null&&yr.renderHeader){let l=yr.renderHeader({config:r,defaultRenderer:()=>{let p=Wo({config:r,showClose:B()});return Ks(le,p,r),p.header},onClose:()=>_t(!1,"user")});if(l){let p=le.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Te=l,nt.header.element=l)}}let Lr=()=>{var p,h,y,A;if(!fe)return;if(ee=!0,!V&&fe&&(V=gm({buffer:fe,getFullHistory:()=>fe.getAllFromStore(),onClose:()=>ar(),config:r,plugins:o,getThroughput:()=>{var R;return(R=re==null?void 0:re.getMetric())!=null?R:{status:"idle"}}})),V&&(xe.style.display="none",(p=Re.parentNode)==null||p.insertBefore(V.element,Re),V.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let R=(A=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:A.toggleButtonActive;R&&R.split(/\s+/).forEach(q=>q&&ht.classList.add(q))}let l=()=>{if(!ee)return;let R=Date.now();R-J>=200&&(V==null||V.update(),J=R),Ue=requestAnimationFrame(l)};J=0,Ue=requestAnimationFrame(l),Xe(),s.emit("eventStream:opened",{timestamp:Date.now()})},ar=()=>{var l,p,h;if(ee){if(ee=!1,V&&V.element.remove(),xe.style.display="",ht){ht.style.boxShadow="";let y=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(A=>A&&ht.classList.remove(A))}Ue!==null&&(cancelAnimationFrame(Ue),Ue=null),Xe(),s.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(Pe){let l=(cc=(lc=r.features)==null?void 0:lc.eventStream)==null?void 0:cc.classNames,p="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!=null&&l.toggleButton?" "+l.toggleButton:"");ht=b("button",p),ht.style.width="28px",ht.style.height="28px",ht.style.color=Ln.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=Ce("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let y=X.clearChatButtonWrapper,A=X.closeButtonWrapper,R=y||A;R&&R.parentNode===Te?Te.insertBefore(ht,R):Te.appendChild(ht),ht.addEventListener("click",()=>{ee?ar():Lr()})}let co=l=>{var A,R,q,F,H;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(A=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?A:l.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let oe=l.querySelector("[data-persona-composer-form]");oe!=null&&oe.parentNode?oe.parentNode.insertBefore(h,oe):l.insertBefore(h,l.firstChild)}if(!((R=l.querySelector("[data-persona-composer-attachment-input]"))!=null?R:l.querySelector('input[type="file"]'))){let oe=b("input");oe.type="file",oe.setAttribute("data-persona-composer-attachment-input",""),oe.accept=((q=p.allowedTypes)!=null?q:$r).join(","),oe.multiple=((F=p.maxFiles)!=null?F:4)>1,oe.style.display="none",oe.setAttribute("aria-label",(H=p.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(oe)}},br=o.find(l=>l.renderComposer);if(br!=null&&br.renderComposer){let l=r.composer,p=br.renderComposer({config:r,defaultRenderer:()=>Ka({config:r}).footer,onSubmit:h=>{var q;if(!O||O.isStreaming())return;let y=h.trim(),A=(q=vt==null?void 0:vt.hasAttachments())!=null?q:!1;if(!y&&!A)return;pl();let R;A&&(R=[],R.push(...vt.getContentParts()),y&&R.push(Ti(y))),O.sendMessage(y,{contentParts:R}),A&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ee==null||Ee.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((dc=r.voiceRecognition)==null?void 0:dc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});p&&(nt.replaceComposer(p),Re=nt.composer.footer)}let po=l=>{let p=(...se)=>{for(let Y of se){let ye=l.querySelector(Y);if(ye)return ye}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(Pt=h),y&&(Se=y),A&&(ue=A),R&&(U=R,rt=R.parentElement),q&&(nn=q);let F=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Lt=F);let H=p("[data-persona-composer-attachment-button]",".persona-attachment-button");H&&(K=H,ce=H.parentElement),Ee=p("[data-persona-composer-attachment-input]",'input[type="file"]'),bt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(Ye=oe)};co(Re),po(Re);let In=(fc=(pc=r.layout)==null?void 0:pc.contentMaxWidth)!=null?fc:D()?(gc=(mc=(uc=r.launcher)==null?void 0:uc.composerBar)==null?void 0:mc.contentMaxWidth)!=null?gc:"720px":void 0;if(In&&(ze.style.maxWidth=In,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%"),In&&Pt&&!D()&&(Pt.style.maxWidth=In,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),In&&Lt&&!D()&&(Lt.style.maxWidth=In,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),In&&bt&&!D()&&(bt.style.maxWidth=In,bt.style.marginLeft="auto",bt.style.marginRight="auto"),(hc=r.attachments)!=null&&hc.enabled&&Ee&&bt){vt=Fs.fromConfig(r.attachments),vt.setPreviewsContainer(bt),Ee.addEventListener("change",h=>{let y=h.target;vt==null||vt.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=Bm(l);le.appendChild(p)}(()=>{var y,A;let l=(A=(y=r.layout)==null?void 0:y.slots)!=null?A:{},p=R=>{switch(R){case"body-top":return le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ze;case"footer-top":return Lt;case"composer":return Pt;case"footer-bottom":return nn;default:return null}},h=(R,q)=>{var F;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")Te.insertBefore(q,Te.firstChild);else if(R==="header-right")Te.appendChild(q);else{let H=Te.querySelector(".persona-flex-col");H?(F=H.parentNode)==null||F.insertBefore(q,H.nextSibling):Te.appendChild(q)}break;case"body-top":{let H=xe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(q):xe.insertBefore(q,xe.firstChild);break}case"body-bottom":xe.appendChild(q);break;case"footer-top":Lt.replaceWith(q);break;case"footer-bottom":nn.replaceWith(q);break;default:break}};for(let[R,q]of Object.entries(l))if(q)try{let F=q({config:r,defaultContent:()=>p(R)});F&&h(R,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,F)}})();let zr=l=>{var q,F;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let A=y.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-bubble-type");if(R==="reasoning")is.has(A)?is.delete(A):is.add(A),om(A,y);else if(R==="tool")ls.has(A)?ls.delete(A):ls.add(A),sm(A,y,r);else if(R==="approval"){let H=r.approval!==!1?r.approval:void 0,oe=((q=H==null?void 0:H.detailsDisplay)!=null?q:"collapsed")==="expanded",se=(F=Ga.get(A))!=null?F:oe;Ga.set(A,!se),cm(A,y,r)}Ar.delete(A)};ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),zr(l))}),ze.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),zr(l))}),ze.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let h=ze.getRootNode(),y=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let A=y.toString(),R=Du(A);!R||R===A||(p.setData("text/plain",R),l.preventDefault())});let Pr=new Map,jr=null,Vr="idle",uo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},mo=(l,p)=>{let{icon:h,label:y}=uo[p];l.setAttribute("aria-label",y),l.title=y,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let A=Ce(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},Kr=()=>{ze.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var R;let h=p.closest("[data-actions-for]"),y=(R=h==null?void 0:h.getAttribute("data-actions-for"))!=null?R:null;mo(p,y&&y===jr?Vr:"idle")})};ze.addEventListener("click",l=>{var q;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let A=y.getAttribute("data-actions-for");if(!A)return;let R=h.getAttribute("data-action");if(R==="copy"){let H=O.getMessages().find(oe=>oe.id===A);if(H&&ie.onCopy){let oe=H.content||"";navigator.clipboard.writeText(oe).then(()=>{h.classList.add("persona-message-action-success");let se=Ce("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=Ce("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),ie.onCopy(H)}}else if(R==="read-aloud")O.toggleReadAloud(A);else if(R==="upvote"||R==="downvote"){let H=((q=Pr.get(A))!=null?q:null)===R,oe=R==="upvote"?"thumbs-up":"thumbs-down";if(H){Pr.delete(A),h.classList.remove("persona-message-action-active");let se=Ce(oe,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=R==="upvote"?"downvote":"upvote",Y=y.querySelector(`[data-action="${se}"]`);if(Y){Y.classList.remove("persona-message-action-active");let _e=Ce(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);_e&&(Y.innerHTML="",Y.appendChild(_e))}Pr.set(A,R),h.classList.add("persona-message-action-active");let ye=Ce(oe,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let we=O.getMessages().find(tt=>tt.id===A);we&&ie.onFeedback&&ie.onFeedback({type:R,messageId:we.id,message:we})}}}),ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let A=y.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-approval-action");if(!R)return;let q=R==="approve"?"approved":"denied",H=O.getMessages().find(se=>se.id===A);if(!(H!=null&&H.approval))return;let oe=y.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?O.resolveWebMcpApproval(A,q):O.resolveApproval(H.approval,q)});let wt=null,Nn=null,Fn={artifacts:[],selectedId:null},An=!1,At={current:null};ze.addEventListener("click",l=>{var Y,ye,Ne,we,tt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ne=(ye=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Ne.call(ye,{type:"download",artifactId:y}))===!0)return;let R=O.getArtifactById(y),q=R==null?void 0:R.markdown,F=(R==null?void 0:R.title)||"artifact";if(!q){let _e=h.closest("[data-open-artifact]"),mt=_e==null?void 0:_e.closest("[data-message-id]"),ot=mt==null?void 0:mt.getAttribute("data-message-id");if(ot){let Ie=O.getMessages().find(qe=>qe.id===ot);if(Ie!=null&&Ie.rawContent)try{let qe=JSON.parse(Ie.rawContent);q=(we=qe==null?void 0:qe.props)==null?void 0:we.markdown,F=((tt=qe==null?void 0:qe.props)==null?void 0:tt.title)||F}catch{}}}if(!q)return;let H=new Blob([q],{type:"text/markdown"}),oe=URL.createObjectURL(H),se=document.createElement("a");se.href=oe,se.download=`${F}.md`,se.click(),URL.revokeObjectURL(oe)}),ze.addEventListener("click",l=>{var R,q,F;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((F=(q=(R=r.features)==null?void 0:R.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:F.call(q,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),An=!1,O.selectArtifact(y),$n())}),ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Jn=X.composerOverlay,Yn=(l,p,h)=>{var F,H,oe,se;let y=p.trim();if(!y||!At.current)return;let A=(F=l.getAttribute("data-tool-call-id"))!=null?F:"",R=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:y,answers:h.structured,values:(H=h.values)!=null?H:h.source==="multi"?y.split(", "):[y],isFreeText:R,source:h.source},bubbles:!0,composed:!0})),Zo(Jn,A);let q=At.current.getMessages().find(Y=>{var ye;return((ye=Y.toolCall)==null?void 0:ye.id)===A});(oe=q==null?void 0:q.agentMetadata)!=null&&oe.awaitingLocalTool?At.current.resolveAskUserQuestion(q,(se=h.structured)!=null?se:y):At.current.sendMessage(y)},On=l=>{var A;let p=At.current;if(!p)return;let h=(A=l.getAttribute("data-tool-call-id"))!=null?A:"",y=p.getMessages().find(R=>{var q;return((q=R.toolCall)==null?void 0:q.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:ga(l,y),currentIndex:or(l)})},Gr=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ir=l=>{var A,R,q;if(((R=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:R.groupedAutoAdvance)===!1)return;let p=or(l),h=Yo(l);if(p>=h-1)return;let y=(q=At.current)==null?void 0:q.getMessages().find(F=>{var H;return((H=F.toolCall)==null?void 0:H.id)===l.getAttribute("data-tool-call-id")});y&&(ha(l,y,r,p+1),On(l))};Jn.addEventListener("click",l=>{var R,q,F,H,oe,se,Y,ye,Ne,we,tt,_e,mt,ot;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let He=(R=y.getAttribute("data-tool-call-id"))!=null?R:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),Zo(Jn,He);let Ie=(q=At.current)==null?void 0:q.getMessages().find(qe=>{var Ve;return((Ve=qe.toolCall)==null?void 0:Ve.id)===He});(F=Ie==null?void 0:Ie.agentMetadata)!=null&&F.awaitingLocalTool&&((H=At.current)==null||H.markAskUserQuestionResolved(Ie),(oe=At.current)==null||oe.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(A==="pick"){let He=h.getAttribute("data-option-label");if(!He)return;let Ie=y.getAttribute("data-multi-select")==="true",qe=so(y);if(qe&&Ie){let Ve=ko(y)[or(y)],yt=new Set(Array.isArray(Ve)?Ve:[]);yt.has(He)?yt.delete(He):yt.add(He),ao(y,Array.from(yt)),On(y);return}if(qe){ao(y,He),On(y),Ir(y);return}if(Ie){let Ve=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ve?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ve);let yt=y.querySelector('[data-ask-user-action="submit-multi"]');yt&&(yt.disabled=vi(y).length===0);return}Yn(y,He,{source:"pick",values:[He]});return}if(A==="submit-multi"){let He=vi(y);if(He.length===0)return;Yn(y,He.join(", "),{source:"multi",values:He});return}if(A==="open-free-text"){let He=y.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let Ie=He.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(A==="focus-free-text"){let He=y.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(A==="submit-free-text"){let He=y.querySelector('[data-ask-free-text-input="true"]'),Ie=(se=He==null?void 0:He.value)!=null?se:"";if(!Ie.trim())return;if(so(y)){ao(y,Ie.trim()),On(y),Ir(y);return}Yn(y,Ie,{source:"free-text"});return}if(A==="next"||A==="back"){if(!At.current)return;let He=(Y=y.getAttribute("data-tool-call-id"))!=null?Y:"",Ie=At.current.getMessages().find(De=>{var Be;return((Be=De.toolCall)==null?void 0:Be.id)===He});if(!Ie)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ve=(Ne=(ye=qe==null?void 0:qe.value)==null?void 0:ye.trim())!=null?Ne:"";if(Ve){let De=ko(y)[or(y)];(typeof De!="string"||De!==Ve)&&ao(y,Ve)}let yt=A==="next"?1:-1,L=or(y)+yt;ha(y,Ie,r,L),On(y);return}if(A==="submit-all"){if(!At.current)return;let He=(we=y.getAttribute("data-tool-call-id"))!=null?we:"",Ie=At.current.getMessages().find(De=>{var Be;return((Be=De.toolCall)==null?void 0:Be.id)===He});if(!Ie)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ve=(_e=(tt=qe==null?void 0:qe.value)==null?void 0:tt.trim())!=null?_e:"";Ve&&ao(y,Ve);let yt=ga(y,Ie);At.current.persistAskUserQuestionProgress(Ie,{answers:yt,currentIndex:or(y)});let L=Gr(yt);Yn(y,L||"(submitted)",{source:"submit-all",structured:yt});return}if(A==="skip"){if(!At.current)return;let He=(mt=y.getAttribute("data-tool-call-id"))!=null?mt:"",Ie=At.current.getMessages().find(Be=>{var me;return((me=Be.toolCall)==null?void 0:me.id)===He});if(!Ie)return;let qe=so(y),Ve=or(y),yt=Yo(y),L=Ve>=yt-1;if(!qe){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),Zo(Jn,He),(ot=Ie.agentMetadata)!=null&&ot.awaitingLocalTool&&(At.current.markAskUserQuestionResolved(Ie),At.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}ao(y,"");let De=y.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),L){let Be=ga(y,Ie),me=Gr(Be);Yn(y,me||"(skipped)",{source:"submit-all",structured:Be});return}ha(y,Ie,r,Ve+1),On(y);return}}),Jn.addEventListener("keydown",l=>{var R;if(l.key!=="Enter")return;let h=l.target;if(!((R=h.matches)!=null&&R.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let A=h.value;if(A.trim()){if(so(y)){ao(y,A.trim()),On(y),Ir(y);return}Yn(y,A,{source:"free-text"})}});let Qr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=Jn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),R=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];R&&(l.preventDefault(),R.click())};document.addEventListener("keydown",Qr);let _n=null,Ht=null,Sn=null,Zn=null,Xr=()=>{};function Wr(){Zn==null||Zn(),Zn=null}let Jr=()=>{var q;if(!_n||!Ht)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((q=n.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){Ht.style.removeProperty("position"),Ht.style.removeProperty("left"),Ht.style.removeProperty("top"),Ht.style.removeProperty("bottom"),Ht.style.removeProperty("width"),Ht.style.removeProperty("z-index");return}let y=_n.firstElementChild;if(!y||y===Ht)return;let A=10;Ht.style.position="absolute",Ht.style.top="0",Ht.style.bottom="0",Ht.style.width=`${A}px`,Ht.style.zIndex="5";let R=y.offsetWidth-A/2;Ht.style.left=`${Math.max(0,R)}px`},vr=()=>{},$n=()=>{var h,y,A,R,q;if(!wt||!sr(r))return;Ja(n,r),Ya(n,r),vr();let l=(R=(A=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:A.narrowHostMaxWidth)!=null?R:520,p=de.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),wt.update(Fn),An?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(q=wt.backdrop)==null||q.classList.add("persona-hidden")):Fn.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),Xr()};if(sr(r)){de.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(le),wt=ym(r,{onSelect:h=>{var y;return(y=At.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{An=!0,$n()}}),wt.element.classList.add("persona-hidden"),_n=p,p.appendChild(l),p.appendChild(wt.element),wt.backdrop&&de.appendChild(wt.backdrop),de.appendChild(p),Xr=()=>{var y,A,R,q;if(!_n||!wt)return;if(!(((R=(A=(y=r.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:R.resizable)===!0)){Sn==null||Sn(),Sn=null,Wr(),Ht&&(Ht.remove(),Ht=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!Ht){let F=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");F.setAttribute("role","separator"),F.setAttribute("aria-orientation","vertical"),F.setAttribute("aria-label","Resize artifacts panel"),F.tabIndex=0;let H=n.ownerDocument,oe=(q=H.defaultView)!=null?q:window,se=Y=>{var mt,ot;if(!wt||Y.button!==0||n.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;Y.preventDefault(),Wr();let ye=Y.clientX,Ne=wt.element.getBoundingClientRect().width,we=(ot=(mt=r.features)==null?void 0:mt.artifacts)==null?void 0:ot.layout,tt=He=>{let Ie=_n.getBoundingClientRect().width,qe=n.classList.contains("persona-artifact-appearance-seamless"),Ve=qe?0:wm(_n,oe),yt=qe?0:F.getBoundingClientRect().width||6,L=Ne-(He.clientX-ye),De=Cm(L,Ie,Ve,yt,we==null?void 0:we.resizableMinWidth,we==null?void 0:we.resizableMaxWidth);wt.element.style.width=`${De}px`,wt.element.style.maxWidth="none",Jr()},_e=()=>{H.removeEventListener("pointermove",tt),H.removeEventListener("pointerup",_e),H.removeEventListener("pointercancel",_e),Zn=null;try{F.releasePointerCapture(Y.pointerId)}catch{}};Zn=_e,H.addEventListener("pointermove",tt),H.addEventListener("pointerup",_e),H.addEventListener("pointercancel",_e);try{F.setPointerCapture(Y.pointerId)}catch{}};F.addEventListener("pointerdown",se),Ht=F,_n.insertBefore(F,wt.element),Sn=()=>{F.removeEventListener("pointerdown",se)}}if(Ht){let F=Fn.artifacts.length>0&&!An;Ht.classList.toggle("persona-hidden",!F),Jr()}},vr=()=>{var oe,se,Y,ye,Ne,we,tt,_e,mt,ot,He,Ie,qe,Ve;if(!T||!wt||((se=(oe=r.launcher)==null?void 0:oe.sidebarMode)!=null?se:!1)||mn(r)&&mr(r).reveal==="emerge")return;let y=(Y=n.ownerDocument.defaultView)!=null?Y:window,A=(Ne=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Ne:!0,R=(tt=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?tt:640;if(A&&y.innerWidth<=R||!xm(r,T))return;let q=(ot=(mt=(_e=r.launcher)==null?void 0:_e.width)!=null?mt:r.launcherWidth)!=null?ot:Ur,F=(Ve=(qe=(Ie=(He=r.features)==null?void 0:He.artifacts)==null?void 0:Ie.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ve:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!An?(de.style.width=F,de.style.maxWidth=F):(de.style.width=q,de.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{$n()}),Nn.observe(de))}else de.appendChild(le),D()&&Qe&&(X.peekBanner&&Qe.appendChild(X.peekBanner),Qe.appendChild(Re));n.appendChild(Me),Qe&&n.appendChild(Qe);let he=()=>{var De,Be,me,Nt,Bt,qt,xt,$t,Vn,Xt,Ge,Et,tn,rr,Kn,bo,vo,Vo,Ko,zt,xo,no,ro,Or,wo,dr,Je,sn;if(D()){de.style.width="100%",de.style.maxWidth="100%";let Ot=(Be=(De=r.launcher)==null?void 0:De.composerBar)!=null?Be:{},Ft=Me.dataset.state==="expanded",gt=(me=Ot.expandedSize)!=null?me:"anchored";if(!(Ft&&gt!=="fullscreen")){le.style.background="",le.style.border="",le.style.borderRadius="",le.style.overflow="",le.style.boxShadow="";return}let Ct=(Bt=(Nt=r.theme)==null?void 0:Nt.components)==null?void 0:Bt.panel,yn=La(r),Tn=(En,Co)=>{var ws;return En==null||En===""?Co:(ws=os(yn,En))!=null?ws:En},Er="1px solid var(--persona-border)",cn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Mn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";le.style.background="var(--persona-surface, #ffffff)",le.style.border=Tn(Ct==null?void 0:Ct.border,Er),le.style.borderRadius=Tn(Ct==null?void 0:Ct.borderRadius,Mn),le.style.boxShadow=Tn(Ct==null?void 0:Ct.shadow,cn),le.style.overflow="hidden";return}let l=mn(r),p=(xt=(qt=r.launcher)==null?void 0:qt.sidebarMode)!=null?xt:!1,h=l||p||((Vn=($t=r.launcher)==null?void 0:$t.fullHeight)!=null?Vn:!1),y=((Xt=r.launcher)==null?void 0:Xt.enabled)===!1,A=(Et=(Ge=r.theme)==null?void 0:Ge.components)==null?void 0:Et.panel,R=La(r),q=(Ot,Ft)=>{var gt;return Ot==null||Ot===""?Ft:(gt=os(R,Ot))!=null?gt:Ot},F=(tn=n.ownerDocument.defaultView)!=null?tn:window,H=(Kn=(rr=r.launcher)==null?void 0:rr.mobileFullscreen)!=null?Kn:!0,oe=(vo=(bo=r.launcher)==null?void 0:bo.mobileBreakpoint)!=null?vo:640,se=F.innerWidth<=oe,Y=H&&se&&T,ye=(Ko=(Vo=r.launcher)==null?void 0:Vo.position)!=null?Ko:"bottom-left",Ne=ye==="bottom-left"||ye==="top-left",we=(xo=(zt=r.launcher)==null?void 0:zt.zIndex)!=null?xo:xn,tt=p||Y?"none":"1px solid var(--persona-border)",_e=Y?"none":p?Ne?"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))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Y&&(_e="none",tt="none");let mt=p||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ot=q(A==null?void 0:A.border,tt),He=q(A==null?void 0:A.shadow,_e),Ie=q(A==null?void 0:A.borderRadius,mt),qe=xe.scrollTop;n.style.cssText="",Me.style.cssText="",de.style.cssText="",le.style.cssText="",xe.style.cssText="",Re.style.cssText="";let Ve=()=>{var Ft;if(qe<=0)return;((Ft=xe.ownerDocument.defaultView)!=null?Ft:window).requestAnimationFrame(()=>{if(xe.scrollTop===qe)return;let gt=xe.scrollHeight-xe.clientHeight;gt<=0||(xe.scrollTop=Math.min(qe,gt))})};if(Y){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=`
34
+ `,L.addEventListener("click",()=>{f=C,W.forEach((F,O)=>{let R=O<C;F.classList.toggle("selected",R),F.setAttribute("aria-checked",O===C-1?"true":"false")})}),W.push(L),M.appendChild(L)}g.appendChild(M);let T=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),C.appendChild(T),g.appendChild(C)}let k=document.createElement("div");k.className="persona-feedback-actions";let E=document.createElement("button");E.type="button",E.className="persona-feedback-btn persona-feedback-btn-skip",E.textContent=i,E.addEventListener("click",()=>{n==null||n(),u.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(f===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let C=(T==null?void 0:T.value.trim())||void 0;await e(f,C),u.remove()}catch(C){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),k.appendChild(E),k.appendChild(P),g.appendChild(k),u.appendChild(g),u}function _m(t){let{onSubmit:e,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=t,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=o,x.appendChild(M),m.appendChild(x);let W=document.createElement("div");W.className="persona-feedback-rating persona-feedback-rating-nps",W.setAttribute("role","radiogroup"),W.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=c;let E=document.createElement("span");E.className="persona-feedback-label-high",E.textContent=u,T.appendChild(k),T.appendChild(E);let P=document.createElement("div");P.className="persona-feedback-numbers";let C=[];for(let $=0;$<=10;$++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${$} out of 10`),N.textContent=String($),N.dataset.rating=String($),$<=6?N.classList.add("persona-feedback-detractor"):$<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{g=$,C.forEach((Z,Se)=>{Z.classList.toggle("selected",Se===$),Z.setAttribute("aria-checked",Se===$?"true":"false")})}),C.push(N),P.appendChild(N)}W.appendChild(T),W.appendChild(P),m.appendChild(W);let L=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),$.appendChild(L),m.appendChild($)}let F=document.createElement("div");F.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=i,O.addEventListener("click",()=>{n==null||n(),f.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(g===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let $=(L==null?void 0:L.value.trim())||void 0;await e(g,$),f.remove()}catch($){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),F.appendChild(O),F.appendChild(R),m.appendChild(F),f.appendChild(m),f}var gs="persona-chat-history",Iv=30*1e3,Wv={"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 Rv(t){var r,o,s;if(!t)return[];let e=[],n=Array.from((r=t.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=Wv[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=t.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function ri(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function Hv(t){var e,n,r,o,s,a,i,d,c;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=t.storage)!=null?e:"session",keyPrefix:(n=t.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=t.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=t.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=t.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=t.clearOnChatClear)!=null?c:!0}:null}function Bv(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var ol=t=>!t||typeof t!="object"?{}:{...t},$m=t=>t.map(e=>({...e,streaming:!1})),Um=(t,e,n)=>{let r=t!=null&&t.markdown?ga(t.markdown):null,o=fa(t==null?void 0:t.sanitize);return t!=null&&t.postprocessMessage&&o&&(t==null?void 0:t.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."),s=>{var u,f,g;let a=(u=s.text)!=null?u:"",i=(f=s.message.rawContent)!=null?f:null;if(e){let m=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});m!==null&&(a=m.text,m.persist||(s.message.__skipPersist=!0),m.resubmit&&!s.streaming&&n&&n())}let d=ko()!==null,c;if(t!=null&&t.postprocessMessage){let m=t.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});c=o?o(m):m}else if(r){let m=s.streaming?$p(a):a,x=r(m);c=o&&d?o(x):x}else c=ao(a);return c}};function zm(t){var i,d,c,u;let e=y("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=(i=t==null?void 0:t.iconName)!=null?i:"upload",r=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(c=t==null?void 0:t.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(u=t==null?void 0:t.iconStrokeWidth)!=null?u:.5,a=fe(n,r,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let f=y("span","persona-drop-overlay-label");f.textContent=t.label,e.appendChild(f)}return e}var qm=(t,e,n)=>{var Fl,Ol,_l,$l,Ul,zl,ql,jl,Vl,Kl,Gl,Ql,Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc;if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let r=Hu(e),o=el.getForInstance(r.plugins),{plugin:s,teardown:a}=ym();r.components&&Fo.registerAll(r.components);let i=Wm(),c=r.persistState===!1?null:(Fl=r.storageAdapter)!=null?Fl:Hm(),u={},f=null,g=!1,m=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:b}=p;return b&&(g=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")f=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return m(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=m(p);h.metadata&&(u=ol(h.metadata)),(Ol=h.messages)!=null&&Ol.length&&(r={...r,initialMessages:h.messages}),(_l=h.artifacts)!=null&&_l.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:($l=h.selectedArtifactId)!=null?$l:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(Ul=l.messages)!=null&&Ul.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let x=()=>u,v=l=>{var h;u=(h=l({...u}))!=null?h:{},et()},M=r.actionParsers&&r.actionParsers.length?r.actionParsers:[nl],W=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ra.message,ra.messageAndClick],T=rl({parsers:M,handlers:W,getSessionMetadata:x,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let k=(ql=(zl=r.launcher)==null?void 0:zl.enabled)!=null?ql:!0,E=(Vl=(jl=r.launcher)==null?void 0:jl.autoExpand)!=null?Vl:!1,P=(Kl=r.autoFocusInput)!=null?Kl:!1,C=E,L=k,F=(Ql=(Gl=r.layout)==null?void 0:Gl.header)==null?void 0:Ql.layout,O=!1,R=()=>Js(r),$=()=>k||R(),N=R()?!1:k?E:!0,Z=!1,Se=null,pe=()=>{Z=!0,Se&&clearTimeout(Se),Se=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=Um(r,T,pe),ve=(Jl=(Xl=r.features)==null?void 0:Xl.showReasoning)!=null?Jl:!0,Ie=(Zl=(Yl=r.features)==null?void 0:Yl.showToolCalls)!=null?Zl:!0,ce=(tc=(ec=r.features)==null?void 0:ec.showEventStreamToggle)!=null?tc:!1,ue=(rc=(nc=r.features)==null?void 0:nc.scrollToBottom)!=null?rc:{},oe=(sc=(oc=r.features)==null?void 0:oc.scrollBehavior)!=null?sc:{},de=`${(ic=typeof r.persistState=="object"?(ac=r.persistState)==null?void 0:ac.keyPrefix:void 0)!=null?ic:"persona-"}event-stream`,$e=ce?new ta(de):null,Ne=(dc=(cc=(lc=r.features)==null?void 0:lc.eventStream)==null?void 0:cc.maxEvents)!=null?dc:2e3,V=ce?new ea(Ne,$e):null,G=ce?new na:null,be=null,X=!1,le=null,Ee=0;$e==null||$e.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Xe={onCopy:l=>{var p,h;i.emit("message:copy",l),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;i.emit("message:feedback",l),U!=null&&U.isClientTokenMode()&&U.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},Ze=(pc=r.statusIndicator)!=null?pc:{},wt=l=>{var p,h,b,S;return l==="idle"?(p=Ze.idleText)!=null?p:wn.idle:l==="connecting"?(h=Ze.connectingText)!=null?h:wn.connecting:l==="connected"?(b=Ze.connectedText)!=null?b:wn.connected:l==="error"?(S=Ze.errorText)!=null?S:wn.error:wn[l]};function dt(l,p,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=p,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=p}let Ye=sm({config:r,showClose:$()}),{wrapper:He,panel:K,pillRoot:qe}=Ye.shell,ze=Ye.panelElements,{container:xe,body:Ce,messagesWrapper:tt,suggestions:Ot,textarea:ne,sendButton:Oe,sendButtonWrapper:gn,composerForm:Bt,statusText:Xt,introTitle:Ir,introSubtitle:hr,closeButton:A,iconHolder:te,headerTitle:Te,headerSubtitle:Re,header:ke,footer:Be,actionsRow:Ve,leftActions:at,rightActions:Pt}=ze,bt=ze.setSendButtonMode,H=ze.micButton,J=ze.micButtonWrapper,Ae=ze.attachmentButton,it=ze.attachmentButtonWrapper,Qe=ze.attachmentInput,Ut=ze.attachmentPreviewsContainer;xe.classList.add("persona-relative"),Ce.classList.add("persona-relative");let fn=12,vt=()=>{var l;return(l=ue.label)!=null?l:""},xt=()=>{var l;return(l=ue.iconName)!=null?l:"arrow-down"},It=()=>ue.enabled!==!1,Ct=()=>{var l;return(l=oe.mode)!=null?l:"follow"},ln=()=>{var l;return(l=oe.anchorTopOffset)!=null?l:16},_t=y("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");_t.type="button",_t.style.display="none",_t.setAttribute("data-persona-scroll-to-bottom","true");let Nn=y("span","persona-flex persona-items-center"),Sn=y("span",""),Tn=y("span","");Tn.setAttribute("data-persona-scroll-to-bottom-count",""),Tn.style.display="none",_t.append(Nn,Sn,Tn),xe.appendChild(_t);let bn=y("div","persona-stream-anchor-spacer");bn.setAttribute("aria-hidden","true"),bn.setAttribute("data-persona-anchor-spacer",""),bn.style.flexShrink="0",bn.style.pointerEvents="none",bn.style.height="0px",Ce.appendChild(bn);let En=()=>{let p=Be.style.display==="none"?0:Be.offsetHeight;_t.style.bottom=`${p+fn}px`};En();let ar=()=>{let l=!!vt();_t.setAttribute("aria-label",vt()||"Jump to latest"),_t.title=vt(),_t.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Nn.innerHTML="";let p=fe(xt(),"14px","currentColor",2);p?(Nn.appendChild(p),Nn.style.display=""):Nn.style.display="none",Sn.textContent=vt(),Sn.style.display=l?"":"none"};ar();let At=null,yr=null,br=o.find(l=>l.renderHeader);if(br!=null&&br.renderHeader){let l=br.renderHeader({config:r,defaultRenderer:()=>{let p=Ho({config:r,showClose:$()});return Ys(xe,p,r),p.header},onClose:()=>zt(!1,"user")});if(l){let p=xe.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),ke=l,Ye.header.element=l)}}let Wr=()=>{var p,h,b,S;if(!V)return;if(X=!0,!be&&V&&(be=Cm({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>ir(),config:r,plugins:o,getThroughput:()=>{var B;return(B=G==null?void 0:G.getMetric())!=null?B:{status:"idle"}}})),be&&(Ce.style.display="none",(p=Be.parentNode)==null||p.insertBefore(be.element,Be),be.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${In.actionIconColor}`;let B=(S=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;B&&B.split(/\s+/).forEach(q=>q&&ut.classList.add(q))}let l=()=>{if(!X)return;let B=Date.now();B-Ee>=200&&(be==null||be.update(),Ee=B),le=requestAnimationFrame(l)};Ee=0,le=requestAnimationFrame(l),ot(),i.emit("eventStream:opened",{timestamp:Date.now()})},ir=()=>{var l,p,h;if(X){if(X=!1,be&&be.element.remove(),Ce.style.display="",ut){ut.style.boxShadow="";let b=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(S=>S&&ut.classList.remove(S))}le!==null&&(cancelAnimationFrame(le),le=null),ot(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ce){let l=(mc=(uc=r.features)==null?void 0:uc.eventStream)==null?void 0:mc.classNames,p="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!=null&&l.toggleButton?" "+l.toggleButton:"");ut=y("button",p),ut.style.width="28px",ut.style.height="28px",ut.style.color=In.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=fe("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let b=ze.clearChatButtonWrapper,S=ze.closeButtonWrapper,B=b||S;B&&B.parentNode===ke?ke.insertBefore(ut,B):ke.appendChild(ut),ut.addEventListener("click",()=>{X?ir():Wr()})}let mo=l=>{var S,B,q,_,D;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ae=l.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):l.insertBefore(h,l.firstChild)}if(!((B=l.querySelector("[data-persona-composer-attachment-input]"))!=null?B:l.querySelector('input[type="file"]'))){let ae=y("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=((q=p.allowedTypes)!=null?q:qr).join(","),ae.multiple=((_=p.maxFiles)!=null?_:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(D=p.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ae)}},vr=o.find(l=>l.renderComposer);if(vr!=null&&vr.renderComposer){let l=r.composer,p=vr.renderComposer({config:r,defaultRenderer:()=>Ja({config:r}).footer,onSubmit:h=>{var q;if(!U||U.isStreaming())return;let b=h.trim(),S=(q=At==null?void 0:At.hasAttachments())!=null?q:!1;if(!b&&!S)return;fl();let B;S&&(B=[],B.push(...At.getContentParts()),b&&B.push(ki(b))),U.sendMessage(b,{contentParts:B}),S&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Qe==null||Qe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((gc=r.voiceRecognition)==null?void 0:gc.enabled)===!0?()=>{yr==null||yr()}:void 0});p&&(Ye.replaceComposer(p),Be=Ye.composer.footer)}let go=l=>{let p=(...ie)=>{for(let Y of ie){let ye=l.querySelector(Y);if(ye)return ye}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),B=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(Bt=h),b&&(ne=b),S&&(Oe=S),B&&(H=B,J=B.parentElement),q&&(Xt=q);let _=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Ot=_);let D=p("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(Ae=D,it=D.parentElement),Qe=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Ut=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Ve=ae)};mo(Be),go(Be);let Wn=(vc=(fc=r.layout)==null?void 0:fc.contentMaxWidth)!=null?vc:R()?(bc=(yc=(hc=r.launcher)==null?void 0:hc.composerBar)==null?void 0:yc.contentMaxWidth)!=null?bc:"720px":void 0;if(Wn&&(tt.style.maxWidth=Wn,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%"),Wn&&Bt&&!R()&&(Bt.style.maxWidth=Wn,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Wn&&Ot&&!R()&&(Ot.style.maxWidth=Wn,Ot.style.marginLeft="auto",Ot.style.marginRight="auto"),Wn&&Ut&&!R()&&(Ut.style.maxWidth=Wn,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(xc=r.attachments)!=null&&xc.enabled&&Qe&&Ut){At=zs.fromConfig(r.attachments),At.setPreviewsContainer(Ut),Qe.addEventListener("change",h=>{let b=h.target;At==null||At.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,p=zm(l);xe.appendChild(p)}(()=>{var b,S;let l=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},p=B=>{switch(B){case"body-top":return xe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return tt;case"footer-top":return Ot;case"composer":return Bt;case"footer-bottom":return Xt;default:return null}},h=(B,q)=>{var _;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")ke.insertBefore(q,ke.firstChild);else if(B==="header-right")ke.appendChild(q);else{let D=ke.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(q,D.nextSibling):ke.appendChild(q)}break;case"body-top":{let D=Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(q):Ce.insertBefore(q,Ce.firstChild);break}case"body-bottom":Ce.appendChild(q);break;case"footer-top":Ot.replaceWith(q);break;case"footer-bottom":Xt.replaceWith(q);break;default:break}};for(let[B,q]of Object.entries(l))if(q)try{let _=q({config:r,defaultContent:()=>p(B)});_&&h(B,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,_)}})();let Kr=l=>{var q,_;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-bubble-type");if(B==="reasoning")ps.has(S)?ps.delete(S):ps.add(S),lm(S,b);else if(B==="tool")us.has(S)?us.delete(S):us.add(S),cm(S,b,r);else if(B==="approval"){let D=r.approval!==!1?r.approval:void 0,ae=((q=D==null?void 0:D.detailsDisplay)!=null?q:"collapsed")==="expanded",ie=(_=Bo.get(S))!=null?_:ae;Bo.set(S,!ie),mm(S,b,r)}Sr.delete(S)};tt.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Kr(l))}),tt.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Kr(l))}),tt.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let h=tt.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),B=_u(S);!B||B===S||(p.setData("text/plain",B),l.preventDefault())});let Rr=new Map,Gr=null,Qr="idle",fo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},ho=(l,p)=>{let{icon:h,label:b}=fo[p];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let S=fe(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Xr=()=>{tt.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var B;let h=p.closest("[data-actions-for]"),b=(B=h==null?void 0:h.getAttribute("data-actions-for"))!=null?B:null;ho(p,b&&b===Gr?Qr:"idle")})};tt.addEventListener("click",l=>{var q;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let B=h.getAttribute("data-action");if(B==="copy"){let D=U.getMessages().find(ae=>ae.id===S);if(D&&Xe.onCopy){let ae=D.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let ie=fe("check",14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=fe("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(ie=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ie)}),Xe.onCopy(D)}}else if(B==="read-aloud")U.toggleReadAloud(S);else if(B==="upvote"||B==="downvote"){let D=((q=Rr.get(S))!=null?q:null)===B,ae=B==="upvote"?"thumbs-up":"thumbs-down";if(D){Rr.delete(S),h.classList.remove("persona-message-action-active");let ie=fe(ae,14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie))}else{let ie=B==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${ie}"]`);if(Y){Y.classList.remove("persona-message-action-active");let _e=fe(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);_e&&(Y.innerHTML="",Y.appendChild(_e))}Rr.set(S,B),h.classList.add("persona-message-action-active");let ye=fe(ae,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let we=U.getMessages().find(Je=>Je.id===S);we&&Xe.onFeedback&&Xe.onFeedback({type:B,messageId:we.id,message:we})}}}),tt.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-approval-action");if(!B)return;let q=B==="approve"?"approved":"denied",D=U.getMessages().find(ie=>ie.id===S);if(!(D!=null&&D.approval))return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?U.resolveWebMcpApproval(S,q):U.resolveApproval(D.approval,q)});let yt=null,Fn=null,On={artifacts:[],selectedId:null},Mn=!1,St={current:null};tt.addEventListener("click",l=>{var Y,ye,De,we,Je;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((De=(ye=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:De.call(ye,{type:"download",artifactId:b}))===!0)return;let B=U.getArtifactById(b),q=B==null?void 0:B.markdown,_=(B==null?void 0:B.title)||"artifact";if(!q){let _e=h.closest("[data-open-artifact]"),ct=_e==null?void 0:_e.closest("[data-message-id]"),nt=ct==null?void 0:ct.getAttribute("data-message-id");if(nt){let Me=U.getMessages().find(Ue=>Ue.id===nt);if(Me!=null&&Me.rawContent)try{let Ue=JSON.parse(Me.rawContent);q=(we=Ue==null?void 0:Ue.props)==null?void 0:we.markdown,_=((Je=Ue==null?void 0:Ue.props)==null?void 0:Je.title)||_}catch{}}}if(!q)return;let D=new Blob([q],{type:"text/markdown"}),ae=URL.createObjectURL(D),ie=document.createElement("a");ie.href=ae,ie.download=`${_}.md`,ie.click(),URL.revokeObjectURL(ae)}),tt.addEventListener("click",l=>{var B,q,_;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(q=(B=r.features)==null?void 0:B.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:_.call(q,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Mn=!1,U.selectArtifact(b),Rn())}),tt.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Xn=ze.composerOverlay,Jn=(l,p,h)=>{var _,D,ae,ie;let b=p.trim();if(!b||!St.current)return;let S=(_=l.getAttribute("data-tool-call-id"))!=null?_:"",B=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?b.split(", "):[b],isFreeText:B,source:h.source},bubbles:!0,composed:!0})),os(Xn,S);let q=St.current.getMessages().find(Y=>{var ye;return((ye=Y.toolCall)==null?void 0:ye.id)===S});(ae=q==null?void 0:q.agentMetadata)!=null&&ae.awaitingLocalTool?St.current.resolveAskUserQuestion(q,(ie=h.structured)!=null?ie:b):St.current.sendMessage(b)},_n=l=>{var S;let p=St.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",b=p.getMessages().find(B=>{var q;return((q=B.toolCall)==null?void 0:q.id)===h});b&&p.persistAskUserQuestionProgress(b,{answers:ba(l,b),currentIndex:or(l)})},Jr=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Hr=l=>{var S,B,q;if(((B=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let p=or(l),h=rs(l);if(p>=h-1)return;let b=(q=St.current)==null?void 0:q.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});b&&(xa(l,b,r,p+1),_n(l))};Xn.addEventListener("click",l=>{var B,q,_,D,ae,ie,Y,ye,De,we,Je,_e,ct,nt;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let Le=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),os(Xn,Le);let Me=(q=St.current)==null?void 0:q.getMessages().find(Ue=>{var je;return((je=Ue.toolCall)==null?void 0:je.id)===Le});(_=Me==null?void 0:Me.agentMetadata)!=null&&_.awaitingLocalTool&&((D=St.current)==null||D.markAskUserQuestionResolved(Me),(ae=St.current)==null||ae.resolveAskUserQuestion(Me,"(dismissed)"));return}if(S==="pick"){let Le=h.getAttribute("data-option-label");if(!Le)return;let Me=b.getAttribute("data-multi-select")==="true",Ue=io(b);if(Ue&&Me){let je=Po(b)[or(b)],ft=new Set(Array.isArray(je)?je:[]);ft.has(Le)?ft.delete(Le):ft.add(Le),lo(b,Array.from(ft)),_n(b);return}if(Ue){lo(b,Le),_n(b),Hr(b);return}if(Me){let je=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",je?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!je);let ft=b.querySelector('[data-ask-user-action="submit-multi"]');ft&&(ft.disabled=Ci(b).length===0);return}Jn(b,Le,{source:"pick",values:[Le]});return}if(S==="submit-multi"){let Le=Ci(b);if(Le.length===0)return;Jn(b,Le.join(", "),{source:"multi",values:Le});return}if(S==="open-free-text"){let Le=b.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let Me=Le.querySelector('[data-ask-free-text-input="true"]');Me==null||Me.focus()}return}if(S==="focus-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(S==="submit-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]'),Me=(ie=Le==null?void 0:Le.value)!=null?ie:"";if(!Me.trim())return;if(io(b)){lo(b,Me.trim()),_n(b),Hr(b);return}Jn(b,Me,{source:"free-text"});return}if(S==="next"||S==="back"){if(!St.current)return;let Le=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",Me=St.current.getMessages().find(We=>{var Pe;return((Pe=We.toolCall)==null?void 0:Pe.id)===Le});if(!Me)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),je=(De=(ye=Ue==null?void 0:Ue.value)==null?void 0:ye.trim())!=null?De:"";if(je){let We=Po(b)[or(b)];(typeof We!="string"||We!==je)&&lo(b,je)}let ft=S==="next"?1:-1,I=or(b)+ft;xa(b,Me,r,I),_n(b);return}if(S==="submit-all"){if(!St.current)return;let Le=(we=b.getAttribute("data-tool-call-id"))!=null?we:"",Me=St.current.getMessages().find(We=>{var Pe;return((Pe=We.toolCall)==null?void 0:Pe.id)===Le});if(!Me)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),je=(_e=(Je=Ue==null?void 0:Ue.value)==null?void 0:Je.trim())!=null?_e:"";je&&lo(b,je);let ft=ba(b,Me);St.current.persistAskUserQuestionProgress(Me,{answers:ft,currentIndex:or(b)});let I=Jr(ft);Jn(b,I||"(submitted)",{source:"submit-all",structured:ft});return}if(S==="skip"){if(!St.current)return;let Le=(ct=b.getAttribute("data-tool-call-id"))!=null?ct:"",Me=St.current.getMessages().find(Pe=>{var me;return((me=Pe.toolCall)==null?void 0:me.id)===Le});if(!Me)return;let Ue=io(b),je=or(b),ft=rs(b),I=je>=ft-1;if(!Ue){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),os(Xn,Le),(nt=Me.agentMetadata)!=null&&nt.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Me),St.current.resolveAskUserQuestion(Me,"(dismissed)"));return}lo(b,"");let We=b.querySelector('[data-ask-free-text-input="true"]');if(We&&(We.value=""),I){let Pe=ba(b,Me),me=Jr(Pe);Jn(b,me||"(skipped)",{source:"submit-all",structured:Pe});return}xa(b,Me,r,je+1),_n(b);return}}),Xn.addEventListener("keydown",l=>{var B;if(l.key!=="Enter")return;let h=l.target;if(!((B=h.matches)!=null&&B.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let S=h.value;if(S.trim()){if(io(b)){lo(b,S.trim()),_n(b),Hr(b);return}Jn(b,S,{source:"free-text"})}});let Yr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=Xn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),B=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];B&&(l.preventDefault(),B.click())};document.addEventListener("keydown",Yr);let $n=null,Wt=null,kn=null,Yn=null,Zr=()=>{};function Br(){Yn==null||Yn(),Yn=null}let eo=()=>{var q;if(!$n||!Wt)return;let l=t.classList.contains("persona-artifact-appearance-seamless"),h=((q=t.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!l||t.classList.contains("persona-artifact-narrow-host")||h){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 b=$n.firstElementChild;if(!b||b===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 B=b.offsetWidth-S/2;Wt.style.left=`${Math.max(0,B)}px`},he=()=>{},Rn=()=>{var h,b,S,B,q;if(!yt||!sr(r))return;ti(t,r),ni(t,r),he();let l=(B=(S=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?B:520,p=K.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),yt.update(On),Mn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(q=yt.backdrop)==null||q.classList.add("persona-hidden")):On.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),Zr()};if(sr(r)){K.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(xe),yt=Tm(r,{onSelect:h=>{var b;return(b=St.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Mn=!0,Rn()}}),yt.element.classList.add("persona-hidden"),$n=p,p.appendChild(l),p.appendChild(yt.element),yt.backdrop&&K.appendChild(yt.backdrop),K.appendChild(p),Zr=()=>{var b,S,B,q;if(!$n||!yt)return;if(!(((B=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:B.resizable)===!0)){kn==null||kn(),kn=null,Br(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let D=t.ownerDocument,ae=(q=D.defaultView)!=null?q:window,ie=Y=>{var ct,nt;if(!yt||Y.button!==0||t.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Y.preventDefault(),Br();let ye=Y.clientX,De=yt.element.getBoundingClientRect().width,we=(nt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:nt.layout,Je=Le=>{let Me=$n.getBoundingClientRect().width,Ue=t.classList.contains("persona-artifact-appearance-seamless"),je=Ue?0:Lm($n,ae),ft=Ue?0:_.getBoundingClientRect().width||6,I=De-(Le.clientX-ye),We=Pm(I,Me,je,ft,we==null?void 0:we.resizableMinWidth,we==null?void 0:we.resizableMaxWidth);yt.element.style.width=`${We}px`,yt.element.style.maxWidth="none",eo()},_e=()=>{D.removeEventListener("pointermove",Je),D.removeEventListener("pointerup",_e),D.removeEventListener("pointercancel",_e),Yn=null;try{_.releasePointerCapture(Y.pointerId)}catch{}};Yn=_e,D.addEventListener("pointermove",Je),D.addEventListener("pointerup",_e),D.addEventListener("pointercancel",_e);try{_.setPointerCapture(Y.pointerId)}catch{}};_.addEventListener("pointerdown",ie),Wt=_,$n.insertBefore(_,yt.element),kn=()=>{_.removeEventListener("pointerdown",ie)}}if(Wt){let _=On.artifacts.length>0&&!Mn;Wt.classList.toggle("persona-hidden",!_),eo()}},he=()=>{var ae,ie,Y,ye,De,we,Je,_e,ct,nt,Le,Me,Ue,je;if(!k||!yt||((ie=(ae=r.launcher)==null?void 0:ae.sidebarMode)!=null?ie:!1)||yn(r)&&gr(r).reveal==="emerge")return;let b=(Y=t.ownerDocument.defaultView)!=null?Y:window,S=(De=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?De:!0,B=(Je=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Je:640;if(S&&b.innerWidth<=B||!km(r,k))return;let q=(nt=(ct=(_e=r.launcher)==null?void 0:_e.width)!=null?ct:r.launcherWidth)!=null?nt:jr,_=(je=(Ue=(Me=(Le=r.features)==null?void 0:Le.artifacts)==null?void 0:Me.layout)==null?void 0:Ue.expandedPanelWidth)!=null?je:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Mn?(K.style.width=_,K.style.maxWidth=_):(K.style.width=q,K.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Rn()}),Fn.observe(K))}else K.appendChild(xe),R()&&qe&&(ze.peekBanner&&qe.appendChild(ze.peekBanner),qe.appendChild(Be));t.appendChild(He),qe&&t.appendChild(qe);let xr=()=>{var We,Pe,me,Dt,Rt,Kt,ht,qt,jn,Zt,Ke,Mt,tn,nr,Vn,Co,Ao,Jo,Yo,Gt,So,ro,oo,$r,To,pr,kr,Ge;if(R()){K.style.width="100%",K.style.maxWidth="100%";let Nt=(Pe=(We=r.launcher)==null?void 0:We.composerBar)!=null?Pe:{},Vt=He.dataset.state==="expanded",Ft=(me=Nt.expandedSize)!=null?me:"anchored";if(!(Vt&&Ft!=="fullscreen")){xe.style.background="",xe.style.border="",xe.style.borderRadius="",xe.style.overflow="",xe.style.boxShadow="";return}let kt=(Rt=(Dt=r.theme)==null?void 0:Dt.components)==null?void 0:Rt.panel,$t=Ra(r),pn=(mn,rr)=>{var so;return mn==null||mn===""?rr:(so=ls($t,mn))!=null?so:mn},Kn="1px solid var(--persona-border)",Lr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",un="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";xe.style.background="var(--persona-surface, #ffffff)",xe.style.border=pn(kt==null?void 0:kt.border,Kn),xe.style.borderRadius=pn(kt==null?void 0:kt.borderRadius,un),xe.style.boxShadow=pn(kt==null?void 0:kt.shadow,Lr),xe.style.overflow="hidden";return}let l=yn(r),p=(ht=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?ht:!1,h=l||p||((jn=(qt=r.launcher)==null?void 0:qt.fullHeight)!=null?jn:!1),b=((Zt=r.launcher)==null?void 0:Zt.enabled)===!1,S=(Mt=(Ke=r.theme)==null?void 0:Ke.components)==null?void 0:Mt.panel,B=Ra(r),q=(Nt,Vt)=>{var Ft;return Nt==null||Nt===""?Vt:(Ft=ls(B,Nt))!=null?Ft:Nt},_=(tn=t.ownerDocument.defaultView)!=null?tn:window,D=(Vn=(nr=r.launcher)==null?void 0:nr.mobileFullscreen)!=null?Vn:!0,ae=(Ao=(Co=r.launcher)==null?void 0:Co.mobileBreakpoint)!=null?Ao:640,ie=_.innerWidth<=ae,Y=D&&ie&&k,ye=(Yo=(Jo=r.launcher)==null?void 0:Jo.position)!=null?Yo:"bottom-left",De=ye==="bottom-left"||ye==="top-left",we=(So=(Gt=r.launcher)==null?void 0:Gt.zIndex)!=null?So:Cn,Je=p||Y?"none":"1px solid var(--persona-border)",_e=Y?"none":p?De?"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))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Y&&(_e="none",Je="none");let ct=p||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",nt=q(S==null?void 0:S.border,Je),Le=q(S==null?void 0:S.shadow,_e),Me=q(S==null?void 0:S.borderRadius,ct),Ue=Ce.scrollTop;t.style.cssText="",He.style.cssText="",K.style.cssText="",xe.style.cssText="",Ce.style.cssText="",Be.style.cssText="";let je=()=>{var Vt;if(Ue<=0)return;((Vt=Ce.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(Ce.scrollTop===Ue)return;let Ft=Ce.scrollHeight-Ce.clientHeight;Ft<=0||(Ce.scrollTop=Math.min(Ue,Ft))})};if(Y){He.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"),He.style.cssText=`
35
35
  position: fixed !important;
36
36
  inset: 0 !important;
37
37
  width: 100% !important;
@@ -43,7 +43,7 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
43
43
  flex-direction: column !important;
44
44
  z-index: ${we} !important;
45
45
  background-color: var(--persona-surface, #ffffff) !important;
46
- `,de.style.cssText=`
46
+ `,K.style.cssText=`
47
47
  position: relative !important;
48
48
  display: flex !important;
49
49
  flex-direction: column !important;
@@ -56,7 +56,7 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
56
56
  padding: 0 !important;
57
57
  box-shadow: none !important;
58
58
  border-radius: 0 !important;
59
- `,le.style.cssText=`
59
+ `,xe.style.cssText=`
60
60
  display: flex !important;
61
61
  flex-direction: column !important;
62
62
  flex: 1 1 0% !important;
@@ -67,11 +67,11 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
67
67
  overflow: hidden !important;
68
68
  border-radius: 0 !important;
69
69
  border: none !important;
70
- `,xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.overflowY="auto",Re.style.flexShrink="0",I=!0,Ve();return}let yt=(ro=(no=r==null?void 0:r.launcher)==null?void 0:no.width)!=null?ro:r==null?void 0:r.launcherWidth,L=yt!=null?yt:Ur;if(!p&&!l)y&&h?(de.style.width="100%",de.style.maxWidth="100%"):(de.style.width=L,de.style.maxWidth=L);else if(l)if(mr(r).reveal==="emerge"){let Ft=mr(r).width;de.style.width=Ft,de.style.maxWidth=Ft}else de.style.width="100%",de.style.maxWidth="100%";if(vr(),de.style.boxShadow=He,de.style.borderRadius=Ie,le.style.border=ot,le.style.borderRadius=Ie,l&&!Y&&(A==null?void 0:A.border)===void 0&&(le.style.border="none",mr(r).side==="right"?le.style.borderLeft="1px solid var(--persona-border)":le.style.borderRight="1px solid var(--persona-border)"),h&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",y&&(n.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%",y&&(Me.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",de.style.overflow="hidden",le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.overflow="hidden",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.overflowY="auto",Re.style.flexShrink="0"),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"),!p&&!y&&!l&&((Or=gr[ye])!=null?Or:gr["bottom-right"]).split(" ").forEach(Ft=>Me.classList.add(Ft)),p){let Ot=(dr=(wo=r.launcher)==null?void 0:wo.sidebarWidth)!=null?dr:"420px";Me.style.cssText=`
70
+ `,Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.overflowY="auto",Be.style.flexShrink="0",O=!0,je();return}let ft=(oo=(ro=r==null?void 0:r.launcher)==null?void 0:ro.width)!=null?oo:r==null?void 0:r.launcherWidth,I=ft!=null?ft:jr;if(!p&&!l)b&&h?(K.style.width="100%",K.style.maxWidth="100%"):(K.style.width=I,K.style.maxWidth=I);else if(l)if(gr(r).reveal==="emerge"){let Vt=gr(r).width;K.style.width=Vt,K.style.maxWidth=Vt}else K.style.width="100%",K.style.maxWidth="100%";if(he(),K.style.boxShadow=Le,K.style.borderRadius=Me,xe.style.border=nt,xe.style.borderRadius=Me,l&&!Y&&(S==null?void 0:S.border)===void 0&&(xe.style.border="none",gr(r).side==="right"?xe.style.borderLeft="1px solid var(--persona-border)":xe.style.borderRight="1px solid var(--persona-border)"),h&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",b&&(t.style.width="100%"),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%",b&&(He.style.overflow="hidden"),K.style.display="flex",K.style.flexDirection="column",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.maxHeight="100%",K.style.height="100%",K.style.overflow="hidden",xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.overflow="hidden",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.overflowY="auto",Be.style.flexShrink="0"),He.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"),!p&&!b&&!l&&(($r=fr[ye])!=null?$r:fr["bottom-right"]).split(" ").forEach(Vt=>He.classList.add(Vt)),p){let Nt=(pr=(To=r.launcher)==null?void 0:To.sidebarWidth)!=null?pr:"420px";He.style.cssText=`
71
71
  position: fixed !important;
72
72
  top: 0 !important;
73
73
  bottom: 0 !important;
74
- width: ${Ot} !important;
74
+ width: ${Nt} !important;
75
75
  height: 100vh !important;
76
76
  max-height: 100vh !important;
77
77
  margin: 0 !important;
@@ -79,8 +79,8 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
79
79
  display: flex !important;
80
80
  flex-direction: column !important;
81
81
  z-index: ${we} !important;
82
- ${Ne?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
- `,de.style.cssText=`
82
+ ${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
+ `,K.style.cssText=`
84
84
  position: relative !important;
85
85
  display: flex !important;
86
86
  flex-direction: column !important;
@@ -91,9 +91,9 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
91
91
  min-height: 0 !important;
92
92
  margin: 0 !important;
93
93
  padding: 0 !important;
94
- box-shadow: ${He} !important;
95
- border-radius: ${Ie} !important;
96
- `,de.style.setProperty("width","100%","important"),de.style.setProperty("max-width","100%","important"),le.style.cssText=`
94
+ box-shadow: ${Le} !important;
95
+ border-radius: ${Me} !important;
96
+ `,K.style.setProperty("width","100%","important"),K.style.setProperty("max-width","100%","important"),xe.style.cssText=`
97
97
  display: flex !important;
98
98
  flex-direction: column !important;
99
99
  flex: 1 1 0% !important;
@@ -102,15 +102,15 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
102
102
  min-height: 0 !important;
103
103
  max-height: 100% !important;
104
104
  overflow: hidden !important;
105
- border-radius: ${Ie} !important;
106
- border: ${ot} !important;
107
- `,Re.style.cssText=`
105
+ border-radius: ${Me} !important;
106
+ border: ${nt} !important;
107
+ `,Be.style.cssText=`
108
108
  flex-shrink: 0 !important;
109
109
  border-top: none !important;
110
110
  padding: 8px 16px 12px 16px !important;
111
- `}if(!y&&!l){let Ot="max-height: -moz-available !important; max-height: stretch !important;",Ft=p?"":"padding-top: 1.25em !important;",gt=p?"":`z-index: ${(sn=(Je=r.launcher)==null?void 0:Je.zIndex)!=null?sn:xn} !important;`;Me.style.cssText+=Ot+Ft+gt}Ve()};he(),ss(n,r),Ja(n,r),Ya(n,r);let ct=[];ct.push(()=>{document.removeEventListener("keydown",Qr)});let Gt=null,rn=null;ct.push(()=>{Gt==null||Gt(),Gt=null,rn==null||rn(),rn=null}),Nn&&ct.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),ct.push(()=>{Sn==null||Sn(),Sn=null,Wr(),Ht&&(Ht.remove(),Ht=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),Pe&&ct.push(()=>{Ue!==null&&(cancelAnimationFrame(Ue),Ue=null),V==null||V.destroy(),V=null,fe==null||fe.destroy(),fe=null,Q=null});let xr=null,us=()=>{xr&&(xr(),xr=null),r.colorScheme==="auto"&&(xr=Bu(()=>{ss(n,r)}))};us(),ct.push(()=>{xr&&(xr(),xr=null)});let Rr=(yc=r.features)==null?void 0:yc.streamAnimation;if(Rr!=null&&Rr.type&&Rr.type!=="none"){let l=$s(Rr.type,Rr.plugins);l&&(Ri(l,n),ct.push(()=>Gu(n)))}let go=dm(Lt),wr=null,O,Do=l=>{var y,A;if(!O)return;let p=l!=null?l:O.getMessages(),h=((A=(y=r.features)==null?void 0:y.suggestReplies)==null?void 0:A.enabled)!==!1?tu(p):null;h?go.render(h,O,Se,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(R=>R.role==="user")?go.render([],O,Se,p):go.render(r.suggestionChips,O,Se,p,r.suggestionChipsConfig)},Cr=!1,Ar=Ou(),Hr=new Map,Sr=new Map,ir=new Map,No=0,ea=To()!==null,Un=Wa(),qn=0,lr=null,cr=!1,fo=!1,Br=0,hn=null,Tr=null,Fo=!1,ho=!1,Oo=null,ta=4,_o=24,na=80,$o=new Map,ft={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ms=(vc=(bc=r.voiceRecognition)==null?void 0:bc.autoResume)!=null?vc:!1,er=l=>{s.emit("voice:state",{active:ft.active,source:l,timestamp:Date.now()})},Wn=()=>{u(l=>({...l,voiceState:{active:ft.active,timestamp:Date.now(),manuallyDeactivated:ft.manuallyDeactivated}}))},ra=()=>{var y,A;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=el(d.voiceState),p=!!l.active,h=Number((A=l.timestamp)!=null?A:0);ft.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<hv&&setTimeout(()=>{var R,q;ft.active||(ft.manuallyDeactivated=!1,((q=(R=r.voiceRecognition)==null?void 0:R.provider)==null?void 0:q.type)==="runtype"?O.toggleVoice().then(()=>{ft.active=O.isVoiceActive(),er("restore"),O.isVoiceActive()&&zo()}):aa("restore"))},1e3)},oa=()=>O?Rm(O.getMessages()).filter(l=>!l.__skipPersist):[];function Yr(l){if(!(i!=null&&i.save))return;let h={messages:l?Rm(l):O?oa():[],metadata:d,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let et=null,w=()=>Me.querySelector("#persona-scroll-container")||xe,$=()=>{et!==null&&(cancelAnimationFrame(et),et=null),cr=!1},_=()=>{lr!==null&&(cancelAnimationFrame(lr),lr=null),fo=!1,$()},G=()=>{Br>0?(Cn.textContent=String(Br),Cn.style.display="",lt.setAttribute("aria-label",`${Yt()||"Jump to latest"} (${Br} new)`)):(Cn.textContent="",Cn.style.display="none",lt.setAttribute("aria-label",Yt()||"Jump to latest"))},ge=()=>{Br!==0&&(Br=0,G())},Fe=()=>Ze()==="follow"?!Un.isFollowing():!Io(xe,_o),Xe=()=>{if(!Rt()||ee){lt.parentNode&&lt.remove(),lt.style.display="none";return}lt.parentNode!==le&&le.appendChild(lt),Pn();let p=qr(xe)>0&&Fe();p||ge(),lt.style.display=p?"":"none"},Mt=()=>{Un.pause()&&(_(),Xe())},Dr=()=>{Un.resume(),ge(),Xe()},Rn=(l=!1)=>{Ze()==="follow"&&Un.isFollowing()&&(!l&&!Cr||(lr!==null&&(cancelAnimationFrame(lr),lr=null),fo=!0,lr=requestAnimationFrame(()=>{lr=null,fo=!1,Un.isFollowing()&&pn(w(),l?220:140)})))},zn=(l,p,h,y=()=>!0)=>{let A=l.scrollTop,R=p(),q=R-A;$();let F=performance.now();cr=!0;let H=se=>1-Math.pow(1-se,3),oe=se=>{if(!y()){$();return}let Y=p();Y!==R&&(R=Y,q=R-A);let ye=se-F,Ne=Math.min(ye/h,1),we=H(Ne),tt=A+q*we;l.scrollTop=tt,qn=l.scrollTop,Ne<1?et=requestAnimationFrame(oe):(l.scrollTop=R,qn=l.scrollTop,et=null,cr=!1)};et=requestAnimationFrame(oe)},pn=(l,p=500)=>{let h=qr(l)-l.scrollTop;if(Math.abs(h)<1){qn=l.scrollTop;return}if(Math.abs(h)>=na){$(),cr=!0,l.scrollTop=qr(l),qn=l.scrollTop,cr=!1;return}zn(l,()=>qr(l),p,()=>Un.isFollowing())},Zr=()=>{let l=w();cr=!0,l.scrollTop=qr(l),qn=l.scrollTop,cr=!1,Xe()},Nr=l=>{Zt.style.height=`${Math.max(0,Math.round(l))}px`,hn&&(hn.spacerHeight=Math.max(0,l))},un=()=>{Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),$(),hn=null,Zt.style.height="0px"},Hn=l=>{Tr!==null&&cancelAnimationFrame(Tr),Tr=requestAnimationFrame(()=>{var oe;Tr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=xe.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,A=h;for(;A&&A!==xe;)y+=A.offsetTop,A=A.offsetParent;let R=(oe=hn==null?void 0:hn.spacerHeight)!=null?oe:0,q=xe.scrollHeight-R,{targetScrollTop:F,spacerHeight:H}=zu({anchorOffsetTop:y,topOffset:Wt(),viewportHeight:xe.clientHeight,contentHeight:q});hn={initialSpacerHeight:H,contentHeightAtAnchor:q,spacerHeight:H},Nr(H),zn(xe,()=>F,220)})},jn=()=>{if(Ze()==="follow"){if(!Un.isFollowing()||Io(xe,1))return;Rn(!Cr);return}if(hn&&hn.initialSpacerHeight>0){let l=xe.scrollHeight-hn.spacerHeight,p=ju({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:l});p!==hn.spacerHeight&&Nr(p)}Xe()},Km=l=>{let p=Ze();p==="follow"?(Dr(),Rn(!0)):p==="anchor-top"&&Hn(l)},Gm=l=>{let p=new Map;l.forEach(h=>{let y=$o.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!ho&&Ze()!=="anchor-top"&&Fe()&&(Br+=1,G(),Xe())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),$o.clear(),p.forEach((h,y)=>{$o.set(y,h)})},Qm=(l,p,h)=>{var ot,He,Ie,qe,Ve,yt;let y=document.createElement("div"),R=(()=>{var De;let L=o.find(Be=>Be.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(L,De)=>De==null?!1:typeof De=="string"?(L.textContent=De,!0):(L.appendChild(De),!0),F=new Set,H=new Set,oe=o.some(L=>L.renderAskUserQuestion),se=[],Y=[],ye=r.enableComponentStreaming!==!1,Ne=o.some(L=>L.renderApproval)&&r.approval!==!1,we=[];if(p.forEach(L=>{var Ge,Et,tn,rr,Kn,bo,vo,Vo,Ko,zt,xo,no,ro,Or,wo,dr;F.add(L.id);let De=oe&&Eo(L),Be=Ne&&L.variant==="approval"&&!!L.approval,me=!De&&L.role==="assistant"&&!L.variant&&ye&&Lm(L);if(!Be&&ir.has(L.id)){let Je=l.querySelector(`#wrapper-${L.id}`);Je==null||Je.removeAttribute("data-preserve-runtime"),ir.delete(L.id)}if(!me&&Sr.has(L.id)){let Je=l.querySelector(`#wrapper-${L.id}`);Je==null||Je.removeAttribute("data-preserve-runtime"),Sr.delete(L.id)}let Nt=Eo(L)?`:${(Ge=L.agentMetadata)!=null&&Ge.askUserQuestionAnswered?"a":"u"}:${(Et=L.agentMetadata)!=null&&Et.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Bt=Fu(L,No)+Nt,qt=De||Be||me?null:_u(Ar,L.id,Bt);if(qt){y.appendChild(qt.cloneNode(!0)),Eo(L)&&((tn=L.toolCall)!=null&&tn.id)&&((rr=L.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((Kn=L.agentMetadata)!=null&&Kn.askUserQuestionAnswered)&&(H.add(L.toolCall.id),fa(L,r,X.composerOverlay));return}let xt=null,$t=o.find(Je=>!!(L.variant==="reasoning"&&Je.renderReasoning||L.variant==="tool"&&Je.renderToolCall||!L.variant&&Je.renderMessage)),Vn=(bo=r.layout)==null?void 0:bo.messages;if(Eo(L)&&((vo=L.agentMetadata)==null?void 0:vo.askUserQuestionAnswered)===!0){Hr.delete(L.id);let Je=l.querySelector(`#wrapper-${L.id}`);Je==null||Je.removeAttribute("data-preserve-runtime");return}if(wi(L)&&((Ko=(Vo=r.features)==null?void 0:Vo.suggestReplies)==null?void 0:Ko.enabled)!==!1)return;if(Eo(L)&&((xo=(zt=r.features)==null?void 0:zt.askUserQuestion)==null?void 0:xo.enabled)!==!1){let Je=o.find(sn=>typeof sn.renderAskUserQuestion=="function");if(Je&&At.current){let sn=Hr.get(L.id),Ot=sn!==Bt,Ft=null;if(Ot){let{payload:Ct,complete:yn}=Jo(L),Tn=L.id,Er=()=>{var cn;return(cn=At.current)==null?void 0:cn.getMessages().find(Mn=>Mn.id===Tn)};Ft=Je.renderAskUserQuestion({message:L,payload:Ct,complete:yn,resolve:cn=>{var En;let Mn=Er();Mn&&((En=At.current)==null||En.resolveAskUserQuestion(Mn,cn))},dismiss:()=>{var Mn,En,Co;let cn=Er();(Mn=cn==null?void 0:cn.agentMetadata)!=null&&Mn.awaitingLocalTool&&((En=At.current)==null||En.markAskUserQuestionResolved(cn),(Co=At.current)==null||Co.resolveAskUserQuestion(cn,"(dismissed)"))},config:r})}let gt=sn!=null;if(Ot&&Ft===null&&!gt){((no=L.agentMetadata)==null?void 0:no.awaitingLocalTool)===!0&&!((ro=L.agentMetadata)!=null&&ro.askUserQuestionAnswered)&&(H.add(L.toolCall.id),fa(L,r,X.composerOverlay));return}let jt=document.createElement("div");jt.className="persona-flex",jt.id=`wrapper-${L.id}`,jt.setAttribute("data-wrapper-id",L.id),jt.setAttribute("data-ask-plugin-stub","true"),jt.setAttribute("data-preserve-runtime","true"),y.appendChild(jt),se.push({messageId:L.id,fingerprint:Bt,bubble:Ft});return}else{((Or=L.agentMetadata)==null?void 0:Or.awaitingLocalTool)===!0&&!((wo=L.agentMetadata)!=null&&wo.askUserQuestionAnswered)&&(H.add(L.toolCall.id),fa(L,r,X.composerOverlay));return}}else if(Be){let Je=o.find(gt=>typeof gt.renderApproval=="function"),Ot=ir.get(L.id)!==Bt,Ft=null;if(Ot&&(Je!=null&&Je.renderApproval)){let gt=L.id,jt=(Ct,yn)=>{var Er,cn,Mn;let Tn=(Er=At.current)==null?void 0:Er.getMessages().find(En=>En.id===gt);Tn!=null&&Tn.approval&&(Tn.approval.toolType==="webmcp"?(cn=At.current)==null||cn.resolveWebMcpApproval(Tn.id,Ct):(Mn=At.current)==null||Mn.resolveApproval(Tn.approval,Ct,yn))};Ft=Je.renderApproval({message:L,defaultRenderer:()=>Qa(L,r),config:r,approve:Ct=>jt("approved",Ct),deny:Ct=>jt("denied",Ct)})}if(Ot&&Ft===null){let gt=l.querySelector(`#wrapper-${L.id}`);gt==null||gt.removeAttribute("data-preserve-runtime"),ir.delete(L.id),xt=Qa(L,r)}else{let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${L.id}`,gt.setAttribute("data-wrapper-id",L.id),gt.setAttribute("data-approval-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),y.appendChild(gt),we.push({messageId:L.id,fingerprint:Bt,bubble:Ft});return}}else if($t)if(L.variant==="reasoning"&&L.reasoning&&$t.renderReasoning){if(!$e)return;xt=$t.renderReasoning({message:L,defaultRenderer:()=>Ui(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&$t.renderToolCall){if(!ve)return;xt=$t.renderToolCall({message:L,defaultRenderer:()=>zi(L,r),config:r})}else $t.renderMessage&&(xt=$t.renderMessage({message:L,defaultRenderer:()=>{let Je=$i(L,h,Vn,r.messageActions,ie,{loadingIndicatorRenderer:R,widgetConfig:r});return L.role!=="user"&&Gi(Je,L,r,O),Je},config:r}));if(!xt&&me){let Je=Pm(L);if(Je){let sn=Sr.get(L.id),Ot=sn!==Bt,Ft=r.wrapComponentDirectiveInBubble!==!1,gt=null;if(Ot){let jt=Em(Je,{config:r,message:L,transform:h});if(jt)if(Ft){let Ct=document.createElement("div");if(Ct.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(" "),Ct.id=`bubble-${L.id}`,Ct.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let yn=document.createElement("div");yn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",yn.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ct.appendChild(yn)}Ct.appendChild(jt),gt=Ct}else{let Ct=document.createElement("div");if(Ct.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ct.id=`bubble-${L.id}`,Ct.setAttribute("data-message-id",L.id),Ct.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let yn=document.createElement("div");yn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",yn.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ct.appendChild(yn)}Ct.appendChild(jt),gt=Ct}}if(gt||sn!=null){let jt=document.createElement("div");jt.className="persona-flex",jt.id=`wrapper-${L.id}`,jt.setAttribute("data-wrapper-id",L.id),jt.setAttribute("data-component-directive-stub","true"),jt.setAttribute("data-preserve-runtime","true"),Ft||jt.classList.add("persona-w-full"),y.appendChild(jt),Y.push({messageId:L.id,fingerprint:Bt,bubble:gt});return}}}if(!xt)if(L.variant==="reasoning"&&L.reasoning){if(!$e)return;xt=Ui(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!ve)return;xt=zi(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;xt=Qa(L,r)}else{let Je=(dr=r.layout)==null?void 0:dr.messages;Je!=null&&Je.renderUserMessage&&L.role==="user"?xt=Je.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):Je!=null&&Je.renderAssistantMessage&&L.role==="assistant"?xt=Je.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):xt=$i(L,h,Je,r.messageActions,ie,{loadingIndicatorRenderer:R,widgetConfig:r}),L.role!=="user"&&xt&&Gi(xt,L,r,O)}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${L.id}`,Xt.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Xt.classList.add("persona-justify-end"),(xt==null?void 0:xt.getAttribute("data-persona-component-directive"))==="true"&&Xt.classList.add("persona-w-full"),Xt.appendChild(xt),$u(Ar,L.id,Bt,Xt),y.appendChild(Xt)}),X.composerOverlay&&X.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let Be=De.getAttribute("data-persona-ask-sheet-for");Be&&!H.has(Be)&&Zo(X.composerOverlay,Be)}),(He=(ot=r.features)==null?void 0:ot.toolCallDisplay)!=null&&He.grouped){let L=[],De=[];p.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&ve){De.push(Be);return}De.length>1&&L.push(De),De=[]}),De.length>1&&L.push(De),L.forEach((Be,me)=>{var Ge,Et;let Nt=Be.map(tn=>Array.from(y.children).find(rr=>rr instanceof HTMLElement&&rr.getAttribute("data-wrapper-id")===tn.id)).filter(tn=>!!tn);if(Nt.length<2)return;let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-tool-group-${me}-${Be[0].id}`,Bt.setAttribute("data-wrapper-id",`tool-group-${me}-${Be[0].id}`);let qt=document.createElement("div");qt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",qt.setAttribute("data-persona-tool-group","true");let xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let $t=`Called ${Be.length} tools`,Vn=(Et=(Ge=r.toolCall)==null?void 0:Ge.renderGroupedSummary)==null?void 0:Et.call(Ge,{messages:Be,toolCalls:Be.map(tn=>tn.toolCall).filter(tn=>!!tn),defaultSummary:$t,config:r});q(xt,Vn)||(xt.textContent=$t);let Xt=document.createElement("div");Xt.className="persona-tool-group-stack persona-flex persona-flex-col",qt.append(xt,Xt),Bt.appendChild(qt),Nt[0].before(Bt),Nt.forEach((tn,rr)=>{let Kn=document.createElement("div");Kn.className="persona-tool-group-item persona-relative",Kn.setAttribute("data-persona-tool-group-item","true"),rr<Nt.length-1&&Kn.setAttribute("data-persona-tool-group-connector","true"),Kn.appendChild(tn),Xt.appendChild(Kn)})})}Uu(Ar,F);let tt=p.some(L=>L.role==="assistant"&&L.streaming),_e=p[p.length-1],mt=(_e==null?void 0:_e.role)==="assistant"&&!_e.streaming&&_e.variant!=="approval";if(Cr&&p.some(L=>L.role==="user")&&!tt&&!mt){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:Gs},De=o.find(me=>me.renderLoadingIndicator),Be=null;if(De!=null&&De.renderLoadingIndicator&&(Be=De.renderLoadingIndicator(L)),Be===null&&((Ie=r.loadingIndicator)!=null&&Ie.render)&&(Be=r.loadingIndicator.render(L)),Be===null&&(Be=Gs()),Be){let me=document.createElement("div"),Nt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;me.className=Nt?["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(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(Be);let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id="wrapper-typing-indicator",Bt.setAttribute("data-wrapper-id","typing-indicator"),Bt.appendChild(me),y.appendChild(Bt)}}if(!Cr&&p.length>0){let L=p[p.length-1],De={config:r,lastMessage:L,messageCount:p.length},Be=o.find(Nt=>Nt.renderIdleIndicator),me=null;if(Be!=null&&Be.renderIdleIndicator&&(me=Be.renderIdleIndicator(De)),me===null&&((Ve=r.loadingIndicator)!=null&&Ve.renderIdle)&&(me=r.loadingIndicator.renderIdle(De)),me){let Nt=document.createElement("div"),Bt=((yt=r.loadingIndicator)==null?void 0:yt.showBubble)!==!1;Nt.className=Bt?["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(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(me);let qt=document.createElement("div");qt.className="persona-flex",qt.id="wrapper-idle-indicator",qt.setAttribute("data-wrapper-id","idle-indicator"),qt.appendChild(Nt),y.appendChild(qt)}}if(Pa(l,y),se.length>0)for(let{messageId:L,fingerprint:De,bubble:Be}of se){let me=l.querySelector(`#wrapper-${L}`);me&&Be!==null&&(me.replaceChildren(Be),me.setAttribute("data-bubble-fp",De),Hr.set(L,De))}if(Hr.size>0)for(let L of Hr.keys())F.has(L)||Hr.delete(L);if(Y.length>0)for(let{messageId:L,fingerprint:De,bubble:Be}of Y){let me=l.querySelector(`#wrapper-${L}`);me&&Be!==null&&(me.replaceChildren(Be),me.setAttribute("data-bubble-fp",De),Sr.set(L,De))}if(Sr.size>0)for(let L of Sr.keys())F.has(L)||Sr.delete(L);if(we.length>0)for(let{messageId:L,fingerprint:De,bubble:Be}of we){let me=l.querySelector(`#wrapper-${L}`);me&&Be!==null&&(me.replaceChildren(Be),me.setAttribute("data-bubble-fp",De),ir.set(L,De))}if(ir.size>0)for(let L of ir.keys())F.has(L)||ir.delete(L)},gs=(l,p,h)=>{Qm(l,p,h),Kr()},fs=null,Xm=()=>{var h;if(fs)return;let l=y=>{let A=y.composedPath();A.includes(Me)||Qe&&A.includes(Qe)||_t(!1,"user")};fs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},il=()=>{var p;if(!fs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",fs,!0),fs=null};ct.push(()=>il());let hs=null,Jm=()=>{var h;if(hs)return;let l=y=>{y.key==="Escape"&&(y.isComposing||_t(!1,"user"))};hs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},ll=()=>{var p;if(!hs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",hs,!0),hs=null};ct.push(()=>ll());let ys=!1,cl=new Set,Ym=()=>{var p,h,y,A;let l=(y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return l||((A=r.features)==null?void 0:A.streamAnimation)},Uo=()=>{var mt,ot,He,Ie;if(!D())return;let l=X.peekBanner,p=X.peekTextNode;if(!l||!p)return;if(E){l.classList.remove("persona-pill-peek--visible");return}let h=(mt=O==null?void 0:O.getMessages())!=null?mt:[],y;for(let qe=h.length-1;qe>=0;qe--){let Ve=h[qe];if(Ve.role==="assistant"&&Ve.content){y=Ve;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let A=y.content,R=!!y.streaming,q=Ym(),F=Ba(q),H=F.type!=="none"?$s(F.type,q==null?void 0:q.plugins):null,oe=((ot=H==null?void 0:H.isAnimating)==null?void 0:ot.call(H,y))===!0,se=H!==null&&(R||oe);se&&H&&!cl.has(H.name)&&(Ri(H,n),cl.add(H.name));let Y=se&&(H!=null&&H.containerClass)?H.containerClass:null,ye=(He=p.dataset.personaPeekStreamClass)!=null?He:null;ye&&ye!==Y&&(p.classList.remove(ye),delete p.dataset.personaPeekStreamClass),Y&&ye!==Y&&(p.classList.add(Y),p.dataset.personaPeekStreamClass=Y),se?(p.style.setProperty("--persona-stream-step",`${F.speed}ms`),p.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ne=se?Da(A,F.buffer,H,y,R):A;if(se&&F.placeholder==="skeleton"&&R&&(!Ne||!Ne.trim())){let qe=document.createElement("div"),Ve=qs();Ve.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ve),Pa(p,qe)}else{let qe=Math.max(0,Ne.length-100),Ve=Ne.length>100?Ne.slice(-100):Ne,yt=oo(Ve);if(!se||!H){let L=Ne.length>100?`\u2026${Ve}`:Ve;p.textContent!==L&&(p.textContent=L)}else{let L=yt;(H.wrap==="char"||H.wrap==="word")&&(L=Us(yt,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:qe}));let De=document.createElement("div");if(De.innerHTML=L,H.useCaret&&Ve.length>0){let Be=Na(),me=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=me[me.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(Be,Nt.nextSibling):De.appendChild(Be)}Pa(p,De),(Ie=H.onAfterRender)==null||Ie.call(H,{container:p,bubble:l,messageId:y.id,message:y,speed:F.speed,duration:F.duration})}}let _e=Cr||ys;l.classList.toggle("persona-pill-peek--visible",_e)};if(D()){let l=X.peekBanner;if(l){let y=A=>{A.preventDefault(),A.stopPropagation(),_t(!0,"user")};l.addEventListener("pointerdown",y),ct.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{ys||(ys=!0,Uo())},h=()=>{ys&&(ys=!1,Uo())};de.addEventListener("pointerenter",p),de.addEventListener("pointerleave",h),ct.push(()=>{de.removeEventListener("pointerenter",p),de.removeEventListener("pointerleave",h)}),Qe&&(Qe.addEventListener("pointerenter",p),Qe.addEventListener("pointerleave",h),ct.push(()=>{Qe.removeEventListener("pointerenter",p),Qe.removeEventListener("pointerleave",h)}))}let Zm=l=>{var ye,Ne,we,tt,_e,mt,ot,He;let p=(Ne=(ye=r.launcher)==null?void 0:ye.composerBar)!=null?Ne:{},h=(we=p.expandedSize)!=null?we:"anchored",y=(tt=p.bottomOffset)!=null?tt:"16px",A=p.collapsedMaxWidth,R=(_e=p.expandedMaxWidth)!=null?_e:"880px",q=(mt=p.expandedTopOffset)!=null?mt:"5vh",F=(ot=p.modalMaxWidth)!=null?ot:"880px",H=(He=p.modalMaxHeight)!=null?He:"min(90vh, 800px)",oe="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Y=Me.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",Qe){let Ie=Qe.style;Ie.bottom=y,Ie.width=A!=null?A:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=F,Y.maxWidth=oe,Y.maxHeight=H,Y.height=H;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${y} + ${se})`,Y.top=q,Y.width=R,Y.maxWidth=oe}},bs=()=>{var H,oe,se,Y,ye,Ne,we,tt;if(!B())return;if(D()){let mt=(se=((oe=(H=r.launcher)==null?void 0:H.composerBar)!=null?oe:{}).expandedSize)!=null?se:"anchored",ot=E?"expanded":"collapsed";Me.dataset.state=ot,Me.dataset.expandedSize=mt,Qe&&(Qe.dataset.state=ot,Qe.dataset.expandedSize=mt),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Zm(E),le.style.display=E?"flex":"none",he(),E?(Xm(),Jm()):(il(),ll()),Uo();return}let l=mn(r),p=(Y=n.ownerDocument.defaultView)!=null?Y:window,h=(Ne=(ye=r.launcher)==null?void 0:ye.mobileBreakpoint)!=null?Ne:640,y=(tt=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?tt:!0,A=p.innerWidth<=h,R=y&&A&&T,q=mr(r).reveal;E?(Me.style.removeProperty("display"),Me.style.display=l?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Qt?Qt.element.style.display="none":on&&(on.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!R?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.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"),de.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"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Qt?Qt.element.style.display=l?"none":"":on&&(on.style.display=l?"none":""))},_t=(l,p="user")=>{var R,q;if(!B()||E===l)return;let h=E;E=l,bs();let y=(()=>{var we,tt,_e,mt,ot,He,Ie,qe,Ve,yt;let F=(tt=(we=r.launcher)==null?void 0:we.sidebarMode)!=null?tt:!1,H=(_e=n.ownerDocument.defaultView)!=null?_e:window,oe=(ot=(mt=r.launcher)==null?void 0:mt.mobileFullscreen)!=null?ot:!0,se=(Ie=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?Ie:640,Y=H.innerWidth<=se,ye=mn(r)&&oe&&Y,Ne=D()&&((yt=(Ve=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ve.expandedSize)!=null?yt:"fullscreen")==="fullscreen";return F||oe&&Y&&T||ye||Ne})();if(E&&y){if(!Gt){let F=n.getRootNode(),H=F instanceof ShadowRoot?F.host:n.closest(".persona-host");H&&(Gt=Hi(H,(q=(R=r.launcher)==null?void 0:R.zIndex)!=null?q:xn))}rn||(rn=Bi(n.ownerDocument))}else E||(Gt==null||Gt(),Gt=null,rn==null||rn(),rn=null);E&&(vs(),Ze()==="follow"?Rn(!0):Zr());let A={open:E,source:p,timestamp:Date.now()};E&&!h?s.emit("widget:opened",A):!E&&h&&s.emit("widget:closed",A),s.emit("widget:state",{open:E,launcherEnabled:T,voiceActive:ft.active,streaming:O.isStreaming()})},ti=l=>{It(l?"stop":"send"),U&&(U.disabled=l),go.buttons.forEach(p=>{p.disabled=l}),Re.dataset.personaComposerStreaming=l?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},ni=()=>{ft.active||Se&&Se.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ni(),200)});let dl=()=>{var h,y,A,R,q,F,H,oe,se,Y,ye;fr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",fn.textContent=(R=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",Se.placeholder=(F=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?F:"How can I help...";let l=xe.querySelector("[data-persona-intro-card]");if(l){let Ne=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;l.style.display=Ne?"":"none",Ne?(xe.classList.remove("persona-gap-3"),xe.classList.add("persona-gap-6")):(xe.classList.remove("persona-gap-6"),xe.classList.add("persona-gap-3"))}!((se=(oe=r.sendButton)==null?void 0:oe.useIcon)!=null&&se)&&!(O!=null&&O.isStreaming())&&(ue.textContent=(ye=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ye:"Send"),Se.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Se.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{u(p=>({...p,sessionId:l}))}});let yo=null,eg=()=>{yo==null&&(yo=setInterval(()=>{let l=ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(yo),yo=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=ya(p-y))})},100))};O=new Ea(r,{onMessagesChanged(l){var y;gs(ze,l,We),eg(),Do(l),Rn(!Cr),Gm(l);let p=[...l].reverse().find(A=>A.role==="user");l.length===0&&un(),!Fo||ho?(Fo=!0,Oo=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Oo&&(Oo=p.id,Km(p.id));let h=ft.lastUserMessageId;p&&p.id!==h&&(ft.lastUserMessageId=p.id,s.emit("user:message",p)),ft.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Yr(l),Uo()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};it(nn,(A=>{var R,q,F,H;return A==="idle"?(R=p.idleText)!=null?R:vn.idle:A==="connecting"?(q=p.connectingText)!=null?q:vn.connecting:A==="connected"?(F=p.connectedText)!=null?F:vn.connected:A==="error"?(H=p.errorText)!=null?H:vn.error:vn[A]})(l),p,l)},onStreamingChanged(l){Cr=l,ti(l),O&&gs(ze,O.getMessages(),We),l||Rn(!0),Uo()},onVoiceStatusChanged(l){var p,h;if(s.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Fr(),zo();break;case"processing":Fr(),sg();break;case"speaking":Fr(),ag();break;default:l==="idle"&&O.isBargeInActive()?(Fr(),zo(),U==null||U.setAttribute("aria-label","End voice session")):(ft.active=!1,Fr(),er("system"),Wn());break}},onArtifactsState(l){Fn=l,$n(),Yr()}}),At.current=O;let ri=null;if(O.onReadAloudChange((l,p)=>{var A;jr=l,Vr=p,Kr();let h=l!=null?l:ri;l&&(ri=l);let y=h&&(A=O.getMessages().find(R=>R.id===h))!=null?A:null;s.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(ri=null)}),Fo=!0,((wc=(xc=r.voiceRecognition)==null?void 0:xc.provider)==null?void 0:wc.type)==="runtype")try{O.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&O.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(fe||r.onSSEEvent)&&O.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),re==null||re.processEvent(l,p),fe==null||fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),c&&c.then(l=>{var p,h,y;if(l){if(l.metadata&&(d=el(l.metadata),P.syncFromMetadata()),(p=l.messages)!=null&&p.length){ho=!0;try{O.hydrateMessages(l.messages)}finally{ho=!1}}(h=l.artifacts)!=null&&h.length&&O.hydrateArtifacts(l.artifacts,(y=l.selectedArtifactId)!=null?y:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let pl=()=>{var p,h,y;!D()||E||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||_t(!0,"auto")},ul=l=>{var A;if(l.preventDefault(),O.isStreaming()){O.cancel(),re==null||re.reset(),V==null||V.update();return}let p=Se.value.trim(),h=(A=vt==null?void 0:vt.hasAttachments())!=null?A:!1;if(!p&&!h)return;pl();let y;h&&(y=[],y.push(...vt.getContentParts()),p&&y.push(Ti(p))),Se.value="",Se.style.height="auto",sa(),O.sendMessage(p,{contentParts:y}),h&&vt.clearAttachments()},tg=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},oi={...Ia},si=!1,sa=()=>{oi={...Ia}},ng=()=>O.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),rg=l=>{if(!Se)return;si=!0,Se.value=l,Se.dispatchEvent(new Event("input",{bubbles:!0})),si=!1;let p=Se.value.length;Se.setSelectionRange(p,p)},ml=()=>{si||sa()},gl=l=>{if(Se){if(tg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Se.selectionStart===0&&Se.selectionEnd===0,h=Nu({direction:l.key==="ArrowUp"?"up":"down",history:ng(),currentValue:Se.value,atStart:p,state:oi});if(oi=h.state,h.handled){l.preventDefault(),h.value!==void 0&&rg(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(O.isStreaming()){l.preventDefault();return}sa(),l.preventDefault(),ue.click()}}},fl=l=>{l.key!=="Escape"||l.isComposing||O.isStreaming()&&l.composedPath().includes(le)&&(O.cancel(),re==null||re.reset(),V==null||V.update(),sa(),l.preventDefault(),l.stopImmediatePropagation())},hl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let p=bv(l.clipboardData);p.length!==0&&(l.preventDefault(),await vt.handleFiles(p))},tr=null,Mr=!1,qo=null,ut=null,yl=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,aa=(l="user")=>{var R,q,F,H,oe,se,Y;if(Mr||O.isStreaming())return;let p=yl();if(!p)return;tr=new p;let y=(q=((R=r.voiceRecognition)!=null?R:{}).pauseDuration)!=null?q:2e3;tr.continuous=!0,tr.interimResults=!0,tr.lang="en-US";let A=Se.value;tr.onresult=ye=>{let Ne="",we="";for(let _e=0;_e<ye.results.length;_e++){let mt=ye.results[_e],ot=mt[0].transcript;mt.isFinal?Ne+=ot+" ":we=ot}let tt=A+Ne+we;Se.value=tt,qo&&clearTimeout(qo),(Ne||we)&&(qo=window.setTimeout(()=>{let _e=Se.value.trim();_e&&tr&&Mr&&(eo(),Se.value="",Se.style.height="auto",O.sendMessage(_e,{viaVoice:!0}))},y))},tr.onerror=ye=>{ye.error!=="no-speech"&&eo()},tr.onend=()=>{if(Mr){let ye=Se.value.trim();ye&&ye!==A.trim()&&(Se.value="",Se.style.height="auto",O.sendMessage(ye,{viaVoice:!0})),eo()}};try{if(tr.start(),Mr=!0,ft.active=!0,l!=="system"&&(ft.manuallyDeactivated=!1),er(l),Wn(),U){let ye=(F=r.voiceRecognition)!=null?F:{};ut={backgroundColor:U.style.backgroundColor,color:U.style.color,borderColor:U.style.borderColor,iconName:(H=ye.iconName)!=null?H:"mic",iconSize:parseFloat((Y=(se=ye.iconSize)!=null?se:(oe=r.sendButton)==null?void 0:oe.size)!=null?Y:"40")||24};let Ne=ye.recordingBackgroundColor,we=ye.recordingIconColor,tt=ye.recordingBorderColor;if(U.classList.add("persona-voice-recording"),U.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",U.style.color=we!=null?we:"var(--persona-voice-recording-indicator, #ffffff)",we){let _e=U.querySelector("svg");_e&&_e.setAttribute("stroke",we)}tt&&(U.style.borderColor=tt),U.setAttribute("aria-label","Stop voice recognition")}}catch{eo("system")}},eo=(l="user")=>{if(Mr){if(Mr=!1,qo&&(clearTimeout(qo),qo=null),tr){try{tr.stop()}catch{}tr=null}if(ft.active=!1,er(l),Wn(),U){if(U.classList.remove("persona-voice-recording"),ut){U.style.backgroundColor=ut.backgroundColor,U.style.color=ut.color,U.style.borderColor=ut.borderColor;let p=U.querySelector("svg");p&&p.setAttribute("stroke",ut.color||"currentColor"),ut=null}U.setAttribute("aria-label","Start voice recognition")}}},og=(l,p)=>{var ot,He,Ie,qe,Ve,yt,L,De,Be;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ot=l==null?void 0:l.provider)==null?void 0:ot.type)==="runtype",A=((He=l==null?void 0:l.provider)==null?void 0:He.type)==="custom";if(!(h||y||A))return null;let q=b("div","persona-send-button-wrapper"),F=b("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 H=(Ie=l==null?void 0:l.iconName)!=null?Ie:"mic",oe=(qe=p==null?void 0:p.size)!=null?qe:"40px",se=(Ve=l==null?void 0:l.iconSize)!=null?Ve:oe,Y=parseFloat(se)||24,ye=(yt=l==null?void 0:l.backgroundColor)!=null?yt:p==null?void 0:p.backgroundColor,Ne=(L=l==null?void 0:l.iconColor)!=null?L:p==null?void 0:p.textColor;F.style.width=se,F.style.height=se,F.style.minWidth=se,F.style.minHeight=se,F.style.fontSize="18px",F.style.lineHeight="1",Ne?F.style.color=Ne:F.style.color="var(--persona-text, #111827)";let tt=Ce(H,Y,Ne||"currentColor",1.5);tt?F.appendChild(tt):F.textContent="\u{1F3A4}",ye?F.style.backgroundColor=ye:F.style.backgroundColor="",l!=null&&l.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l!=null&&l.borderColor&&(F.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),q.appendChild(F);let _e=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((Be=l==null?void 0:l.showTooltip)!=null?Be:!1)&&_e){let me=b("div","persona-send-button-tooltip");me.textContent=_e,q.appendChild(me)}return{micButton:F,micButtonWrapper:q}},ai=()=>{var p,h,y,A,R;if(!U||ut)return;let l=(p=r.voiceRecognition)!=null?p:{};ut={backgroundColor:U.style.backgroundColor,color:U.style.color,borderColor:U.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((R=(A=l.iconSize)!=null?A:(y=r.sendButton)==null?void 0:y.size)!=null?R:"40")||24}},ii=(l,p)=>{var R,q,F,H,oe;if(!U)return;let h=U.querySelector("svg");h&&h.remove();let y=(oe=ut==null?void 0:ut.iconSize)!=null?oe:parseFloat((H=(F=(R=r.voiceRecognition)==null?void 0:R.iconSize)!=null?F:(q=r.sendButton)==null?void 0:q.size)!=null?H:"40")||24,A=Ce(l,y,p,1.5);A&&U.appendChild(A)},ia=()=>{U&&U.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},zo=()=>{var A;if(!U)return;ai();let l=(A=r.voiceRecognition)!=null?A:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(ia(),U.classList.add("persona-voice-recording"),U.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",U.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let R=U.querySelector("svg");R&&R.setAttribute("stroke",h)}y&&(U.style.borderColor=y),U.setAttribute("aria-label","Stop voice recognition")},sg=()=>{var F,H,oe,se,Y,ye,Ne,we;if(!U)return;ai();let l=(F=r.voiceRecognition)!=null?F:{},p=O.getVoiceInterruptionMode(),h=(H=l.processingIconName)!=null?H:"loader",y=(se=(oe=l.processingIconColor)!=null?oe:ut==null?void 0:ut.color)!=null?se:"",A=(ye=(Y=l.processingBackgroundColor)!=null?Y:ut==null?void 0:ut.backgroundColor)!=null?ye:"",R=(we=(Ne=l.processingBorderColor)!=null?Ne:ut==null?void 0:ut.borderColor)!=null?we:"";ia(),U.classList.add("persona-voice-processing"),U.style.backgroundColor=A,U.style.borderColor=R;let q=y||"currentColor";U.style.color=q,ii(h,q),U.setAttribute("aria-label","Processing voice input"),p==="none"&&(U.style.cursor="default")},ag=()=>{var oe,se,Y,ye,Ne,we,tt,_e,mt,ot,He,Ie;if(!U)return;ai();let l=(oe=r.voiceRecognition)!=null?oe:{},p=O.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(se=l.speakingIconName)!=null?se:h,A=(we=l.speakingIconColor)!=null?we:p==="barge-in"?(ye=(Y=l.recordingIconColor)!=null?Y:ut==null?void 0:ut.color)!=null?ye:"":(Ne=ut==null?void 0:ut.color)!=null?Ne:"",R=(mt=l.speakingBackgroundColor)!=null?mt:p==="barge-in"?(tt=l.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(_e=ut==null?void 0:ut.backgroundColor)!=null?_e:"",q=(Ie=l.speakingBorderColor)!=null?Ie:p==="barge-in"?(ot=l.recordingBorderColor)!=null?ot:"":(He=ut==null?void 0:ut.borderColor)!=null?He:"";ia(),U.classList.add("persona-voice-speaking"),U.style.backgroundColor=R,U.style.borderColor=q;let F=A||"currentColor";U.style.color=F,ii(y,F);let H=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";U.setAttribute("aria-label",H),p==="none"&&(U.style.cursor="default"),p==="barge-in"&&U.classList.add("persona-voice-recording")},Fr=()=>{var l,p,h;U&&(ia(),ut&&(U.style.backgroundColor=(l=ut.backgroundColor)!=null?l:"",U.style.color=(p=ut.color)!=null?p:"",U.style.borderColor=(h=ut.borderColor)!=null?h:"",ii(ut.iconName,ut.color||"currentColor"),ut=null),U.style.cursor="",U.setAttribute("aria-label","Start voice recognition"))},la=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=O.getVoiceStatus(),y=O.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Wn(),er("user"),Fr()});return}O.toggleVoice().then(()=>{ft.active=O.isVoiceActive(),ft.manuallyDeactivated=!O.isVoiceActive(),Wn(),er("user"),O.isVoiceActive()?zo():Fr()});return}if(Mr){let h=Se.value.trim();ft.manuallyDeactivated=!0,Wn(),eo("user"),h&&(Se.value="",Se.style.height="auto",O.sendMessage(h))}else ft.manuallyDeactivated=!1,Wn(),aa("user")};Dn=la,U&&(U.addEventListener("click",la),ct.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Fr()):eo("system"),U&&U.removeEventListener("click",la)}));let ig=s.on("assistant:complete",()=>{ms&&(ft.active||ft.manuallyDeactivated||ms==="assistant"&&!ft.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!ft.active&&!ft.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?O.toggleVoice().then(()=>{ft.active=O.isVoiceActive(),er("auto"),O.isVoiceActive()&&zo()}):aa("auto"))},600))});ct.push(ig);let lg=s.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});ct.push(lg);let bl=()=>{_t(!E,"user")},Qt=null,on=null;if(T&&!D()){let{instance:l,element:p}=Fi({config:r,plugins:o,onToggle:bl});Qt=l,l||(on=p)}Qt?n.appendChild(Qt.element):on&&n.appendChild(on),bs(),Do(),dl(),ti(O.isStreaming()),Ze()==="follow"?Rn(!0):Zr(),ra(),N&&(!T||D()?setTimeout(()=>ni(),0):E&&setTimeout(()=>ni(),200));let vs=()=>{var H,oe,se,Y,ye,Ne,we,tt,_e,mt,ot,He,Ie,qe,Ve,yt,L,De,Be,me,Nt,Bt;if(D()){Pn(),bs();return}let l=mn(r),p=(oe=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?oe:!1,h=l||p||((Y=(se=r.launcher)==null?void 0:se.fullHeight)!=null?Y:!1),y=(ye=n.ownerDocument.defaultView)!=null?ye:window,A=(we=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?we:!0,R=(_e=(tt=r.launcher)==null?void 0:tt.mobileBreakpoint)!=null?_e:640,q=y.innerWidth<=R,F=A&&q&&T;try{if(F){he(),ss(n,r);return}if(I&&(I=!1,he(),ss(n,r)),!T&&!l){de.style.height="",de.style.width="";return}if(!p&&!l){let qt=(ot=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?ot:r==null?void 0:r.launcherWidth,xt=qt!=null?qt:Ur;de.style.width=xt,de.style.maxWidth=xt}if(vr(),!h){let qt=y.innerHeight,xt=64,$t=(Ie=(He=r.launcher)==null?void 0:He.heightOffset)!=null?Ie:0,Vn=Math.max(200,qt-xt),Xt=Math.min(640,Vn),Ge=Math.max(200,Xt-$t);de.style.height=`${Ge}px`}}finally{if(Pn(),bs(),E&&T){let xt=((qe=n.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((yt=(Ve=r.launcher)==null?void 0:Ve.mobileBreakpoint)!=null?yt:640),$t=(De=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?De:!1,Vn=(me=(Be=r.launcher)==null?void 0:Be.mobileFullscreen)!=null?me:!0,Xt=mn(r)&&Vn&&xt,Ge=$t||Vn&&xt&&T||Xt;if(Ge&&!rn){let Et=n.getRootNode(),tn=Et instanceof ShadowRoot?Et.host:n.closest(".persona-host");tn&&!Gt&&(Gt=Hi(tn,(Bt=(Nt=r.launcher)==null?void 0:Nt.zIndex)!=null?Bt:xn)),rn=Bi(n.ownerDocument)}else Ge||(Gt==null||Gt(),Gt=null,rn==null||rn(),rn=null)}}};vs();let vl=(Cc=n.ownerDocument.defaultView)!=null?Cc:window;if(vl.addEventListener("resize",vs),ct.push(()=>vl.removeEventListener("resize",vs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Pn()});l.observe(Re),ct.push(()=>l.disconnect())}qn=xe.scrollTop;let xl=qr(xe),cg=()=>{let l=xe.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:xe.ownerDocument.getSelection()},li=()=>qu(cg(),xe),wl=()=>{let l=xe.scrollTop,p=qr(xe),h=p<xl;if(xl=p,Ze()!=="follow"){qn=l,Xe();return}let{action:y,nextLastScrollTop:A}=Ra({following:Un.isFollowing(),currentScrollTop:l,lastScrollTop:qn,nearBottom:Io(xe,_o),userScrollThreshold:ta,isAutoScrolling:cr||fo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qn=A,y==="resume"){li()||Dr();return}y==="pause"&&Mt()};if(xe.addEventListener("scroll",wl,{passive:!0}),ct.push(()=>xe.removeEventListener("scroll",wl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{jn()});l.observe(ze),l.observe(xe),ct.push(()=>l.disconnect())}let Cl=()=>{Ze()==="follow"&&Un.isFollowing()&&li()&&Mt()},Al=xe.ownerDocument;Al.addEventListener("selectionchange",Cl),ct.push(()=>{Al.removeEventListener("selectionchange",Cl)});let Sl=l=>{if(Ze()!=="follow")return;let p=Ha({following:Un.isFollowing(),deltaY:l.deltaY,nearBottom:Io(xe,_o),resumeWhenNearBottom:!0});p==="pause"?Mt():p==="resume"&&!li()&&Dr()};xe.addEventListener("wheel",Sl,{passive:!0}),ct.push(()=>xe.removeEventListener("wheel",Sl)),lt.addEventListener("click",()=>{un(),xe.scrollTop=xe.scrollHeight,qn=xe.scrollTop,Dr(),Rn(!0),Xe()}),ct.push(()=>lt.remove()),ct.push(()=>{_(),un()});let Tl=()=>{je&&(wr&&(je.removeEventListener("click",wr),wr=null),B()?(je.style.display="",wr=()=>{_t(!1,"user")},je.addEventListener("click",wr)):je.style.display="none")};Tl(),(()=>{let{clearChatButton:l}=X;l&&l.addEventListener("click",()=>{O.clearMessages(),Ar.clear(),Dr(),Zo(X.composerOverlay);try{localStorage.removeItem(ds),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ds}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ds)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},P.syncFromMetadata(),fe==null||fe.clear(),re==null||re.reset(),V==null||V.update()})})(),Pt&&Pt.addEventListener("submit",ul),Se==null||Se.addEventListener("keydown",gl),Se==null||Se.addEventListener("input",ml),Se==null||Se.addEventListener("paste",hl);let Ml=(Ac=n.ownerDocument)!=null?Ac:document;Ml.addEventListener("keydown",fl,!0);let El="persona-attachment-drop-active",xs=0,ci=()=>{xs=0,le.classList.remove(El)},jo=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&vt!==null},kl=l=>{!Za(l.dataTransfer)||!jo()||(xs++,xs===1&&le.classList.add(El))},Ll=l=>{!Za(l.dataTransfer)||!jo()||(xs--,xs<=0&&ci())},Pl=l=>{!Za(l.dataTransfer)||!jo()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Il=l=>{var h;if(!Za(l.dataTransfer)||!jo())return;l.preventDefault(),l.stopPropagation(),ci();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&vt.handleFiles(p)},to=!0;le.addEventListener("dragenter",kl,to),le.addEventListener("dragleave",Ll,to),n.addEventListener("dragover",Pl,to),n.addEventListener("drop",Il,to);let ca=n.ownerDocument,Wl=l=>{jo()&&l.preventDefault()},Rl=l=>{jo()&&l.preventDefault()};ca.addEventListener("dragover",Wl),ca.addEventListener("drop",Rl),ct.push(()=>{Pt&&Pt.removeEventListener("submit",ul),Se==null||Se.removeEventListener("keydown",gl),Se==null||Se.removeEventListener("input",ml),Se==null||Se.removeEventListener("paste",hl),Ml.removeEventListener("keydown",fl,!0)}),ct.push(()=>{le.removeEventListener("dragenter",kl,to),le.removeEventListener("dragleave",Ll,to),n.removeEventListener("dragover",Pl,to),n.removeEventListener("drop",Il,to),ca.removeEventListener("dragover",Wl),ca.removeEventListener("drop",Rl),ci()}),ct.push(()=>{O.cancel()}),Qt?ct.push(()=>{Qt==null||Qt.destroy()}):on&&ct.push(()=>{on==null||on.remove()});let en={update(l){var yn,Tn,Er,cn,Mn,En,Co,ws,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,Uc,qc,zc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,qd,zd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Mp,Ep,kp;let p=r.toolCall,h=r.messageActions,y=(yn=r.layout)==null?void 0:yn.messages,A=r.colorScheme,R=r.loadingIndicator,q=r.iterationDisplay,F=(Tn=r.features)==null?void 0:Tn.showReasoning,H=(Er=r.features)==null?void 0:Er.showToolCalls,oe=(cn=r.features)==null?void 0:cn.toolCallDisplay,se=(Mn=r.features)==null?void 0:Mn.reasoningDisplay;r={...r,...l},he(),ss(n,r),Ja(n,r),Ya(n,r),$n(),r.colorScheme!==A&&us();let Y=Xi.getForInstance(r.plugins);o.length=0,o.push(...Y),T=(Co=(En=r.launcher)==null?void 0:En.enabled)!=null?Co:!0,M=(Pc=(ws=r.launcher)==null?void 0:ws.autoExpand)!=null?Pc:!1,$e=(Wc=(Ic=r.features)==null?void 0:Ic.showReasoning)!=null?Wc:!0,ve=(Hc=(Rc=r.features)==null?void 0:Rc.showToolCalls)!=null?Hc:!0,Oe=(Dc=(Bc=r.features)==null?void 0:Bc.scrollToBottom)!=null?Dc:{};let ye=Ze();Ae=(Fc=(Nc=r.features)==null?void 0:Nc.scrollBehavior)!=null?Fc:{},ye!==Ze()&&(un(),Dr()),hr(),Xe();let Ne=Pe;if(Pe=(_c=(Oc=r.features)==null?void 0:Oc.showEventStreamToggle)!=null?_c:!1,Pe&&!Ne){if(fe||(Q=new Xs(ne),fe=new Qs(ae,Q),re=re!=null?re:new Js,Q.open().then(()=>fe==null?void 0:fe.restore()).catch(()=>{}),O.setSSEEventCallback((Z,St)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,Z,St),re==null||re.processEvent(Z,St),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(St)})})),!ht&&Te){let Z=(Uc=($c=r.features)==null?void 0:$c.eventStream)==null?void 0:Uc.classNames,St="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"+(Z!=null&&Z.toggleButton?" "+Z.toggleButton:"");ht=b("button",St),ht.style.width="28px",ht.style.height="28px",ht.style.color=Ln.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let Ut=Ce("activity","18px","currentColor",1.5);Ut&&ht.appendChild(Ut);let st=X.clearChatButtonWrapper,kt=X.closeButtonWrapper,an=st||kt;an&&an.parentNode===Te?Te.insertBefore(ht,an):Te.appendChild(ht),ht.addEventListener("click",()=>{ee?ar():Lr()})}}else!Pe&&Ne&&(ar(),ht&&(ht.remove(),ht=null),fe==null||fe.clear(),Q==null||Q.destroy(),fe=null,Q=null,re==null||re.reset(),re=null);if(((qc=r.launcher)==null?void 0:qc.enabled)===!1&&Qt&&(Qt.destroy(),Qt=null),((zc=r.launcher)==null?void 0:zc.enabled)===!1&&on&&(on.remove(),on=null),((jc=r.launcher)==null?void 0:jc.enabled)!==!1&&!Qt&&!on){let{instance:Z,element:St}=Fi({config:r,plugins:o,onToggle:bl});Qt=Z,Z||(on=St),n.appendChild(St)}Qt&&Qt.update(r),pe&&((Vc=r.launcher)==null?void 0:Vc.title)!==void 0&&(pe.textContent=r.launcher.title),ke&&((Kc=r.launcher)==null?void 0:Kc.subtitle)!==void 0&&(ke.textContent=r.launcher.subtitle);let we=(Gc=r.layout)==null?void 0:Gc.header;if((we==null?void 0:we.layout)!==C&&Te){let Z=we?_a(r,we,{showClose:B(),onClose:()=>_t(!1,"user")}):Wo({config:r,showClose:B(),onClose:()=>_t(!1,"user")});nt.replaceHeader(Z),Te=nt.header.element,S=nt.header.iconHolder,pe=nt.header.headerTitle,ke=nt.header.headerSubtitle,je=nt.header.closeButton,C=we==null?void 0:we.layout}else if(we&&(S&&(S.style.display=we.showIcon===!1?"none":""),pe&&(pe.style.display=we.showTitle===!1?"none":""),ke&&(ke.style.display=we.showSubtitle===!1?"none":""),je&&(je.style.display=we.showCloseButton===!1?"none":""),X.clearChatButtonWrapper)){let Z=we.showClearChat;if(Z!==void 0){X.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:St}=X;St&&!St.classList.contains("persona-absolute")&&(Z?St.classList.remove("persona-ml-auto"):St.classList.add("persona-ml-auto"))}}let _e=((Qc=r.layout)==null?void 0:Qc.showHeader)!==!1;Te&&(Te.style.display=_e?"":"none");let mt=((Xc=r.layout)==null?void 0:Xc.showFooter)!==!1;Re&&(Re.style.display=mt?"":"none"),Pn(),Xe(),T!==W?T?_t(M,"auto"):(E=!0,bs()):M!==k&&_t(M,"auto"),k=M,W=T,vs(),Tl();let Ie=JSON.stringify(l.toolCall)!==JSON.stringify(p),qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ve=JSON.stringify((Jc=r.layout)==null?void 0:Jc.messages)!==JSON.stringify(y),yt=((Yc=r.loadingIndicator)==null?void 0:Yc.render)!==(R==null?void 0:R.render)||((Zc=r.loadingIndicator)==null?void 0:Zc.renderIdle)!==(R==null?void 0:R.renderIdle)||((ed=r.loadingIndicator)==null?void 0:ed.showBubble)!==(R==null?void 0:R.showBubble),L=r.iterationDisplay!==q,De=((nd=(td=r.features)==null?void 0:td.showReasoning)!=null?nd:!0)!==(F!=null?F:!0)||((od=(rd=r.features)==null?void 0:rd.showToolCalls)!=null?od:!0)!==(H!=null?H:!0)||JSON.stringify((sd=r.features)==null?void 0:sd.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify((ad=r.features)==null?void 0:ad.reasoningDisplay)!==JSON.stringify(se);(Ie||qe||Ve||yt||L||De)&&O&&(No++,gs(ze,O.getMessages(),We));let me=(id=r.launcher)!=null?id:{},Nt=(ld=me.headerIconHidden)!=null?ld:!1,Bt=(dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.showIcon,qt=Nt||Bt===!1,xt=me.headerIconName,$t=(pd=me.headerIconSize)!=null?pd:"48px";if(S){let Z=le.querySelector(".persona-border-b-persona-divider"),St=Z==null?void 0:Z.querySelector(".persona-flex-col");if(qt)S.style.display="none",Z&&St&&!Z.contains(St)&&Z.insertBefore(St,Z.firstChild);else{if(S.style.display="",S.style.height=$t,S.style.width=$t,Z&&St&&(Z.contains(S)?S.nextSibling!==St&&(S.remove(),Z.insertBefore(S,St)):Z.insertBefore(S,St)),xt){let st=parseFloat($t)||24,kt=Ce(xt,st*.6,"currentColor",1);kt?S.replaceChildren(kt):S.textContent=(ud=me.agentIconText)!=null?ud:"\u{1F4AC}"}else if(me.iconUrl){let st=S.querySelector("img");if(st)st.src=me.iconUrl,st.style.height=$t,st.style.width=$t;else{let kt=document.createElement("img");kt.src=me.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=$t,kt.style.width=$t,S.replaceChildren(kt)}}else{let st=S.querySelector("svg"),kt=S.querySelector("img");(st||kt)&&S.replaceChildren(),S.textContent=(md=me.agentIconText)!=null?md:"\u{1F4AC}"}let Ut=S.querySelector("img");Ut&&(Ut.style.height=$t,Ut.style.width=$t)}}let Vn=(fd=(gd=r.layout)==null?void 0:gd.header)==null?void 0:fd.showTitle,Xt=(yd=(hd=r.layout)==null?void 0:hd.header)==null?void 0:yd.showSubtitle;if(pe&&(pe.style.display=Vn===!1?"none":""),ke&&(ke.style.display=Xt===!1?"none":""),je){((vd=(bd=r.layout)==null?void 0:bd.header)==null?void 0:vd.showCloseButton)===!1?je.style.display="none":je.style.display="";let St=(xd=me.closeButtonSize)!=null?xd:"32px",Ut=(wd=me.closeButtonPlacement)!=null?wd:"inline";je.style.height=St,je.style.width=St;let{closeButtonWrapper:st}=X,kt=Ut==="top-right",an=st==null?void 0:st.classList.contains("persona-absolute");if(st&&kt!==an)if(st.remove(),kt)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",le.style.position="relative",le.appendChild(st);else{let dt=(Ad=(Cd=me.clearChat)==null?void 0:Cd.placement)!=null?Ad:"inline",ln=(Td=(Sd=me.clearChat)==null?void 0:Sd.enabled)!=null?Td:!0;st.className=ln&&dt==="inline"?"":"persona-ml-auto";let Bn=le.querySelector(".persona-border-b-persona-divider");Bn&&Bn.appendChild(st)}if(je.style.color=me.closeButtonColor||Ln.actionIconColor,me.closeButtonBackgroundColor?(je.style.backgroundColor=me.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let dt=me.closeButtonBorderWidth||"0px",ln=me.closeButtonBorderColor||"transparent";je.style.border=`${dt} solid ${ln}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");me.closeButtonBorderRadius?(je.style.borderRadius=me.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(je.style.paddingLeft=me.closeButtonPaddingX,je.style.paddingRight=me.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),me.closeButtonPaddingY?(je.style.paddingTop=me.closeButtonPaddingY,je.style.paddingBottom=me.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom="");let bn=(Md=me.closeButtonIconName)!=null?Md:"x",pr=(Ed=me.closeButtonIconText)!=null?Ed:"\xD7";je.innerHTML="";let kn=Ce(bn,"28px","currentColor",1);kn?je.appendChild(kn):je.textContent=pr;let Kt=(kd=me.closeButtonTooltipText)!=null?kd:"Close chat",Gn=(Ld=me.closeButtonShowTooltip)!=null?Ld:!0;if(je.setAttribute("aria-label",Kt),st&&(st._cleanupTooltip&&(st._cleanupTooltip(),delete st._cleanupTooltip),Gn&&Kt)){let dt=null,ln=()=>{if(dt||!je)return;let Ao=je.ownerDocument,Cs=Ao.body;if(!Cs)return;dt=kr(Ao,"div","persona-clear-chat-tooltip"),dt.textContent=Kt;let As=kr(Ao,"div");As.className="persona-clear-chat-tooltip-arrow",dt.appendChild(As);let So=je.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(io),dt.style.left=`${So.left+So.width/2}px`,dt.style.top=`${So.top-8}px`,dt.style.transform="translate(-50%, -100%)",Cs.appendChild(dt)},Bn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};st.addEventListener("mouseenter",ln),st.addEventListener("mouseleave",Bn),je.addEventListener("focus",ln),je.addEventListener("blur",Bn),st._cleanupTooltip=()=>{Bn(),st&&(st.removeEventListener("mouseenter",ln),st.removeEventListener("mouseleave",Bn)),je&&(je.removeEventListener("focus",ln),je.removeEventListener("blur",Bn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:Et}=X;if(Ge){let Z=(Pd=me.clearChat)!=null?Pd:{},St=(Id=Z.enabled)!=null?Id:!0,Ut=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showClearChat,st=Ut!==void 0?Ut:St,kt=(Hd=Z.placement)!=null?Hd:"inline";if(Et){Et.style.display=st?"":"none";let{closeButtonWrapper:an}=X;!D()&&an&&!an.classList.contains("persona-absolute")&&(st?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let bn=kt==="top-right",pr=Et.classList.contains("persona-absolute");if(!D()&&bn!==pr&&st){if(Et.remove(),bn)Et.className="persona-absolute persona-top-4 persona-z-50",Et.style.right="48px",le.style.position="relative",le.appendChild(Et);else{Et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Et.style.right="";let Kt=le.querySelector(".persona-border-b-persona-divider"),Gn=X.closeButtonWrapper;Kt&&Gn&&Gn.parentElement===Kt?Kt.insertBefore(Et,Gn):Kt&&Kt.appendChild(Et)}let kn=X.closeButtonWrapper;kn&&!kn.classList.contains("persona-absolute")&&(bn?kn.classList.add("persona-ml-auto"):kn.classList.remove("persona-ml-auto"))}}if(st){if(!D()){let dt=(Bd=Z.size)!=null?Bd:"32px";Ge.style.height=dt,Ge.style.width=dt}let an=(Dd=Z.iconName)!=null?Dd:"refresh-cw",bn=(Nd=Z.iconColor)!=null?Nd:"";Ge.style.color=bn||Ln.actionIconColor,Ge.innerHTML="";let pr=D()?"14px":"20px",kn=Ce(an,pr,"currentColor",2);if(kn&&Ge.appendChild(kn),Z.backgroundColor?(Ge.style.backgroundColor=Z.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let dt=Z.borderWidth||"0px",ln=Z.borderColor||"transparent";Ge.style.border=`${dt} solid ${ln}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");Z.borderRadius?(Ge.style.borderRadius=Z.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),Z.paddingX?(Ge.style.paddingLeft=Z.paddingX,Ge.style.paddingRight=Z.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),Z.paddingY?(Ge.style.paddingTop=Z.paddingY,Ge.style.paddingBottom=Z.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Kt=(Fd=Z.tooltipText)!=null?Fd:"Clear chat",Gn=(Od=Z.showTooltip)!=null?Od:!0;if(Ge.setAttribute("aria-label",Kt),Et&&(Et._cleanupTooltip&&(Et._cleanupTooltip(),delete Et._cleanupTooltip),Gn&&Kt)){let dt=null,ln=()=>{if(dt||!Ge)return;let Ao=Ge.ownerDocument,Cs=Ao.body;if(!Cs)return;dt=kr(Ao,"div","persona-clear-chat-tooltip"),dt.textContent=Kt;let As=kr(Ao,"div");As.className="persona-clear-chat-tooltip-arrow",dt.appendChild(As);let So=Ge.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(io),dt.style.left=`${So.left+So.width/2}px`,dt.style.top=`${So.top-8}px`,dt.style.transform="translate(-50%, -100%)",Cs.appendChild(dt)},Bn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};Et.addEventListener("mouseenter",ln),Et.addEventListener("mouseleave",Bn),Ge.addEventListener("focus",ln),Ge.addEventListener("blur",Bn),Et._cleanupTooltip=()=>{Bn(),Et&&(Et.removeEventListener("mouseenter",ln),Et.removeEventListener("mouseleave",Bn)),Ge&&(Ge.removeEventListener("focus",ln),Ge.removeEventListener("blur",Bn))}}}}let tn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Yi],rr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ys.message,Ys.messageAndClick];P=Zi({parsers:tn,handlers:rr,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),We=Hm(r,P,te),O.updateConfig(r),gs(ze,O.getMessages(),We),Do(),dl(),ti(O.isStreaming());let Kn=((_d=r.voiceRecognition)==null?void 0:_d.enabled)===!0,bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),vo=((Ud=($d=r.voiceRecognition)==null?void 0:$d.provider)==null?void 0:Ud.type)==="runtype";if(Kn&&(bo||vo))if(!U||!rt){let Z=og(r.voiceRecognition,r.sendButton);Z&&(U=Z.micButton,rt=Z.micButtonWrapper,pt.insertBefore(rt,gn),U.addEventListener("click",la),U.disabled=O.isStreaming())}else{let Z=(qd=r.voiceRecognition)!=null?qd:{},St=(zd=r.sendButton)!=null?zd:{},Ut=(jd=Z.iconName)!=null?jd:"mic",st=(Vd=St.size)!=null?Vd:"40px",kt=(Kd=Z.iconSize)!=null?Kd:st,an=parseFloat(kt)||24;U.style.width=kt,U.style.height=kt,U.style.minWidth=kt,U.style.minHeight=kt;let bn=(Qd=(Gd=Z.iconColor)!=null?Gd:St.textColor)!=null?Qd:"currentColor";U.innerHTML="";let pr=Ce(Ut,an,bn,2);pr?U.appendChild(pr):U.textContent="\u{1F3A4}";let kn=(Xd=Z.backgroundColor)!=null?Xd:St.backgroundColor;kn?U.style.backgroundColor=kn:U.style.backgroundColor="",bn?U.style.color=bn:U.style.color="var(--persona-text, #111827)",Z.borderWidth?(U.style.borderWidth=Z.borderWidth,U.style.borderStyle="solid"):(U.style.borderWidth="",U.style.borderStyle=""),Z.borderColor?U.style.borderColor=Z.borderColor:U.style.borderColor="",Z.paddingX?(U.style.paddingLeft=Z.paddingX,U.style.paddingRight=Z.paddingX):(U.style.paddingLeft="",U.style.paddingRight=""),Z.paddingY?(U.style.paddingTop=Z.paddingY,U.style.paddingBottom=Z.paddingY):(U.style.paddingTop="",U.style.paddingBottom="");let Kt=rt==null?void 0:rt.querySelector(".persona-send-button-tooltip"),Gn=(Jd=Z.tooltipText)!=null?Jd:"Start voice recognition";if(((Yd=Z.showTooltip)!=null?Yd:!1)&&Gn)if(Kt)Kt.textContent=Gn,Kt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Gn,rt==null||rt.insertBefore(ln,U)}else Kt&&(Kt.style.display="none");rt.style.display="",U.disabled=O.isStreaming()}else U&&rt&&(rt.style.display="none",((ep=(Zd=r.voiceRecognition)==null?void 0:Zd.provider)==null?void 0:ep.type)==="runtype"?O.isVoiceActive()&&O.toggleVoice():Mr&&eo());if(((tp=r.attachments)==null?void 0:tp.enabled)===!0)if(!ce||!K){let Z=(np=r.attachments)!=null?np:{},Ut=(op=((rp=r.sendButton)!=null?rp:{}).size)!=null?op:"40px";bt||(bt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),bt.style.display="none",Pt.insertBefore(bt,Se)),Ee||(Ee=document.createElement("input"),Ee.type="file",Ee.accept=((sp=Z.allowedTypes)!=null?sp:$r).join(","),Ee.multiple=((ap=Z.maxFiles)!=null?ap:4)>1,Ee.style.display="none",Ee.setAttribute("aria-label","Attach files"),Pt.insertBefore(Ee,Se)),ce=b("div","persona-send-button-wrapper"),K=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),K.type="button",K.setAttribute("aria-label",(ip=Z.buttonTooltipText)!=null?ip:"Attach file");let st=(lp=Z.buttonIconName)!=null?lp:"paperclip",kt=Ut,an=parseFloat(kt)||40,bn=Math.round(an*.6);K.style.width=kt,K.style.height=kt,K.style.minWidth=kt,K.style.minHeight=kt,K.style.fontSize="18px",K.style.lineHeight="1",K.style.backgroundColor="transparent",K.style.color="var(--persona-primary, #111827)",K.style.border="none",K.style.borderRadius="6px",K.style.transition="background-color 0.15s ease",K.addEventListener("mouseenter",()=>{K.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),K.addEventListener("mouseleave",()=>{K.style.backgroundColor="transparent"});let pr=Ce(st,bn,"currentColor",1.5);pr?K.appendChild(pr):K.textContent="\u{1F4CE}",K.addEventListener("click",Gn=>{Gn.preventDefault(),Ee==null||Ee.click()}),ce.appendChild(K);let kn=(cp=Z.buttonTooltipText)!=null?cp:"Attach file",Kt=b("div","persona-send-button-tooltip");Kt.textContent=kn,ce.appendChild(Kt),Ke.append(ce),!vt&&Ee&&bt&&(vt=Fs.fromConfig(Z),vt.setPreviewsContainer(bt),Ee.addEventListener("change",async()=>{vt&&(Ee!=null&&Ee.files)&&(await vt.handleFileSelect(Ee.files),Ee.value="")})),le.querySelector(".persona-attachment-drop-overlay")||le.appendChild(Bm(Z.dropOverlay))}else{ce.style.display="";let Z=(dp=r.attachments)!=null?dp:{};Ee&&(Ee.accept=((pp=Z.allowedTypes)!=null?pp:$r).join(","),Ee.multiple=((up=Z.maxFiles)!=null?up:4)>1),vt&&vt.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}else ce&&(ce.style.display="none"),vt&&vt.clearAttachments(),(mp=le.querySelector(".persona-attachment-drop-overlay"))==null||mp.remove();let zt=(gp=r.sendButton)!=null?gp:{},xo=(fp=zt.useIcon)!=null?fp:!1,no=(hp=zt.iconText)!=null?hp:"\u2191",ro=zt.iconName,Or=(yp=zt.tooltipText)!=null?yp:"Send message",wo=(bp=zt.showTooltip)!=null?bp:!1,dr=(vp=zt.size)!=null?vp:"40px",Je=zt.backgroundColor,sn=zt.textColor;if(xo){if(ue.style.width=dr,ue.style.height=dr,ue.style.minWidth=dr,ue.style.minHeight=dr,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.innerHTML="",sn?ue.style.color=sn:ue.style.color="var(--persona-button-primary-fg, #ffffff)",ro){let Z=parseFloat(dr)||24,St=(sn==null?void 0:sn.trim())||"currentColor",Ut=Ce(ro,Z,St,2);Ut?ue.appendChild(Ut):ue.textContent=no}else ue.textContent=no;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Je?(ue.style.backgroundColor=Je,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=(wp=(xp=r.copy)==null?void 0:xp.sendButtonLabel)!=null?wp:"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",Je?(ue.style.backgroundColor=Je,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),sn?ue.style.color=sn:ue.classList.add("persona-text-white");zt.borderWidth?(ue.style.borderWidth=zt.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),zt.borderColor?ue.style.borderColor=zt.borderColor:ue.style.borderColor="",zt.paddingX?(ue.style.paddingLeft=zt.paddingX,ue.style.paddingRight=zt.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),zt.paddingY?(ue.style.paddingTop=zt.paddingY,ue.style.paddingBottom=zt.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Ot=gn==null?void 0:gn.querySelector(".persona-send-button-tooltip");if(wo&&Or)if(Ot)Ot.textContent=Or,Ot.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=Or,gn==null||gn.insertBefore(Z,ue)}else Ot&&(Ot.style.display="none");let Ft=(Mp=(Cp=r.layout)==null?void 0:Cp.contentMaxWidth)!=null?Mp:D()?(Tp=(Sp=(Ap=r.launcher)==null?void 0:Ap.composerBar)==null?void 0:Sp.contentMaxWidth)!=null?Tp:"720px":void 0;Ft?(ze.style.maxWidth=Ft,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%",Pt&&(Pt.style.maxWidth=Ft,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Lt&&(Lt.style.maxWidth=Ft,Lt.style.marginLeft="auto",Lt.style.marginRight="auto")):(ze.style.maxWidth="",ze.style.marginLeft="",ze.style.marginRight="",ze.style.width="",Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""),Lt&&(Lt.style.maxWidth="",Lt.style.marginLeft="",Lt.style.marginRight=""));let gt=(Ep=r.statusIndicator)!=null?Ep:{},jt=(kp=gt.visible)!=null?kp:!0;if(nn.style.display=jt?"":"none",O){let Z=O.getStatus();it(nn,(Ut=>{var st,kt,an,bn;return Ut==="idle"?(st=gt.idleText)!=null?st:vn.idle:Ut==="connecting"?(kt=gt.connectingText)!=null?kt:vn.connecting:Ut==="connected"?(an=gt.connectedText)!=null?an:vn.connected:Ut==="error"?(bn=gt.errorText)!=null?bn:vn.error:vn[Ut]})(Z),gt,Z)}nn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Ct=gt.align==="left"?"persona-text-left":gt.align==="center"?"persona-text-center":"persona-text-right";nn.classList.add(Ct)},open(){B()&&_t(!0,"api")},close(){B()&&_t(!1,"api")},toggle(){B()&&_t(!E,"api")},clearChat(){An=!1,O.clearMessages(),Ar.clear(),Dr();try{localStorage.removeItem(ds),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ds}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ds)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},P.syncFromMetadata(),fe==null||fe.clear(),re==null||re.reset(),V==null||V.update()},setMessage(l){return!Se||O.isStreaming()?!1:(!E&&B()&&_t(!0,"system"),Se.value=l,Se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Se.value.trim();return p?(!E&&B()&&_t(!0,"system"),Se.value="",Se.style.height="auto",O.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return O.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(O.isVoiceActive()||(!E&&B()&&_t(!0,"system"),ft.manuallyDeactivated=!1,Wn(),O.toggleVoice().then(()=>{ft.active=O.isVoiceActive(),er("user"),O.isVoiceActive()&&zo()})),!0):Mr?!0:yl()?(!E&&B()&&_t(!0,"system"),ft.manuallyDeactivated=!1,Wn(),aa("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Wn(),er("user"),Fr()}),!0):!1:Mr?(ft.manuallyDeactivated=!0,Wn(),eo("user"),!0):!1},injectMessage(l){return!E&&B()&&_t(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!E&&B()&&_t(!0,"system");let p=O.injectAssistantMessage(l);return z&&(z=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),p},injectUserMessage(l){return!E&&B()&&_t(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!E&&B()&&_t(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!E&&B()&&_t(!0,"system"),O.injectMessageBatch(l)},injectComponentDirective(l){return!E&&B()&&_t(!0,"system"),O.injectComponentDirective(l)},injectTestMessage(l){!E&&B()&&_t(!0,"system"),O.injectTestEvent(l)},async connectStream(l,p){return O.connectStream(l,p)},__pushEventStreamEvent(l){fe&&(re==null||re.processEvent(l.type,l.payload),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Pe||!fe||Lr()},hideEventStream(){ee&&ar()},isEventStreamVisible(){return ee},showArtifacts(){sr(r)&&(An=!1,$n(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){sr(r)&&(An=!0,$n())},upsertArtifact(l){return sr(r)?(An=!1,O.upsertArtifact(l)):null},selectArtifact(l){sr(r)&&O.selectArtifact(l)},clearArtifacts(){sr(r)&&O.clearArtifacts()},getArtifacts(){var l;return(l=O==null?void 0:O.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=O==null?void 0:O.getSelectedArtifactId())!=null?l:null},focusInput(){return T&&!E&&!D()||!Se?!1:(Se.focus(),!0)},async resolveApproval(l,p,h){let A=O.getMessages().find(R=>{var q;return R.variant==="approval"&&((q=R.approval)==null?void 0:q.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){O.resolveWebMcpApproval(A.id,p);return}return O.resolveApproval(A.approval,p,h)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){u(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return B()&&E},isVoiceActive(){return ft.active},toggleReadAloud(l){O.toggleReadAloud(l)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(l){return O.getReadAloudState(l)},onReadAloudChange(l){return O.onReadAloudChange(l)},getState(){return{open:B()&&E,launcherEnabled:T,voiceActive:ft.active,streaming:O.isStreaming()}},showCSATFeedback(l){!E&&B()&&_t(!0,"system");let p=ze.querySelector(".persona-feedback-container");p&&p.remove();let h=Im({onSubmit:async(y,A)=>{var R;O.isClientTokenMode()&&await O.submitCSATFeedback(y,A),(R=l==null?void 0:l.onSubmit)==null||R.call(l,y,A)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&B()&&_t(!0,"system");let p=ze.querySelector(".persona-feedback-container");p&&p.remove();let h=Wm({onSubmit:async(y,A)=>{var R;O.isClientTokenMode()&&await O.submitNPSFeedback(y,A),(R=l==null?void 0:l.onSubmit)==null||R.call(l,y,A)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return O.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return O.submitNPSFeedback(l,p)},destroy(){yo!=null&&(clearInterval(yo),yo=null),ct.forEach(l=>l()),Me.remove(),Qe==null||Qe.remove(),Qt==null||Qt.destroy(),on==null||on.remove(),wr&&je.removeEventListener("click",wr)}};if((((Sc=t==null?void 0:t.debugTools)!=null?Sc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:h=>h?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ct.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=F=>{let H=F.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&en.focusInput()};if(window.addEventListener("persona:focusInput",p),ct.push(()=>{window.removeEventListener("persona:focusInput",p)}),Pe){let F=oe=>{let se=oe.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&en.showEventStream()},H=oe=>{let se=oe.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",H),ct.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",H)})}let h=F=>{let H=F.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&en.showArtifacts()},y=F=>{let H=F.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&en.hideArtifacts()},A=F=>{let H=F.detail;H!=null&&H.instanceId&&H.instanceId!==l||H!=null&&H.artifact&&en.upsertArtifact(H.artifact)},R=F=>{let H=F.detail;H!=null&&H.instanceId&&H.instanceId!==l||typeof(H==null?void 0:H.id)=="string"&&en.selectArtifact(H.id)},q=F=>{let H=F.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",q),ct.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",q)})}let nr=vv(r.persistState);if(nr&&B()){let l=xv(nr.storage),p=`${nr.keyPrefix}widget-open`,h=`${nr.keyPrefix}widget-voice`,y=`${nr.keyPrefix}widget-voice-mode`;if(l){let A=((Tc=nr.persist)==null?void 0:Tc.openState)&&l.getItem(p)==="true",R=((Mc=nr.persist)==null?void 0:Mc.voiceState)&&l.getItem(h)==="true",q=((Ec=nr.persist)==null?void 0:Ec.voiceState)&&l.getItem(y)==="true";if(A&&setTimeout(()=>{en.open(),setTimeout(()=>{var F;if(R||q)en.startVoiceRecognition();else if((F=nr.persist)!=null&&F.focusInput){let H=n.querySelector("textarea");H&&H.focus()}},100)},0),(kc=nr.persist)!=null&&kc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Lc=nr.persist)!=null&&Lc.voiceState&&(s.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),s.on("user:message",F=>{l.setItem(y,F.viaVoice?"true":"false")})),nr.clearOnChatClear){let F=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},H=()=>F();window.addEventListener("persona:clear-chat",H),ct.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return m&&B()&&setTimeout(()=>{en.open()},0),Uo(),ea||Rp().then(()=>{O&&(No++,Ar.clear(),gs(ze,O.getMessages(),We))}).catch(()=>{}),en};var wv=(n,e)=>{let t=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},Cv=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},Av=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},Sv=(n,e)=>{let t=n.parentElement;if(!t)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},Nm=(n,e)=>{var r,o;let t=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=t?"":"100%",n.style.display=t?"":"flex",n.style.flexDirection=t?"":"column",n.style.flex=t?"":"1 1 auto",n.style.minHeight=t?"":"0"},ol=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},Fm=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",ol(n)},tl=n=>{n.style.transition=""},nl=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},rl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},ei=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},Tv=(n,e,t,r,o)=>{o?t.parentElement!==e&&(n.replaceChildren(),e.replaceChildren(t,r),n.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),n.appendChild(t),n.appendChild(r))},Mv=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Om=(n,e,t,r,o,s,a)=>{var v,x,P,T,M,N;let i=mr(s),d=i.reveal==="push";Tv(n,e,t,r,d),Mv(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,m=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(T=(P=s==null?void 0:s.launcher)==null?void 0:P.mobileBreakpoint)!=null?T:640,g=c!=null?c.innerWidth<=f:!1;if(m&&g&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),nl(e),tl(r),Fm(r),rl(t),ei(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((N=(M=s==null?void 0:s.launcher)==null?void 0:M.zIndex)!=null?N:xn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),Fm(r),Cv(r,i.maxHeight),i.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",nl(e),tl(r),rl(t),ei(o,r);let k=i.animate?"transform 180ms ease":"none",W=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":W;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=k,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",tl(r),ol(r),ei(o,r);let k=wv(i.width,n.clientWidth),W=Math.max(0,n.clientWidth),C=i.animate?"margin-left 180ms ease":"none",I=i.side==="right"?a?-k:0:a?0:-k;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${W+k}px`,e.style.transition=C,e.style.marginLeft=`${I}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${W}px`,t.style.maxWidth=`${W}px`,t.style.minWidth=`${W}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",nl(e),ol(r),rl(t),ei(o,r);let k=i.reveal==="emerge";k?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let W=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${W}`,r.style.width=W,r.style.maxWidth=W,r.style.minWidth=W,r.style.minHeight="0",Av(r,i.maxHeight),r.style.overflow=k||I?"hidden":"visible",r.style.transition=C,k&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Ev=(n,e)=>{let t=n.ownerDocument.createElement("div");return Nm(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Nm(t,r)},destroy(){t.remove()}}},kv=(n,e)=>{var N,k,W,C;let{ownerDocument:t}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=n.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),m=t.createElement("div"),f=(k=(N=e==null?void 0:e.launcher)==null?void 0:N.enabled)==null||k?(C=(W=e==null?void 0:e.launcher)==null?void 0:W.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",m.dataset.personaDockRole="host",c.appendChild(m),r.insertBefore(a,n),d.appendChild(n);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),mr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Om(a,i,d,c,m,e,f)}),g.observe(a))},x=!1,P=()=>{Om(a,i,d,c,m,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,Sv(a,mr(e)))},T=a.ownerDocument.defaultView,M=()=>{P()};return T==null||T.addEventListener("resize",M),mr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),P(),{mode:"docked",host:m,shell:a,syncWidgetState(I){let D=I.launcherEnabled?I.open:!0;f!==D&&(f=D,P())},updateConfig(I){var D,B;e=I,((B=(D=e==null?void 0:e.launcher)==null?void 0:D.enabled)!=null?B:!0)===!1&&(f=!0),P()},destroy(){T==null||T.removeEventListener("resize",M),u(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},_m=(n,e)=>mn(e)?kv(n,e):Ev(n,e);var Zs={desktop:{w:1280,h:800},mobile:{w:390,h:844}},$m=.15,Um=1.5,sl="persona-preview-shell-theme",Lv={load:()=>null,save:()=>{},clear:()=>{}},Pv=["How do I get started?","Pricing & plans","Talk to support"];function al(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Iv(n){return n==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function qm(n){let e=Iv(n);return`* { box-sizing: border-box; }
111
+ `}if(!b&&!l){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Vt=p?"":"padding-top: 1.25em !important;",Ft=p?"":`z-index: ${(Ge=(kr=r.launcher)==null?void 0:kr.zIndex)!=null?Ge:Cn} !important;`;He.style.cssText+=Nt+Vt+Ft}je()};xr(),cs(t,r),ti(t,r),ni(t,r);let mt=[];mt.push(()=>{document.removeEventListener("keydown",Yr)});let nn=null,rn=null;mt.push(()=>{nn==null||nn(),nn=null,rn==null||rn(),rn=null}),Fn&&mt.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),mt.push(()=>{kn==null||kn(),kn=null,Br(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ce&&mt.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),be==null||be.destroy(),be=null,V==null||V.destroy(),V=null,$e=null});let wr=null,hs=()=>{wr&&(wr(),wr=null),r.colorScheme==="auto"&&(wr=Ou(()=>{cs(t,r)}))};hs(),mt.push(()=>{wr&&(wr(),wr=null)}),mt.push(a);let Dr=(wc=r.features)==null?void 0:wc.streamAnimation;if(Dr!=null&&Dr.type&&Dr.type!=="none"){let l=Vs(Dr.type,Dr.plugins);l&&(Di(l,t),mt.push(()=>Yu(t)))}let yo=bm(Ot),Cr=null,U,_o=l=>{var b,S;if(!U)return;let p=l!=null?l:U.getMessages(),h=((S=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:S.enabled)!==!1?su(p):null;h?yo.render(h,U,ne,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(B=>B.role==="user")?yo.render([],U,ne,p):yo.render(r.suggestionChips,U,ne,p,r.suggestionChipsConfig)},Ar=!1,Sr=zu(),Nr=new Map,Tr=new Map,lr=new Map,$o=0,sa=ko()!==null,Un=Da(),zn=0,cr=null,dr=!1,bo=!1,Fr=0,vn=null,Er=null,Uo=!1,vo=!1,zo=null,aa=4,qo=24,ia=80,jo=new Map,pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ys=(Ac=(Cc=r.voiceRecognition)==null?void 0:Cc.autoResume)!=null?Ac:!1,Zn=l=>{i.emit("voice:state",{active:pt.active,source:l,timestamp:Date.now()})},Hn=()=>{v(l=>({...l,voiceState:{active:pt.active,timestamp:Date.now(),manuallyDeactivated:pt.manuallyDeactivated}}))},la=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=ol(u.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);pt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<Iv&&setTimeout(()=>{var B,q;pt.active||(pt.manuallyDeactivated=!1,((q=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:q.type)==="runtype"?U.toggleVoice().then(()=>{pt.active=U.isVoiceActive(),Zn("restore"),U.isVoiceActive()&&Qo()}):da("restore"))},1e3)},Vo=()=>U?$m(U.getMessages()).filter(l=>!l.__skipPersist):[];function et(l){if(!(c!=null&&c.save))return;let h={messages:l?$m(l):U?Vo():[],metadata:u,artifacts:On.artifacts,selectedArtifactId:On.selectedId};try{let b=c.save(h);b instanceof Promise&&b.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let w=null,j=()=>He.querySelector("#persona-scroll-container")||Ce,z=()=>{w!==null&&(cancelAnimationFrame(w),w=null),dr=!1},Q=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),bo=!1,z()},ge=()=>{Fr>0?(Tn.textContent=String(Fr),Tn.style.display="",_t.setAttribute("aria-label",`${vt()||"Jump to latest"} (${Fr} new)`)):(Tn.textContent="",Tn.style.display="none",_t.setAttribute("aria-label",vt()||"Jump to latest"))},Fe=()=>{Fr!==0&&(Fr=0,ge())},gt=()=>Ct()==="follow"?!Un.isFollowing():!Ro(Ce,qo),ot=()=>{if(!It()||X){_t.parentNode&&_t.remove(),_t.style.display="none";return}_t.parentNode!==xe&&xe.appendChild(_t),En();let p=Vr(Ce)>0&&gt();p||Fe(),_t.style.display=p?"":"none"},bs=()=>{Un.pause()&&(Q(),ot())},Bn=()=>{Un.resume(),Fe(),ot()},cn=(l=!1)=>{Ct()==="follow"&&Un.isFollowing()&&(!l&&!Ar||(cr!==null&&(cancelAnimationFrame(cr),cr=null),bo=!0,cr=requestAnimationFrame(()=>{cr=null,bo=!1,Un.isFollowing()&&xo(j(),l?220:140)})))},dn=(l,p,h,b=()=>!0)=>{let S=l.scrollTop,B=p(),q=B-S;z();let _=performance.now();dr=!0;let D=ie=>1-Math.pow(1-ie,3),ae=ie=>{if(!b()){z();return}let Y=p();Y!==B&&(B=Y,q=B-S);let ye=ie-_,De=Math.min(ye/h,1),we=D(De),Je=S+q*we;l.scrollTop=Je,zn=l.scrollTop,De<1?w=requestAnimationFrame(ae):(l.scrollTop=B,zn=l.scrollTop,w=null,dr=!1)};w=requestAnimationFrame(ae)},xo=(l,p=500)=>{let h=Vr(l)-l.scrollTop;if(Math.abs(h)<1){zn=l.scrollTop;return}if(Math.abs(h)>=ia){z(),dr=!0,l.scrollTop=Vr(l),zn=l.scrollTop,dr=!1;return}dn(l,()=>Vr(l),p,()=>Un.isFollowing())},Or=()=>{let l=j();dr=!0,l.scrollTop=Vr(l),zn=l.scrollTop,dr=!1,ot()},Ln=l=>{bn.style.height=`${Math.max(0,Math.round(l))}px`,vn&&(vn.spacerHeight=Math.max(0,l))},hn=()=>{Er!==null&&(cancelAnimationFrame(Er),Er=null),z(),vn=null,bn.style.height="0px"},qn=l=>{Er!==null&&cancelAnimationFrame(Er),Er=requestAnimationFrame(()=>{var ae;Er=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Ce.querySelector(`[data-message-id="${p}"]`);if(!h)return;let b=0,S=h;for(;S&&S!==Ce;)b+=S.offsetTop,S=S.offsetParent;let B=(ae=vn==null?void 0:vn.spacerHeight)!=null?ae:0,q=Ce.scrollHeight-B,{targetScrollTop:_,spacerHeight:D}=Gu({anchorOffsetTop:b,topOffset:ln(),viewportHeight:Ce.clientHeight,contentHeight:q});vn={initialSpacerHeight:D,contentHeightAtAnchor:q,spacerHeight:D},Ln(D),dn(Ce,()=>_,220)})},tg=()=>{if(Ct()==="follow"){if(!Un.isFollowing()||Ro(Ce,1))return;cn(!Ar);return}if(vn&&vn.initialSpacerHeight>0){let l=Ce.scrollHeight-vn.spacerHeight,p=Qu({initialSpacerHeight:vn.initialSpacerHeight,contentHeightAtAnchor:vn.contentHeightAtAnchor,currentContentHeight:l});p!==vn.spacerHeight&&Ln(p)}ot()},ng=l=>{let p=Ct();p==="follow"?(Bn(),cn(!0)):p==="anchor-top"&&qn(l)},rg=l=>{let p=new Map;l.forEach(h=>{let b=jo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!vo&&Ct()!=="anchor-top"&&gt()&&(Fr+=1,ge(),ot())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),jo.clear(),p.forEach((h,b)=>{jo.set(b,h)})},og=(l,p,h)=>{var nt,Le,Me,Ue,je,ft;let b=document.createElement("div"),B=(()=>{var We;let I=o.find(Pe=>Pe.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((We=r.loadingIndicator)!=null&&We.render)return r.loadingIndicator.render})(),q=(I,We)=>We==null?!1:typeof We=="string"?(I.textContent=We,!0):(I.appendChild(We),!0),_=new Set,D=new Set,ae=o.some(I=>I.renderAskUserQuestion),ie=[],Y=[],ye=r.enableComponentStreaming!==!1,De=r.approval!==!1,we=[];if(p.forEach(I=>{var Ke,Mt,tn,nr,Vn,Co,Ao,Jo,Yo,Gt,So,ro,oo,$r,To,pr,kr;_.add(I.id);let We=ae&&Lo(I),Pe=De&&I.variant==="approval"&&!!I.approval,me=!We&&I.role==="assistant"&&!I.variant&&ye&&Nm(I);if(!Pe&&lr.has(I.id)){let Ge=l.querySelector(`#wrapper-${I.id}`);Ge==null||Ge.removeAttribute("data-preserve-runtime"),lr.delete(I.id)}if(!me&&Tr.has(I.id)){let Ge=l.querySelector(`#wrapper-${I.id}`);Ge==null||Ge.removeAttribute("data-preserve-runtime"),Tr.delete(I.id)}let Dt=Lo(I)?`:${(Ke=I.agentMetadata)!=null&&Ke.askUserQuestionAnswered?"a":"u"}:${(Mt=I.agentMetadata)!=null&&Mt.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",Rt=Uu(I,$o)+Dt,Kt=We||Pe||me?null:qu(Sr,I.id,Rt);if(Kt){b.appendChild(Kt.cloneNode(!0)),Lo(I)&&((tn=I.toolCall)!=null&&tn.id)&&((nr=I.agentMetadata)==null?void 0:nr.awaitingLocalTool)===!0&&!((Vn=I.agentMetadata)!=null&&Vn.askUserQuestionAnswered)&&(D.add(I.toolCall.id),va(I,r,ze.composerOverlay));return}let ht=null,qt=o.find(Ge=>!!(I.variant==="reasoning"&&Ge.renderReasoning||I.variant==="tool"&&Ge.renderToolCall||!I.variant&&Ge.renderMessage)),jn=(Co=r.layout)==null?void 0:Co.messages;if(Lo(I)&&((Ao=I.agentMetadata)==null?void 0:Ao.askUserQuestionAnswered)===!0){Nr.delete(I.id);let Ge=l.querySelector(`#wrapper-${I.id}`);Ge==null||Ge.removeAttribute("data-preserve-runtime");return}if(Si(I)&&((Yo=(Jo=r.features)==null?void 0:Jo.suggestReplies)==null?void 0:Yo.enabled)!==!1)return;if(Lo(I)&&((So=(Gt=r.features)==null?void 0:Gt.askUserQuestion)==null?void 0:So.enabled)!==!1){let Ge=o.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(Ge&&St.current){let Nt=Nr.get(I.id),Vt=Nt!==Rt,Ft=null;if(Vt){let{payload:$t,complete:pn}=ns(I),Kn=I.id,Lr=()=>{var un;return(un=St.current)==null?void 0:un.getMessages().find(mn=>mn.id===Kn)};Ft=Ge.renderAskUserQuestion({message:I,payload:$t,complete:pn,resolve:un=>{var rr;let mn=Lr();mn&&((rr=St.current)==null||rr.resolveAskUserQuestion(mn,un))},dismiss:()=>{var mn,rr,so;let un=Lr();(mn=un==null?void 0:un.agentMetadata)!=null&&mn.awaitingLocalTool&&((rr=St.current)==null||rr.markAskUserQuestionResolved(un),(so=St.current)==null||so.resolveAskUserQuestion(un,"(dismissed)"))},config:r})}let Qt=Nt!=null;if(Vt&&Ft===null&&!Qt){((ro=I.agentMetadata)==null?void 0:ro.awaitingLocalTool)===!0&&!((oo=I.agentMetadata)!=null&&oo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),va(I,r,ze.composerOverlay));return}let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${I.id}`,kt.setAttribute("data-wrapper-id",I.id),kt.setAttribute("data-ask-plugin-stub","true"),kt.setAttribute("data-preserve-runtime","true"),b.appendChild(kt),ie.push({messageId:I.id,fingerprint:Rt,bubble:Ft});return}else{(($r=I.agentMetadata)==null?void 0:$r.awaitingLocalTool)===!0&&!((To=I.agentMetadata)!=null&&To.askUserQuestionAnswered)&&(D.add(I.toolCall.id),va(I,r,ze.composerOverlay));return}}else if(Pe){let Ge=(pr=o.find(Qt=>typeof Qt.renderApproval=="function"))!=null?pr:s,Vt=lr.get(I.id)!==Rt,Ft=null;if(Vt&&(Ge!=null&&Ge.renderApproval)){let Qt=I.id,kt=($t,pn)=>{var Lr,un,mn;let Kn=(Lr=St.current)==null?void 0:Lr.getMessages().find(rr=>rr.id===Qt);Kn!=null&&Kn.approval&&(Kn.approval.toolType==="webmcp"?(un=St.current)==null||un.resolveWebMcpApproval(Kn.id,$t):(mn=St.current)==null||mn.resolveApproval(Kn.approval,$t,pn))};Ft=Ge.renderApproval({message:I,defaultRenderer:()=>Za(I,r),config:r,approve:$t=>kt("approved",$t),deny:$t=>kt("denied",$t)})}if(Vt&&Ft===null){let Qt=l.querySelector(`#wrapper-${I.id}`);Qt==null||Qt.removeAttribute("data-preserve-runtime"),lr.delete(I.id),ht=Za(I,r)}else{let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${I.id}`,Qt.setAttribute("data-wrapper-id",I.id),Qt.setAttribute("data-approval-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),b.appendChild(Qt),we.push({messageId:I.id,fingerprint:Rt,bubble:Ft});return}}else if(qt)if(I.variant==="reasoning"&&I.reasoning&&qt.renderReasoning){if(!ve)return;ht=qt.renderReasoning({message:I,defaultRenderer:()=>ji(I,r),config:r})}else if(I.variant==="tool"&&I.toolCall&&qt.renderToolCall){if(!Ie)return;ht=qt.renderToolCall({message:I,defaultRenderer:()=>Ki(I,r),config:r})}else qt.renderMessage&&(ht=qt.renderMessage({message:I,defaultRenderer:()=>{let Ge=qi(I,h,jn,r.messageActions,Xe,{loadingIndicatorRenderer:B,widgetConfig:r});return I.role!=="user"&&Yi(Ge,I,r,U),Ge},config:r}));if(!ht&&me){let Ge=Fm(I);if(Ge){let Nt=Tr.get(I.id),Vt=Nt!==Rt,Ft=r.wrapComponentDirectiveInBubble!==!1,Qt=null;if(Vt){let kt=Bm(Ge,{config:r,message:I,transform:h});if(kt)if(Ft){let $t=document.createElement("div");if($t.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(" "),$t.id=`bubble-${I.id}`,$t.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(pn)}$t.appendChild(kt),Qt=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${I.id}`,$t.setAttribute("data-message-id",I.id),$t.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(pn)}$t.appendChild(kt),Qt=$t}}if(Qt||Nt!=null){let kt=document.createElement("div");kt.className="persona-flex",kt.id=`wrapper-${I.id}`,kt.setAttribute("data-wrapper-id",I.id),kt.setAttribute("data-component-directive-stub","true"),kt.setAttribute("data-preserve-runtime","true"),Ft||kt.classList.add("persona-w-full"),b.appendChild(kt),Y.push({messageId:I.id,fingerprint:Rt,bubble:Qt});return}}}if(!ht)if(I.variant==="reasoning"&&I.reasoning){if(!ve)return;ht=ji(I,r)}else if(I.variant==="tool"&&I.toolCall){if(!Ie)return;ht=Ki(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;ht=Za(I,r)}else{let Ge=(kr=r.layout)==null?void 0:kr.messages;Ge!=null&&Ge.renderUserMessage&&I.role==="user"?ht=Ge.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):Ge!=null&&Ge.renderAssistantMessage&&I.role==="assistant"?ht=Ge.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):ht=qi(I,h,Ge,r.messageActions,Xe,{loadingIndicatorRenderer:B,widgetConfig:r}),I.role!=="user"&&ht&&Yi(ht,I,r,U)}let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${I.id}`,Zt.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Zt.classList.add("persona-justify-end"),(ht==null?void 0:ht.getAttribute("data-persona-component-directive"))==="true"&&Zt.classList.add("persona-w-full"),Zt.appendChild(ht),ju(Sr,I.id,Rt,Zt),b.appendChild(Zt)}),ze.composerOverlay&&ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Pe=We.getAttribute("data-persona-ask-sheet-for");Pe&&!D.has(Pe)&&os(ze.composerOverlay,Pe)}),(Le=(nt=r.features)==null?void 0:nt.toolCallDisplay)!=null&&Le.grouped){let I=[],We=[];p.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ie){We.push(Pe);return}We.length>1&&I.push(We),We=[]}),We.length>1&&I.push(We),I.forEach((Pe,me)=>{var Ke,Mt;let Dt=Pe.map(tn=>Array.from(b.children).find(nr=>nr instanceof HTMLElement&&nr.getAttribute("data-wrapper-id")===tn.id)).filter(tn=>!!tn);if(Dt.length<2)return;let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id=`wrapper-tool-group-${me}-${Pe[0].id}`,Rt.setAttribute("data-wrapper-id",`tool-group-${me}-${Pe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let ht=document.createElement("div");ht.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Pe.length} tools`,jn=(Mt=(Ke=r.toolCall)==null?void 0:Ke.renderGroupedSummary)==null?void 0:Mt.call(Ke,{messages:Pe,toolCalls:Pe.map(tn=>tn.toolCall).filter(tn=>!!tn),defaultSummary:qt,config:r});q(ht,jn)||(ht.textContent=qt);let Zt=document.createElement("div");Zt.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(ht,Zt),Rt.appendChild(Kt),Dt[0].before(Rt),Dt.forEach((tn,nr)=>{let Vn=document.createElement("div");Vn.className="persona-tool-group-item persona-relative",Vn.setAttribute("data-persona-tool-group-item","true"),nr<Dt.length-1&&Vn.setAttribute("data-persona-tool-group-connector","true"),Vn.appendChild(tn),Zt.appendChild(Vn)})})}Vu(Sr,_);let Je=p.some(I=>I.role==="assistant"&&I.streaming),_e=p[p.length-1],ct=(_e==null?void 0:_e.role)==="assistant"&&!_e.streaming&&_e.variant!=="approval";if(Ar&&p.some(I=>I.role==="user")&&!Je&&!ct){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:Zs},We=o.find(me=>me.renderLoadingIndicator),Pe=null;if(We!=null&&We.renderLoadingIndicator&&(Pe=We.renderLoadingIndicator(I)),Pe===null&&((Me=r.loadingIndicator)!=null&&Me.render)&&(Pe=r.loadingIndicator.render(I)),Pe===null&&(Pe=Zs()),Pe){let me=document.createElement("div"),Dt=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;me.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-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(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(Pe);let Rt=document.createElement("div");Rt.className="persona-flex",Rt.id="wrapper-typing-indicator",Rt.setAttribute("data-wrapper-id","typing-indicator"),Rt.appendChild(me),b.appendChild(Rt)}}if(!Ar&&p.length>0){let I=p[p.length-1],We={config:r,lastMessage:I,messageCount:p.length},Pe=o.find(Dt=>Dt.renderIdleIndicator),me=null;if(Pe!=null&&Pe.renderIdleIndicator&&(me=Pe.renderIdleIndicator(We)),me===null&&((je=r.loadingIndicator)!=null&&je.renderIdle)&&(me=r.loadingIndicator.renderIdle(We)),me){let Dt=document.createElement("div"),Rt=((ft=r.loadingIndicator)==null?void 0:ft.showBubble)!==!1;Dt.className=Rt?["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(" "),Dt.setAttribute("data-idle-indicator","true"),Dt.appendChild(me);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Dt),b.appendChild(Kt)}}if(Ha(l,b),ie.length>0)for(let{messageId:I,fingerprint:We,bubble:Pe}of ie){let me=l.querySelector(`#wrapper-${I}`);me&&Pe!==null&&(me.replaceChildren(Pe),me.setAttribute("data-bubble-fp",We),Nr.set(I,We))}if(Nr.size>0)for(let I of Nr.keys())_.has(I)||Nr.delete(I);if(Y.length>0)for(let{messageId:I,fingerprint:We,bubble:Pe}of Y){let me=l.querySelector(`#wrapper-${I}`);me&&Pe!==null&&(me.replaceChildren(Pe),me.setAttribute("data-bubble-fp",We),Tr.set(I,We))}if(Tr.size>0)for(let I of Tr.keys())_.has(I)||Tr.delete(I);if(we.length>0)for(let{messageId:I,fingerprint:We,bubble:Pe}of we){let me=l.querySelector(`#wrapper-${I}`);me&&Pe!==null&&(me.replaceChildren(Pe),me.setAttribute("data-bubble-fp",We),lr.set(I,We))}if(lr.size>0)for(let I of lr.keys())_.has(I)||lr.delete(I)},vs=(l,p,h)=>{og(l,p,h),Xr()},xs=null,sg=()=>{var h;if(xs)return;let l=b=>{let S=b.composedPath();S.includes(He)||qe&&S.includes(qe)||zt(!1,"user")};xs=l,((h=t.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},pl=()=>{var p;if(!xs)return;((p=t.ownerDocument)!=null?p:document).removeEventListener("pointerdown",xs,!0),xs=null};mt.push(()=>pl());let ws=null,ag=()=>{var h;if(ws)return;let l=b=>{b.key==="Escape"&&(b.isComposing||zt(!1,"user"))};ws=l,((h=t.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},ul=()=>{var p;if(!ws)return;((p=t.ownerDocument)!=null?p:document).removeEventListener("keydown",ws,!0),ws=null};mt.push(()=>ul());let Cs=!1,ml=new Set,ig=()=>{var p,h,b,S;let l=(b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((S=r.features)==null?void 0:S.streamAnimation)},Ko=()=>{var ct,nt,Le,Me;if(!R())return;let l=ze.peekBanner,p=ze.peekTextNode;if(!l||!p)return;if(N){l.classList.remove("persona-pill-peek--visible");return}let h=(ct=U==null?void 0:U.getMessages())!=null?ct:[],b;for(let Ue=h.length-1;Ue>=0;Ue--){let je=h[Ue];if(je.role==="assistant"&&je.content){b=je;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let S=b.content,B=!!b.streaming,q=ig(),_=Oa(q),D=_.type!=="none"?Vs(_.type,q==null?void 0:q.plugins):null,ae=((nt=D==null?void 0:D.isAnimating)==null?void 0:nt.call(D,b))===!0,ie=D!==null&&(B||ae);ie&&D&&!ml.has(D.name)&&(Di(D,t),ml.add(D.name));let Y=ie&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Le=p.dataset.personaPeekStreamClass)!=null?Le:null;ye&&ye!==Y&&(p.classList.remove(ye),delete p.dataset.personaPeekStreamClass),Y&&ye!==Y&&(p.classList.add(Y),p.dataset.personaPeekStreamClass=Y),ie?(p.style.setProperty("--persona-stream-step",`${_.speed}ms`),p.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let De=ie?_a(S,_.buffer,D,b,B):S;if(ie&&_.placeholder==="skeleton"&&B&&(!De||!De.trim())){let Ue=document.createElement("div"),je=Gs();je.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(je),Ha(p,Ue)}else{let Ue=Math.max(0,De.length-100),je=De.length>100?De.slice(-100):De,ft=ao(je);if(!ie||!D){let I=De.length>100?`\u2026${je}`:je;p.textContent!==I&&(p.textContent=I)}else{let I=ft;(D.wrap==="char"||D.wrap==="word")&&(I=Ks(ft,D.wrap,`peek-${b.id}`,{skipTags:D.skipTags,startIndex:Ue}));let We=document.createElement("div");if(We.innerHTML=I,D.useCaret&&je.length>0){let Pe=$a(),me=We.querySelectorAll(".persona-stream-char, .persona-stream-word"),Dt=me[me.length-1];Dt!=null&&Dt.parentNode?Dt.parentNode.insertBefore(Pe,Dt.nextSibling):We.appendChild(Pe)}Ha(p,We),(Me=D.onAfterRender)==null||Me.call(D,{container:p,bubble:l,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let _e=Ar||Cs;l.classList.toggle("persona-pill-peek--visible",_e)};if(R()){let l=ze.peekBanner;if(l){let b=S=>{S.preventDefault(),S.stopPropagation(),zt(!0,"user")};l.addEventListener("pointerdown",b),mt.push(()=>{l.removeEventListener("pointerdown",b)})}let p=()=>{Cs||(Cs=!0,Ko())},h=()=>{Cs&&(Cs=!1,Ko())};K.addEventListener("pointerenter",p),K.addEventListener("pointerleave",h),mt.push(()=>{K.removeEventListener("pointerenter",p),K.removeEventListener("pointerleave",h)}),qe&&(qe.addEventListener("pointerenter",p),qe.addEventListener("pointerleave",h),mt.push(()=>{qe.removeEventListener("pointerenter",p),qe.removeEventListener("pointerleave",h)}))}let lg=l=>{var ye,De,we,Je,_e,ct,nt,Le;let p=(De=(ye=r.launcher)==null?void 0:ye.composerBar)!=null?De:{},h=(we=p.expandedSize)!=null?we:"anchored",b=(Je=p.bottomOffset)!=null?Je:"16px",S=p.collapsedMaxWidth,B=(_e=p.expandedMaxWidth)!=null?_e:"880px",q=(ct=p.expandedTopOffset)!=null?ct:"5vh",_=(nt=p.modalMaxWidth)!=null?nt:"880px",D=(Le=p.modalMaxHeight)!=null?Le:"min(90vh, 800px)",ae="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",Y=He.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",qe){let Me=qe.style;Me.bottom=b,Me.width=S!=null?S:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=_,Y.maxWidth=ae,Y.maxHeight=D,Y.height=D;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${ie})`,Y.top=q,Y.width=B,Y.maxWidth=ae}},As=()=>{var D,ae,ie,Y,ye,De,we,Je;if(!$())return;if(R()){let ct=(ie=((ae=(D=r.launcher)==null?void 0:D.composerBar)!=null?ae:{}).expandedSize)!=null?ie:"anchored",nt=N?"expanded":"collapsed";He.dataset.state=nt,He.dataset.expandedSize=ct,qe&&(qe.dataset.state=nt,qe.dataset.expandedSize=ct),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),K.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),lg(N),xe.style.display=N?"flex":"none",xr(),N?(sg(),ag()):(pl(),ul()),Ko();return}let l=yn(r),p=(Y=t.ownerDocument.defaultView)!=null?Y:window,h=(De=(ye=r.launcher)==null?void 0:ye.mobileBreakpoint)!=null?De:640,b=(Je=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Je:!0,S=p.innerWidth<=h,B=b&&S&&k,q=gr(r).reveal;N?(He.style.removeProperty("display"),He.style.display=l?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),K.classList.remove("persona-scale-95","persona-opacity-0"),K.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":on&&(on.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!B?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),K.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),K.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.classList.add("persona-pointer-events-none","persona-opacity-0"),K.classList.remove("persona-scale-100","persona-opacity-100"),K.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=l?"none":"":on&&(on.style.display=l?"none":""))},zt=(l,p="user")=>{var B,q;if(!$()||N===l)return;let h=N;N=l,As();let b=(()=>{var we,Je,_e,ct,nt,Le,Me,Ue,je,ft;let _=(Je=(we=r.launcher)==null?void 0:we.sidebarMode)!=null?Je:!1,D=(_e=t.ownerDocument.defaultView)!=null?_e:window,ae=(nt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?nt:!0,ie=(Me=(Le=r.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Me:640,Y=D.innerWidth<=ie,ye=yn(r)&&ae&&Y,De=R()&&((ft=(je=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:je.expandedSize)!=null?ft:"fullscreen")==="fullscreen";return _||ae&&Y&&k||ye||De})();if(N&&b){if(!nn){let _=t.getRootNode(),D=_ instanceof ShadowRoot?_.host:t.closest(".persona-host");D&&(nn=Ni(D,(q=(B=r.launcher)==null?void 0:B.zIndex)!=null?q:Cn))}rn||(rn=Fi(t.ownerDocument))}else N||(nn==null||nn(),nn=null,rn==null||rn(),rn=null);N&&(Ss(),Ct()==="follow"?cn(!0):Or());let S={open:N,source:p,timestamp:Date.now()};N&&!h?i.emit("widget:opened",S):!N&&h&&i.emit("widget:closed",S),i.emit("widget:state",{open:N,launcherEnabled:k,voiceActive:pt.active,streaming:U.isStreaming()})},si=l=>{bt(l?"stop":"send"),H&&(H.disabled=l),yo.buttons.forEach(p=>{p.disabled=l}),Be.dataset.personaComposerStreaming=l?"true":"false",Be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},ai=()=>{pt.active||ne&&ne.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ai(),200)});let gl=()=>{var h,b,S,B,q,_,D,ae,ie,Y,ye;Ir.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",hr.textContent=(B=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",ne.placeholder=(_=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?_:"How can I help...";let l=Ce.querySelector("[data-persona-intro-card]");if(l){let De=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=De?"":"none",De?(Ce.classList.remove("persona-gap-3"),Ce.classList.add("persona-gap-6")):(Ce.classList.remove("persona-gap-6"),Ce.classList.add("persona-gap-3"))}!((ie=(ae=r.sendButton)==null?void 0:ae.useIcon)!=null&&ie)&&!(U!=null&&U.isStreaming())&&(Oe.textContent=(ye=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ye:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=u.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(p=>({...p,sessionId:l}))}});let wo=null,cg=()=>{wo==null&&(wo=setInterval(()=>{let l=tt.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(wo),wo=null;return}let p=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=wa(p-b))})},100))};U=new Ia(r,{onMessagesChanged(l){var b;vs(tt,l,ee),cg(),_o(l),cn(!Ar),rg(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&hn(),!Uo||vo?(Uo=!0,zo=(b=p==null?void 0:p.id)!=null?b:null):p&&p.id!==zo&&(zo=p.id,ng(p.id));let h=pt.lastUserMessageId;p&&p.id!==h&&(pt.lastUserMessageId=p.id,i.emit("user:message",p)),pt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),et(l),Ko()},onStatusChanged(l){var b;let p=(b=r.statusIndicator)!=null?b:{};dt(Xt,(S=>{var B,q,_,D;return S==="idle"?(B=p.idleText)!=null?B:wn.idle:S==="connecting"?(q=p.connectingText)!=null?q:wn.connecting:S==="connected"?(_=p.connectedText)!=null?_:wn.connected:S==="error"?(D=p.errorText)!=null?D:wn.error:wn[S]})(l),p,l)},onStreamingChanged(l){Ar=l,si(l),U&&vs(tt,U.getMessages(),ee),l||cn(!0),Ko()},onVoiceStatusChanged(l){var p,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":_r(),Qo();break;case"processing":_r(),gg();break;case"speaking":_r(),fg();break;default:l==="idle"&&U.isBargeInActive()?(_r(),Qo(),H==null||H.setAttribute("aria-label","End voice session")):(pt.active=!1,_r(),Zn("system"),Hn());break}},onArtifactsState(l){On=l,Rn(),et()}}),St.current=U;let ii=null;if(U.onReadAloudChange((l,p)=>{var S;Gr=l,Qr=p,Xr();let h=l!=null?l:ii;l&&(ii=l);let b=h&&(S=U.getMessages().find(B=>B.id===h))!=null?S:null;i.emit("message:read-aloud",{messageId:h,message:b,state:p,timestamp:Date.now()}),p==="idle"&&(ii=null)}),Uo=!0,((Tc=(Sc=r.voiceRecognition)==null?void 0:Sc.provider)==null?void 0:Tc.type)==="runtype")try{U.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&U.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(V||r.onSSEEvent)&&U.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),G==null||G.processEvent(l,p),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),f&&f.then(l=>{var p,h,b;if(l){if(l.metadata&&(u=ol(l.metadata),T.syncFromMetadata()),(p=l.messages)!=null&&p.length){vo=!0;try{U.hydrateMessages(l.messages)}finally{vo=!1}}(h=l.artifacts)!=null&&h.length&&U.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let fl=()=>{var p,h,b;!R()||N||!((b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||zt(!0,"auto")},hl=l=>{var S;if(l.preventDefault(),U.isStreaming()){U.cancel(),G==null||G.reset(),be==null||be.update();return}let p=ne.value.trim(),h=(S=At==null?void 0:At.hasAttachments())!=null?S:!1;if(!p&&!h)return;fl();let b;h&&(b=[],b.push(...At.getContentParts()),p&&b.push(ki(p))),ne.value="",ne.style.height="auto",ca(),U.sendMessage(p,{contentParts:b}),h&&At.clearAttachments()},dg=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},li={...Ba},ci=!1,ca=()=>{li={...Ba}},pg=()=>U.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),ug=l=>{if(!ne)return;ci=!0,ne.value=l,ne.dispatchEvent(new Event("input",{bubbles:!0})),ci=!1;let p=ne.value.length;ne.setSelectionRange(p,p)},yl=()=>{ci||ca()},bl=l=>{if(ne){if(dg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=ne.selectionStart===0&&ne.selectionEnd===0,h=$u({direction:l.key==="ArrowUp"?"up":"down",history:pg(),currentValue:ne.value,atStart:p,state:li});if(li=h.state,h.handled){l.preventDefault(),h.value!==void 0&&ug(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(U.isStreaming()){l.preventDefault();return}ca(),l.preventDefault(),Oe.click()}}},vl=l=>{l.key!=="Escape"||l.isComposing||U.isStreaming()&&l.composedPath().includes(xe)&&(U.cancel(),G==null||G.reset(),be==null||be.update(),ca(),l.preventDefault(),l.stopImmediatePropagation())},xl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let p=Rv(l.clipboardData);p.length!==0&&(l.preventDefault(),await At.handleFiles(p))},er=null,Mr=!1,Go=null,lt=null,wl=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,da=(l="user")=>{var B,q,_,D,ae,ie,Y;if(Mr||U.isStreaming())return;let p=wl();if(!p)return;er=new p;let b=(q=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?q:2e3;er.continuous=!0,er.interimResults=!0,er.lang="en-US";let S=ne.value;er.onresult=ye=>{let De="",we="";for(let _e=0;_e<ye.results.length;_e++){let ct=ye.results[_e],nt=ct[0].transcript;ct.isFinal?De+=nt+" ":we=nt}let Je=S+De+we;ne.value=Je,Go&&clearTimeout(Go),(De||we)&&(Go=window.setTimeout(()=>{let _e=ne.value.trim();_e&&er&&Mr&&(to(),ne.value="",ne.style.height="auto",U.sendMessage(_e,{viaVoice:!0}))},b))},er.onerror=ye=>{ye.error!=="no-speech"&&to()},er.onend=()=>{if(Mr){let ye=ne.value.trim();ye&&ye!==S.trim()&&(ne.value="",ne.style.height="auto",U.sendMessage(ye,{viaVoice:!0})),to()}};try{if(er.start(),Mr=!0,pt.active=!0,l!=="system"&&(pt.manuallyDeactivated=!1),Zn(l),Hn(),H){let ye=(_=r.voiceRecognition)!=null?_:{};lt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((Y=(ie=ye.iconSize)!=null?ie:(ae=r.sendButton)==null?void 0:ae.size)!=null?Y:"40")||24};let De=ye.recordingBackgroundColor,we=ye.recordingIconColor,Je=ye.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=we!=null?we:"var(--persona-voice-recording-indicator, #ffffff)",we){let _e=H.querySelector("svg");_e&&_e.setAttribute("stroke",we)}Je&&(H.style.borderColor=Je),H.setAttribute("aria-label","Stop voice recognition")}}catch{to("system")}},to=(l="user")=>{if(Mr){if(Mr=!1,Go&&(clearTimeout(Go),Go=null),er){try{er.stop()}catch{}er=null}if(pt.active=!1,Zn(l),Hn(),H){if(H.classList.remove("persona-voice-recording"),lt){H.style.backgroundColor=lt.backgroundColor,H.style.color=lt.color,H.style.borderColor=lt.borderColor;let p=H.querySelector("svg");p&&p.setAttribute("stroke",lt.color||"currentColor"),lt=null}H.setAttribute("aria-label","Start voice recognition")}}},mg=(l,p)=>{var nt,Le,Me,Ue,je,ft,I,We,Pe;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((nt=l==null?void 0:l.provider)==null?void 0:nt.type)==="runtype",S=((Le=l==null?void 0:l.provider)==null?void 0:Le.type)==="custom";if(!(h||b||S))return null;let q=y("div","persona-send-button-wrapper"),_=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let D=(Me=l==null?void 0:l.iconName)!=null?Me:"mic",ae=(Ue=p==null?void 0:p.size)!=null?Ue:"40px",ie=(je=l==null?void 0:l.iconSize)!=null?je:ae,Y=parseFloat(ie)||24,ye=(ft=l==null?void 0:l.backgroundColor)!=null?ft:p==null?void 0:p.backgroundColor,De=(I=l==null?void 0:l.iconColor)!=null?I:p==null?void 0:p.textColor;_.style.width=ie,_.style.height=ie,_.style.minWidth=ie,_.style.minHeight=ie,_.style.fontSize="18px",_.style.lineHeight="1",De?_.style.color=De:_.style.color="var(--persona-text, #111827)";let Je=fe(D,Y,De||"currentColor",1.5);Je?_.appendChild(Je):_.textContent="\u{1F3A4}",ye?_.style.backgroundColor=ye:_.style.backgroundColor="",l!=null&&l.borderWidth&&(_.style.borderWidth=l.borderWidth,_.style.borderStyle="solid"),l!=null&&l.borderColor&&(_.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(_.style.paddingLeft=l.paddingX,_.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(_.style.paddingTop=l.paddingY,_.style.paddingBottom=l.paddingY),q.appendChild(_);let _e=(We=l==null?void 0:l.tooltipText)!=null?We:"Start voice recognition";if(((Pe=l==null?void 0:l.showTooltip)!=null?Pe:!1)&&_e){let me=y("div","persona-send-button-tooltip");me.textContent=_e,q.appendChild(me)}return{micButton:_,micButtonWrapper:q}},di=()=>{var p,h,b,S,B;if(!H||lt)return;let l=(p=r.voiceRecognition)!=null?p:{};lt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((B=(S=l.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},pi=(l,p)=>{var B,q,_,D,ae;if(!H)return;let h=H.querySelector("svg");h&&h.remove();let b=(ae=lt==null?void 0:lt.iconSize)!=null?ae:parseFloat((D=(_=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?_:(q=r.sendButton)==null?void 0:q.size)!=null?D:"40")||24,S=fe(l,b,p,1.5);S&&H.appendChild(S)},pa=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qo=()=>{var S;if(!H)return;di();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(pa(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let B=H.querySelector("svg");B&&B.setAttribute("stroke",h)}b&&(H.style.borderColor=b),H.setAttribute("aria-label","Stop voice recognition")},gg=()=>{var _,D,ae,ie,Y,ye,De,we;if(!H)return;di();let l=(_=r.voiceRecognition)!=null?_:{},p=U.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",b=(ie=(ae=l.processingIconColor)!=null?ae:lt==null?void 0:lt.color)!=null?ie:"",S=(ye=(Y=l.processingBackgroundColor)!=null?Y:lt==null?void 0:lt.backgroundColor)!=null?ye:"",B=(we=(De=l.processingBorderColor)!=null?De:lt==null?void 0:lt.borderColor)!=null?we:"";pa(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=S,H.style.borderColor=B;let q=b||"currentColor";H.style.color=q,pi(h,q),H.setAttribute("aria-label","Processing voice input"),p==="none"&&(H.style.cursor="default")},fg=()=>{var ae,ie,Y,ye,De,we,Je,_e,ct,nt,Le,Me;if(!H)return;di();let l=(ae=r.voiceRecognition)!=null?ae:{},p=U.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",b=(ie=l.speakingIconName)!=null?ie:h,S=(we=l.speakingIconColor)!=null?we:p==="barge-in"?(ye=(Y=l.recordingIconColor)!=null?Y:lt==null?void 0:lt.color)!=null?ye:"":(De=lt==null?void 0:lt.color)!=null?De:"",B=(ct=l.speakingBackgroundColor)!=null?ct:p==="barge-in"?(Je=l.recordingBackgroundColor)!=null?Je:"var(--persona-voice-recording-bg, #ef4444)":(_e=lt==null?void 0:lt.backgroundColor)!=null?_e:"",q=(Me=l.speakingBorderColor)!=null?Me:p==="barge-in"?(nt=l.recordingBorderColor)!=null?nt:"":(Le=lt==null?void 0:lt.borderColor)!=null?Le:"";pa(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=B,H.style.borderColor=q;let _=S||"currentColor";H.style.color=_,pi(b,_);let D=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",D),p==="none"&&(H.style.cursor="default"),p==="barge-in"&&H.classList.add("persona-voice-recording")},_r=()=>{var l,p,h;H&&(pa(),lt&&(H.style.backgroundColor=(l=lt.backgroundColor)!=null?l:"",H.style.color=(p=lt.color)!=null?p:"",H.style.borderColor=(h=lt.borderColor)!=null?h:"",pi(lt.iconName,lt.color||"currentColor"),lt=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},ua=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=U.getVoiceStatus(),b=U.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){U.stopVoicePlayback();return}if(U.isBargeInActive()){U.stopVoicePlayback(),U.deactivateBargeIn().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Hn(),Zn("user"),_r()});return}U.toggleVoice().then(()=>{pt.active=U.isVoiceActive(),pt.manuallyDeactivated=!U.isVoiceActive(),Hn(),Zn("user"),U.isVoiceActive()?Qo():_r()});return}if(Mr){let h=ne.value.trim();pt.manuallyDeactivated=!0,Hn(),to("user"),h&&(ne.value="",ne.style.height="auto",U.sendMessage(h))}else pt.manuallyDeactivated=!1,Hn(),da("user")};yr=ua,H&&(H.addEventListener("click",ua),mt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(U.isVoiceActive()&&U.toggleVoice(),_r()):to("system"),H&&H.removeEventListener("click",ua)}));let hg=i.on("assistant:complete",()=>{ys&&(pt.active||pt.manuallyDeactivated||ys==="assistant"&&!pt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!pt.active&&!pt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?U.toggleVoice().then(()=>{pt.active=U.isVoiceActive(),Zn("auto"),U.isVoiceActive()&&Qo()}):da("auto"))},600))});mt.push(hg);let yg=i.on("action:resubmit",()=>{setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)});mt.push(yg);let Cl=()=>{zt(!N,"user")},Yt=null,on=null;if(k&&!R()){let{instance:l,element:p}=$i({config:r,plugins:o,onToggle:Cl});Yt=l,l||(on=p)}Yt?t.appendChild(Yt.element):on&&t.appendChild(on),As(),_o(),gl(),si(U.isStreaming()),Ct()==="follow"?cn(!0):Or(),la(),P&&(!k||R()?setTimeout(()=>ai(),0):N&&setTimeout(()=>ai(),200));let Ss=()=>{var D,ae,ie,Y,ye,De,we,Je,_e,ct,nt,Le,Me,Ue,je,ft,I,We,Pe,me,Dt,Rt;if(R()){En(),As();return}let l=yn(r),p=(ae=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?ae:!1,h=l||p||((Y=(ie=r.launcher)==null?void 0:ie.fullHeight)!=null?Y:!1),b=(ye=t.ownerDocument.defaultView)!=null?ye:window,S=(we=(De=r.launcher)==null?void 0:De.mobileFullscreen)!=null?we:!0,B=(_e=(Je=r.launcher)==null?void 0:Je.mobileBreakpoint)!=null?_e:640,q=b.innerWidth<=B,_=S&&q&&k;try{if(_){xr(),cs(t,r);return}if(O&&(O=!1,xr(),cs(t,r)),!k&&!l){K.style.height="",K.style.width="";return}if(!p&&!l){let Kt=(nt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?nt:r==null?void 0:r.launcherWidth,ht=Kt!=null?Kt:jr;K.style.width=ht,K.style.maxWidth=ht}if(he(),!h){let Kt=b.innerHeight,ht=64,qt=(Me=(Le=r.launcher)==null?void 0:Le.heightOffset)!=null?Me:0,jn=Math.max(200,Kt-ht),Zt=Math.min(640,jn),Ke=Math.max(200,Zt-qt);K.style.height=`${Ke}px`}}finally{if(En(),As(),N&&k){let ht=((Ue=t.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((ft=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?ft:640),qt=(We=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?We:!1,jn=(me=(Pe=r.launcher)==null?void 0:Pe.mobileFullscreen)!=null?me:!0,Zt=yn(r)&&jn&&ht,Ke=qt||jn&&ht&&k||Zt;if(Ke&&!rn){let Mt=t.getRootNode(),tn=Mt instanceof ShadowRoot?Mt.host:t.closest(".persona-host");tn&&!nn&&(nn=Ni(tn,(Rt=(Dt=r.launcher)==null?void 0:Dt.zIndex)!=null?Rt:Cn)),rn=Fi(t.ownerDocument)}else Ke||(nn==null||nn(),nn=null,rn==null||rn(),rn=null)}}};Ss();let Al=(Ec=t.ownerDocument.defaultView)!=null?Ec:window;if(Al.addEventListener("resize",Ss),mt.push(()=>Al.removeEventListener("resize",Ss)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{En()});l.observe(Be),mt.push(()=>l.disconnect())}zn=Ce.scrollTop;let Sl=Vr(Ce),bg=()=>{let l=Ce.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:Ce.ownerDocument.getSelection()},ui=()=>Ku(bg(),Ce),Tl=()=>{let l=Ce.scrollTop,p=Vr(Ce),h=p<Sl;if(Sl=p,Ct()!=="follow"){zn=l,ot();return}let{action:b,nextLastScrollTop:S}=Na({following:Un.isFollowing(),currentScrollTop:l,lastScrollTop:zn,nearBottom:Ro(Ce,qo),userScrollThreshold:aa,isAutoScrolling:dr||bo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(zn=S,b==="resume"){ui()||Bn();return}b==="pause"&&bs()};if(Ce.addEventListener("scroll",Tl,{passive:!0}),mt.push(()=>Ce.removeEventListener("scroll",Tl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{tg()});l.observe(tt),l.observe(Ce),mt.push(()=>l.disconnect())}let El=()=>{Ct()==="follow"&&Un.isFollowing()&&ui()&&bs()},Ml=Ce.ownerDocument;Ml.addEventListener("selectionchange",El),mt.push(()=>{Ml.removeEventListener("selectionchange",El)});let kl=l=>{if(Ct()!=="follow")return;let p=Fa({following:Un.isFollowing(),deltaY:l.deltaY,nearBottom:Ro(Ce,qo),resumeWhenNearBottom:!0});p==="pause"?bs():p==="resume"&&!ui()&&Bn()};Ce.addEventListener("wheel",kl,{passive:!0}),mt.push(()=>Ce.removeEventListener("wheel",kl)),_t.addEventListener("click",()=>{hn(),Ce.scrollTop=Ce.scrollHeight,zn=Ce.scrollTop,Bn(),cn(!0),ot()}),mt.push(()=>_t.remove()),mt.push(()=>{Q(),hn()});let Ll=()=>{A&&(Cr&&(A.removeEventListener("click",Cr),Cr=null),$()?(A.style.display="",Cr=()=>{zt(!1,"user")},A.addEventListener("click",Cr)):A.style.display="none")};Ll(),(()=>{let{clearChatButton:l}=ze;l&&l.addEventListener("click",()=>{U.clearMessages(),Sr.clear(),Bn(),os(ze.composerOverlay);try{localStorage.removeItem(gs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==gs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),c!=null&&c.clear)try{let h=c.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}u={},T.syncFromMetadata(),V==null||V.clear(),G==null||G.reset(),be==null||be.update()})})(),Bt&&Bt.addEventListener("submit",hl),ne==null||ne.addEventListener("keydown",bl),ne==null||ne.addEventListener("input",yl),ne==null||ne.addEventListener("paste",xl);let Pl=(Mc=t.ownerDocument)!=null?Mc:document;Pl.addEventListener("keydown",vl,!0);let Il="persona-attachment-drop-active",Ts=0,mi=()=>{Ts=0,xe.classList.remove(Il)},Xo=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},Wl=l=>{!ri(l.dataTransfer)||!Xo()||(Ts++,Ts===1&&xe.classList.add(Il))},Rl=l=>{!ri(l.dataTransfer)||!Xo()||(Ts--,Ts<=0&&mi())},Hl=l=>{!ri(l.dataTransfer)||!Xo()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Bl=l=>{var h;if(!ri(l.dataTransfer)||!Xo())return;l.preventDefault(),l.stopPropagation(),mi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&At.handleFiles(p)},no=!0;xe.addEventListener("dragenter",Wl,no),xe.addEventListener("dragleave",Rl,no),t.addEventListener("dragover",Hl,no),t.addEventListener("drop",Bl,no);let ma=t.ownerDocument,Dl=l=>{Xo()&&l.preventDefault()},Nl=l=>{Xo()&&l.preventDefault()};ma.addEventListener("dragover",Dl),ma.addEventListener("drop",Nl),mt.push(()=>{Bt&&Bt.removeEventListener("submit",hl),ne==null||ne.removeEventListener("keydown",bl),ne==null||ne.removeEventListener("input",yl),ne==null||ne.removeEventListener("paste",xl),Pl.removeEventListener("keydown",vl,!0)}),mt.push(()=>{xe.removeEventListener("dragenter",Wl,no),xe.removeEventListener("dragleave",Rl,no),t.removeEventListener("dragover",Hl,no),t.removeEventListener("drop",Bl,no),ma.removeEventListener("dragover",Dl),ma.removeEventListener("drop",Nl),mi()}),mt.push(()=>{U.cancel()}),Yt?mt.push(()=>{Yt==null||Yt.destroy()}):on&&mt.push(()=>{on==null||on.remove()});let en={update(l){var $t,pn,Kn,Lr,un,mn,rr,so,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,Uc,zc,qc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,zd,qd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp;let p=r.toolCall,h=r.messageActions,b=($t=r.layout)==null?void 0:$t.messages,S=r.colorScheme,B=r.loadingIndicator,q=r.iterationDisplay,_=(pn=r.features)==null?void 0:pn.showReasoning,D=(Kn=r.features)==null?void 0:Kn.showToolCalls,ae=(Lr=r.features)==null?void 0:Lr.toolCallDisplay,ie=(un=r.features)==null?void 0:un.reasoningDisplay;r={...r,...l},xr(),cs(t,r),ti(t,r),ni(t,r),Rn(),r.colorScheme!==S&&hs();let Y=el.getForInstance(r.plugins);o.length=0,o.push(...Y),k=(rr=(mn=r.launcher)==null?void 0:mn.enabled)!=null?rr:!0,E=(Hc=(so=r.launcher)==null?void 0:so.autoExpand)!=null?Hc:!1,ve=(Dc=(Bc=r.features)==null?void 0:Bc.showReasoning)!=null?Dc:!0,Ie=(Fc=(Nc=r.features)==null?void 0:Nc.showToolCalls)!=null?Fc:!0,ue=(_c=(Oc=r.features)==null?void 0:Oc.scrollToBottom)!=null?_c:{};let ye=Ct();oe=(Uc=($c=r.features)==null?void 0:$c.scrollBehavior)!=null?Uc:{},ye!==Ct()&&(hn(),Bn()),ar(),ot();let De=ce;if(ce=(qc=(zc=r.features)==null?void 0:zc.showEventStreamToggle)!=null?qc:!1,ce&&!De){if(V||($e=new ta(de),V=new ea(Ne,$e),G=G!=null?G:new na,$e.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),U.setSSEEventCallback((re,Tt)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,re,Tt),G==null||G.processEvent(re,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!ut&&ke){let re=(Vc=(jc=r.features)==null?void 0:jc.eventStream)==null?void 0:Vc.classNames,Tt="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"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");ut=y("button",Tt),ut.style.width="28px",ut.style.height="28px",ut.style.color=In.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let jt=fe("activity","18px","currentColor",1.5);jt&&ut.appendChild(jt);let rt=ze.clearChatButtonWrapper,Lt=ze.closeButtonWrapper,sn=rt||Lt;sn&&sn.parentNode===ke?ke.insertBefore(ut,sn):ke.appendChild(ut),ut.addEventListener("click",()=>{X?ir():Wr()})}}else!ce&&De&&(ir(),ut&&(ut.remove(),ut=null),V==null||V.clear(),$e==null||$e.destroy(),V=null,$e=null,G==null||G.reset(),G=null);if(((Kc=r.launcher)==null?void 0:Kc.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((Gc=r.launcher)==null?void 0:Gc.enabled)===!1&&on&&(on.remove(),on=null),((Qc=r.launcher)==null?void 0:Qc.enabled)!==!1&&!Yt&&!on){let{instance:re,element:Tt}=$i({config:r,plugins:o,onToggle:Cl});Yt=re,re||(on=Tt),t.appendChild(Tt)}Yt&&Yt.update(r),Te&&((Xc=r.launcher)==null?void 0:Xc.title)!==void 0&&(Te.textContent=r.launcher.title),Re&&((Jc=r.launcher)==null?void 0:Jc.subtitle)!==void 0&&(Re.textContent=r.launcher.subtitle);let we=(Yc=r.layout)==null?void 0:Yc.header;if((we==null?void 0:we.layout)!==F&&ke){let re=we?qa(r,we,{showClose:$(),onClose:()=>zt(!1,"user")}):Ho({config:r,showClose:$(),onClose:()=>zt(!1,"user")});Ye.replaceHeader(re),ke=Ye.header.element,te=Ye.header.iconHolder,Te=Ye.header.headerTitle,Re=Ye.header.headerSubtitle,A=Ye.header.closeButton,F=we==null?void 0:we.layout}else if(we&&(te&&(te.style.display=we.showIcon===!1?"none":""),Te&&(Te.style.display=we.showTitle===!1?"none":""),Re&&(Re.style.display=we.showSubtitle===!1?"none":""),A&&(A.style.display=we.showCloseButton===!1?"none":""),ze.clearChatButtonWrapper)){let re=we.showClearChat;if(re!==void 0){ze.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Tt}=ze;Tt&&!Tt.classList.contains("persona-absolute")&&(re?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let _e=((Zc=r.layout)==null?void 0:Zc.showHeader)!==!1;ke&&(ke.style.display=_e?"":"none");let ct=((ed=r.layout)==null?void 0:ed.showFooter)!==!1;Be&&(Be.style.display=ct?"":"none"),En(),ot(),k!==L?k?zt(E,"auto"):(N=!0,As()):E!==C&&zt(E,"auto"),C=E,L=k,Ss(),Ll();let Me=JSON.stringify(l.toolCall)!==JSON.stringify(p),Ue=JSON.stringify(r.messageActions)!==JSON.stringify(h),je=JSON.stringify((td=r.layout)==null?void 0:td.messages)!==JSON.stringify(b),ft=((nd=r.loadingIndicator)==null?void 0:nd.render)!==(B==null?void 0:B.render)||((rd=r.loadingIndicator)==null?void 0:rd.renderIdle)!==(B==null?void 0:B.renderIdle)||((od=r.loadingIndicator)==null?void 0:od.showBubble)!==(B==null?void 0:B.showBubble),I=r.iterationDisplay!==q,We=((ad=(sd=r.features)==null?void 0:sd.showReasoning)!=null?ad:!0)!==(_!=null?_:!0)||((ld=(id=r.features)==null?void 0:id.showToolCalls)!=null?ld:!0)!==(D!=null?D:!0)||JSON.stringify((cd=r.features)==null?void 0:cd.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((dd=r.features)==null?void 0:dd.reasoningDisplay)!==JSON.stringify(ie);(Me||Ue||je||ft||I||We)&&U&&($o++,vs(tt,U.getMessages(),ee));let me=(pd=r.launcher)!=null?pd:{},Dt=(ud=me.headerIconHidden)!=null?ud:!1,Rt=(gd=(md=r.layout)==null?void 0:md.header)==null?void 0:gd.showIcon,Kt=Dt||Rt===!1,ht=me.headerIconName,qt=(fd=me.headerIconSize)!=null?fd:"48px";if(te){let re=xe.querySelector(".persona-border-b-persona-divider"),Tt=re==null?void 0:re.querySelector(".persona-flex-col");if(Kt)te.style.display="none",re&&Tt&&!re.contains(Tt)&&re.insertBefore(Tt,re.firstChild);else{if(te.style.display="",te.style.height=qt,te.style.width=qt,re&&Tt&&(re.contains(te)?te.nextSibling!==Tt&&(te.remove(),re.insertBefore(te,Tt)):re.insertBefore(te,Tt)),ht){let rt=parseFloat(qt)||24,Lt=fe(ht,rt*.6,"currentColor",1);Lt?te.replaceChildren(Lt):te.textContent=(hd=me.agentIconText)!=null?hd:"\u{1F4AC}"}else if(me.iconUrl){let rt=te.querySelector("img");if(rt)rt.src=me.iconUrl,rt.style.height=qt,rt.style.width=qt;else{let Lt=document.createElement("img");Lt.src=me.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=qt,Lt.style.width=qt,te.replaceChildren(Lt)}}else{let rt=te.querySelector("svg"),Lt=te.querySelector("img");(rt||Lt)&&te.replaceChildren(),te.textContent=(yd=me.agentIconText)!=null?yd:"\u{1F4AC}"}let jt=te.querySelector("img");jt&&(jt.style.height=qt,jt.style.width=qt)}}let jn=(vd=(bd=r.layout)==null?void 0:bd.header)==null?void 0:vd.showTitle,Zt=(wd=(xd=r.layout)==null?void 0:xd.header)==null?void 0:wd.showSubtitle;if(Te&&(Te.style.display=jn===!1?"none":""),Re&&(Re.style.display=Zt===!1?"none":""),A){((Ad=(Cd=r.layout)==null?void 0:Cd.header)==null?void 0:Ad.showCloseButton)===!1?A.style.display="none":A.style.display="";let Tt=(Sd=me.closeButtonSize)!=null?Sd:"32px",jt=(Td=me.closeButtonPlacement)!=null?Td:"inline";A.style.height=Tt,A.style.width=Tt;let{closeButtonWrapper:rt}=ze,Lt=jt==="top-right",sn=rt==null?void 0:rt.classList.contains("persona-absolute");if(rt&&Lt!==sn)if(rt.remove(),Lt)rt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",xe.style.position="relative",xe.appendChild(rt);else{let st=(Md=(Ed=me.clearChat)==null?void 0:Ed.placement)!=null?Md:"inline",an=(Ld=(kd=me.clearChat)==null?void 0:kd.enabled)!=null?Ld:!0;rt.className=an&&st==="inline"?"":"persona-ml-auto";let Dn=xe.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(rt)}if(A.style.color=me.closeButtonColor||In.actionIconColor,me.closeButtonBackgroundColor?(A.style.backgroundColor=me.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let st=me.closeButtonBorderWidth||"0px",an=me.closeButtonBorderColor||"transparent";A.style.border=`${st} solid ${an}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");me.closeButtonBorderRadius?(A.style.borderRadius=me.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(A.style.paddingLeft=me.closeButtonPaddingX,A.style.paddingRight=me.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),me.closeButtonPaddingY?(A.style.paddingTop=me.closeButtonPaddingY,A.style.paddingBottom=me.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let xn=(Pd=me.closeButtonIconName)!=null?Pd:"x",ur=(Id=me.closeButtonIconText)!=null?Id:"\xD7";A.innerHTML="";let Pn=fe(xn,"28px","currentColor",1);Pn?A.appendChild(Pn):A.textContent=ur;let Jt=(Wd=me.closeButtonTooltipText)!=null?Wd:"Close chat",Gn=(Rd=me.closeButtonShowTooltip)!=null?Rd:!0;if(A.setAttribute("aria-label",Jt),rt&&(rt._cleanupTooltip&&(rt._cleanupTooltip(),delete rt._cleanupTooltip),Gn&&Jt)){let st=null,an=()=>{if(st||!A)return;let Eo=A.ownerDocument,Es=Eo.body;if(!Es)return;st=Pr(Eo,"div","persona-clear-chat-tooltip"),st.textContent=Jt;let Ms=Pr(Eo,"div");Ms.className="persona-clear-chat-tooltip-arrow",st.appendChild(Ms);let Mo=A.getBoundingClientRect();st.style.position="fixed",st.style.zIndex=String(po),st.style.left=`${Mo.left+Mo.width/2}px`,st.style.top=`${Mo.top-8}px`,st.style.transform="translate(-50%, -100%)",Es.appendChild(st)},Dn=()=>{st&&st.parentNode&&(st.parentNode.removeChild(st),st=null)};rt.addEventListener("mouseenter",an),rt.addEventListener("mouseleave",Dn),A.addEventListener("focus",an),A.addEventListener("blur",Dn),rt._cleanupTooltip=()=>{Dn(),rt&&(rt.removeEventListener("mouseenter",an),rt.removeEventListener("mouseleave",Dn)),A&&(A.removeEventListener("focus",an),A.removeEventListener("blur",Dn))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Mt}=ze;if(Ke){let re=(Hd=me.clearChat)!=null?Hd:{},Tt=(Bd=re.enabled)!=null?Bd:!0,jt=(Nd=(Dd=r.layout)==null?void 0:Dd.header)==null?void 0:Nd.showClearChat,rt=jt!==void 0?jt:Tt,Lt=(Fd=re.placement)!=null?Fd:"inline";if(Mt){Mt.style.display=rt?"":"none";let{closeButtonWrapper:sn}=ze;!R()&&sn&&!sn.classList.contains("persona-absolute")&&(rt?sn.classList.remove("persona-ml-auto"):sn.classList.add("persona-ml-auto"));let xn=Lt==="top-right",ur=Mt.classList.contains("persona-absolute");if(!R()&&xn!==ur&&rt){if(Mt.remove(),xn)Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px",xe.style.position="relative",xe.appendChild(Mt);else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let Jt=xe.querySelector(".persona-border-b-persona-divider"),Gn=ze.closeButtonWrapper;Jt&&Gn&&Gn.parentElement===Jt?Jt.insertBefore(Mt,Gn):Jt&&Jt.appendChild(Mt)}let Pn=ze.closeButtonWrapper;Pn&&!Pn.classList.contains("persona-absolute")&&(xn?Pn.classList.add("persona-ml-auto"):Pn.classList.remove("persona-ml-auto"))}}if(rt){if(!R()){let st=(Od=re.size)!=null?Od:"32px";Ke.style.height=st,Ke.style.width=st}let sn=(_d=re.iconName)!=null?_d:"refresh-cw",xn=($d=re.iconColor)!=null?$d:"";Ke.style.color=xn||In.actionIconColor,Ke.innerHTML="";let ur=R()?"14px":"20px",Pn=fe(sn,ur,"currentColor",2);if(Pn&&Ke.appendChild(Pn),re.backgroundColor?(Ke.style.backgroundColor=re.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let st=re.borderWidth||"0px",an=re.borderColor||"transparent";Ke.style.border=`${st} solid ${an}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");re.borderRadius?(Ke.style.borderRadius=re.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),re.paddingX?(Ke.style.paddingLeft=re.paddingX,Ke.style.paddingRight=re.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),re.paddingY?(Ke.style.paddingTop=re.paddingY,Ke.style.paddingBottom=re.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Jt=(Ud=re.tooltipText)!=null?Ud:"Clear chat",Gn=(zd=re.showTooltip)!=null?zd:!0;if(Ke.setAttribute("aria-label",Jt),Mt&&(Mt._cleanupTooltip&&(Mt._cleanupTooltip(),delete Mt._cleanupTooltip),Gn&&Jt)){let st=null,an=()=>{if(st||!Ke)return;let Eo=Ke.ownerDocument,Es=Eo.body;if(!Es)return;st=Pr(Eo,"div","persona-clear-chat-tooltip"),st.textContent=Jt;let Ms=Pr(Eo,"div");Ms.className="persona-clear-chat-tooltip-arrow",st.appendChild(Ms);let Mo=Ke.getBoundingClientRect();st.style.position="fixed",st.style.zIndex=String(po),st.style.left=`${Mo.left+Mo.width/2}px`,st.style.top=`${Mo.top-8}px`,st.style.transform="translate(-50%, -100%)",Es.appendChild(st)},Dn=()=>{st&&st.parentNode&&(st.parentNode.removeChild(st),st=null)};Mt.addEventListener("mouseenter",an),Mt.addEventListener("mouseleave",Dn),Ke.addEventListener("focus",an),Ke.addEventListener("blur",Dn),Mt._cleanupTooltip=()=>{Dn(),Mt&&(Mt.removeEventListener("mouseenter",an),Mt.removeEventListener("mouseleave",Dn)),Ke&&(Ke.removeEventListener("focus",an),Ke.removeEventListener("blur",Dn))}}}}let tn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[nl],nr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ra.message,ra.messageAndClick];T=rl({parsers:tn,handlers:nr,getSessionMetadata:x,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=Um(r,T,pe),U.updateConfig(r),vs(tt,U.getMessages(),ee),_o(),gl(),si(U.isStreaming());let Vn=((qd=r.voiceRecognition)==null?void 0:qd.enabled)===!0,Co=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ao=((Vd=(jd=r.voiceRecognition)==null?void 0:jd.provider)==null?void 0:Vd.type)==="runtype";if(Vn&&(Co||Ao))if(!H||!J){let re=mg(r.voiceRecognition,r.sendButton);re&&(H=re.micButton,J=re.micButtonWrapper,Pt.insertBefore(J,gn),H.addEventListener("click",ua),H.disabled=U.isStreaming())}else{let re=(Kd=r.voiceRecognition)!=null?Kd:{},Tt=(Gd=r.sendButton)!=null?Gd:{},jt=(Qd=re.iconName)!=null?Qd:"mic",rt=(Xd=Tt.size)!=null?Xd:"40px",Lt=(Jd=re.iconSize)!=null?Jd:rt,sn=parseFloat(Lt)||24;H.style.width=Lt,H.style.height=Lt,H.style.minWidth=Lt,H.style.minHeight=Lt;let xn=(Zd=(Yd=re.iconColor)!=null?Yd:Tt.textColor)!=null?Zd:"currentColor";H.innerHTML="";let ur=fe(jt,sn,xn,2);ur?H.appendChild(ur):H.textContent="\u{1F3A4}";let Pn=(ep=re.backgroundColor)!=null?ep:Tt.backgroundColor;Pn?H.style.backgroundColor=Pn:H.style.backgroundColor="",xn?H.style.color=xn:H.style.color="var(--persona-text, #111827)",re.borderWidth?(H.style.borderWidth=re.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),re.borderColor?H.style.borderColor=re.borderColor:H.style.borderColor="",re.paddingX?(H.style.paddingLeft=re.paddingX,H.style.paddingRight=re.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),re.paddingY?(H.style.paddingTop=re.paddingY,H.style.paddingBottom=re.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Jt=J==null?void 0:J.querySelector(".persona-send-button-tooltip"),Gn=(tp=re.tooltipText)!=null?tp:"Start voice recognition";if(((np=re.showTooltip)!=null?np:!1)&&Gn)if(Jt)Jt.textContent=Gn,Jt.style.display="";else{let an=document.createElement("div");an.className="persona-send-button-tooltip",an.textContent=Gn,J==null||J.insertBefore(an,H)}else Jt&&(Jt.style.display="none");J.style.display="",H.disabled=U.isStreaming()}else H&&J&&(J.style.display="none",((op=(rp=r.voiceRecognition)==null?void 0:rp.provider)==null?void 0:op.type)==="runtype"?U.isVoiceActive()&&U.toggleVoice():Mr&&to());if(((sp=r.attachments)==null?void 0:sp.enabled)===!0)if(!it||!Ae){let re=(ap=r.attachments)!=null?ap:{},jt=(lp=((ip=r.sendButton)!=null?ip:{}).size)!=null?lp:"40px";Ut||(Ut=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",Bt.insertBefore(Ut,ne)),Qe||(Qe=document.createElement("input"),Qe.type="file",Qe.accept=((cp=re.allowedTypes)!=null?cp:qr).join(","),Qe.multiple=((dp=re.maxFiles)!=null?dp:4)>1,Qe.style.display="none",Qe.setAttribute("aria-label","Attach files"),Bt.insertBefore(Qe,ne)),it=y("div","persona-send-button-wrapper"),Ae=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ae.type="button",Ae.setAttribute("aria-label",(pp=re.buttonTooltipText)!=null?pp:"Attach file");let rt=(up=re.buttonIconName)!=null?up:"paperclip",Lt=jt,sn=parseFloat(Lt)||40,xn=Math.round(sn*.6);Ae.style.width=Lt,Ae.style.height=Lt,Ae.style.minWidth=Lt,Ae.style.minHeight=Lt,Ae.style.fontSize="18px",Ae.style.lineHeight="1",Ae.style.backgroundColor="transparent",Ae.style.color="var(--persona-primary, #111827)",Ae.style.border="none",Ae.style.borderRadius="6px",Ae.style.transition="background-color 0.15s ease",Ae.addEventListener("mouseenter",()=>{Ae.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ae.addEventListener("mouseleave",()=>{Ae.style.backgroundColor="transparent"});let ur=fe(rt,xn,"currentColor",1.5);ur?Ae.appendChild(ur):Ae.textContent="\u{1F4CE}",Ae.addEventListener("click",Gn=>{Gn.preventDefault(),Qe==null||Qe.click()}),it.appendChild(Ae);let Pn=(mp=re.buttonTooltipText)!=null?mp:"Attach file",Jt=y("div","persona-send-button-tooltip");Jt.textContent=Pn,it.appendChild(Jt),at.append(it),!At&&Qe&&Ut&&(At=zs.fromConfig(re),At.setPreviewsContainer(Ut),Qe.addEventListener("change",async()=>{At&&(Qe!=null&&Qe.files)&&(await At.handleFileSelect(Qe.files),Qe.value="")})),xe.querySelector(".persona-attachment-drop-overlay")||xe.appendChild(zm(re.dropOverlay))}else{it.style.display="";let re=(gp=r.attachments)!=null?gp:{};Qe&&(Qe.accept=((fp=re.allowedTypes)!=null?fp:qr).join(","),Qe.multiple=((hp=re.maxFiles)!=null?hp:4)>1),At&&At.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else it&&(it.style.display="none"),At&&At.clearAttachments(),(yp=xe.querySelector(".persona-attachment-drop-overlay"))==null||yp.remove();let Gt=(bp=r.sendButton)!=null?bp:{},So=(vp=Gt.useIcon)!=null?vp:!1,ro=(xp=Gt.iconText)!=null?xp:"\u2191",oo=Gt.iconName,$r=(wp=Gt.tooltipText)!=null?wp:"Send message",To=(Cp=Gt.showTooltip)!=null?Cp:!1,pr=(Ap=Gt.size)!=null?Ap:"40px",kr=Gt.backgroundColor,Ge=Gt.textColor;if(So){if(Oe.style.width=pr,Oe.style.height=pr,Oe.style.minWidth=pr,Oe.style.minHeight=pr,Oe.style.fontSize="18px",Oe.style.lineHeight="1",Oe.innerHTML="",Ge?Oe.style.color=Ge:Oe.style.color="var(--persona-button-primary-fg, #ffffff)",oo){let re=parseFloat(pr)||24,Tt=(Ge==null?void 0:Ge.trim())||"currentColor",jt=fe(oo,re,Tt,2);jt?Oe.appendChild(jt):Oe.textContent=ro}else Oe.textContent=ro;Oe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",kr?(Oe.style.backgroundColor=kr,Oe.classList.remove("persona-bg-persona-primary")):(Oe.style.backgroundColor="",Oe.classList.add("persona-bg-persona-primary"))}else Oe.textContent=(Tp=(Sp=r.copy)==null?void 0:Sp.sendButtonLabel)!=null?Tp:"Send",Oe.style.width="",Oe.style.height="",Oe.style.minWidth="",Oe.style.minHeight="",Oe.style.fontSize="",Oe.style.lineHeight="",Oe.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",kr?(Oe.style.backgroundColor=kr,Oe.classList.remove("persona-bg-persona-accent")):Oe.classList.add("persona-bg-persona-accent"),Ge?Oe.style.color=Ge:Oe.classList.add("persona-text-white");Gt.borderWidth?(Oe.style.borderWidth=Gt.borderWidth,Oe.style.borderStyle="solid"):(Oe.style.borderWidth="",Oe.style.borderStyle=""),Gt.borderColor?Oe.style.borderColor=Gt.borderColor:Oe.style.borderColor="",Gt.paddingX?(Oe.style.paddingLeft=Gt.paddingX,Oe.style.paddingRight=Gt.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),Gt.paddingY?(Oe.style.paddingTop=Gt.paddingY,Oe.style.paddingBottom=Gt.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let Nt=gn==null?void 0:gn.querySelector(".persona-send-button-tooltip");if(To&&$r)if(Nt)Nt.textContent=$r,Nt.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=$r,gn==null||gn.insertBefore(re,Oe)}else Nt&&(Nt.style.display="none");let Vt=(Pp=(Ep=r.layout)==null?void 0:Ep.contentMaxWidth)!=null?Pp:R()?(Lp=(kp=(Mp=r.launcher)==null?void 0:Mp.composerBar)==null?void 0:kp.contentMaxWidth)!=null?Lp:"720px":void 0;Vt?(tt.style.maxWidth=Vt,tt.style.marginLeft="auto",tt.style.marginRight="auto",tt.style.width="100%",Bt&&(Bt.style.maxWidth=Vt,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"),Ot&&(Ot.style.maxWidth=Vt,Ot.style.marginLeft="auto",Ot.style.marginRight="auto")):(tt.style.maxWidth="",tt.style.marginLeft="",tt.style.marginRight="",tt.style.width="",Bt&&(Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight=""),Ot&&(Ot.style.maxWidth="",Ot.style.marginLeft="",Ot.style.marginRight=""));let Ft=(Ip=r.statusIndicator)!=null?Ip:{},Qt=(Wp=Ft.visible)!=null?Wp:!0;if(Xt.style.display=Qt?"":"none",U){let re=U.getStatus();dt(Xt,(jt=>{var rt,Lt,sn,xn;return jt==="idle"?(rt=Ft.idleText)!=null?rt:wn.idle:jt==="connecting"?(Lt=Ft.connectingText)!=null?Lt:wn.connecting:jt==="connected"?(sn=Ft.connectedText)!=null?sn:wn.connected:jt==="error"?(xn=Ft.errorText)!=null?xn:wn.error:wn[jt]})(re),Ft,re)}Xt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kt=Ft.align==="left"?"persona-text-left":Ft.align==="center"?"persona-text-center":"persona-text-right";Xt.classList.add(kt)},open(){$()&&zt(!0,"api")},close(){$()&&zt(!1,"api")},toggle(){$()&&zt(!N,"api")},clearChat(){Mn=!1,U.clearMessages(),Sr.clear(),Bn();try{localStorage.removeItem(gs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==gs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let p=c.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}u={},T.syncFromMetadata(),V==null||V.clear(),G==null||G.reset(),be==null||be.update()},setMessage(l){return!ne||U.isStreaming()?!1:(!N&&$()&&zt(!0,"system"),ne.value=l,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(U.isStreaming())return!1;let p=(l==null?void 0:l.trim())||ne.value.trim();return p?(!N&&$()&&zt(!0,"system"),ne.value="",ne.style.height="auto",U.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return U.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(U.isVoiceActive()||(!N&&$()&&zt(!0,"system"),pt.manuallyDeactivated=!1,Hn(),U.toggleVoice().then(()=>{pt.active=U.isVoiceActive(),Zn("user"),U.isVoiceActive()&&Qo()})),!0):Mr?!0:wl()?(!N&&$()&&zt(!0,"system"),pt.manuallyDeactivated=!1,Hn(),da("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?U.isVoiceActive()?(U.toggleVoice().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Hn(),Zn("user"),_r()}),!0):!1:Mr?(pt.manuallyDeactivated=!0,Hn(),to("user"),!0):!1},injectMessage(l){return!N&&$()&&zt(!0,"system"),U.injectMessage(l)},injectAssistantMessage(l){!N&&$()&&zt(!0,"system");let p=U.injectAssistantMessage(l);return Z&&(Z=!1,Se&&(clearTimeout(Se),Se=null),setTimeout(()=>{U&&!U.isStreaming()&&U.continueConversation()},100)),p},injectUserMessage(l){return!N&&$()&&zt(!0,"system"),U.injectUserMessage(l)},injectSystemMessage(l){return!N&&$()&&zt(!0,"system"),U.injectSystemMessage(l)},injectMessageBatch(l){return!N&&$()&&zt(!0,"system"),U.injectMessageBatch(l)},injectComponentDirective(l){return!N&&$()&&zt(!0,"system"),U.injectComponentDirective(l)},injectTestMessage(l){!N&&$()&&zt(!0,"system"),U.injectTestEvent(l)},async connectStream(l,p){return U.connectStream(l,p)},__pushEventStreamEvent(l){V&&(G==null||G.processEvent(l.type,l.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ce||!V||Wr()},hideEventStream(){X&&ir()},isEventStreamVisible(){return X},showArtifacts(){sr(r)&&(Mn=!1,Rn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){sr(r)&&(Mn=!0,Rn())},upsertArtifact(l){return sr(r)?(Mn=!1,U.upsertArtifact(l)):null},selectArtifact(l){sr(r)&&U.selectArtifact(l)},clearArtifacts(){sr(r)&&U.clearArtifacts()},getArtifacts(){var l;return(l=U==null?void 0:U.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=U==null?void 0:U.getSelectedArtifactId())!=null?l:null},focusInput(){return k&&!N&&!R()||!ne?!1:(ne.focus(),!0)},async resolveApproval(l,p,h){let S=U.getMessages().find(B=>{var q;return B.variant==="approval"&&((q=B.approval)==null?void 0:q.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){U.resolveWebMcpApproval(S.id,p);return}return U.resolveApproval(S.approval,p,h)},getMessages(){return U.getMessages()},getStatus(){return U.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(l){v(l)},on(l,p){return i.on(l,p)},off(l,p){i.off(l,p)},isOpen(){return $()&&N},isVoiceActive(){return pt.active},toggleReadAloud(l){U.toggleReadAloud(l)},stopReadAloud(){U.stopSpeaking()},getReadAloudState(l){return U.getReadAloudState(l)},onReadAloudChange(l){return U.onReadAloudChange(l)},getState(){return{open:$()&&N,launcherEnabled:k,voiceActive:pt.active,streaming:U.isStreaming()}},showCSATFeedback(l){!N&&$()&&zt(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=Om({onSubmit:async(b,S)=>{var B;U.isClientTokenMode()&&await U.submitCSATFeedback(b,S),(B=l==null?void 0:l.onSubmit)==null||B.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!N&&$()&&zt(!0,"system");let p=tt.querySelector(".persona-feedback-container");p&&p.remove();let h=_m({onSubmit:async(b,S)=>{var B;U.isClientTokenMode()&&await U.submitNPSFeedback(b,S),(B=l==null?void 0:l.onSubmit)==null||B.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});tt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return U.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return U.submitNPSFeedback(l,p)},destroy(){wo!=null&&(clearInterval(wo),wo=null),mt.forEach(l=>l()),He.remove(),qe==null||qe.remove(),Yt==null||Yt.destroy(),on==null||on.remove(),Cr&&A.removeEventListener("click",Cr)}};if((((kc=n==null?void 0:n.debugTools)!=null?kc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:h=>h?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=p,mt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),p=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.focusInput()};if(window.addEventListener("persona:focusInput",p),mt.push(()=>{window.removeEventListener("persona:focusInput",p)}),ce){let _=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===l)&&en.showEventStream()},D=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===l)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),mt.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.showArtifacts()},b=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.hideArtifacts()},S=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&en.upsertArtifact(D.artifact)},B=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&en.selectArtifact(D.id)},q=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",q),mt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",q)})}let tr=Hv(r.persistState);if(tr&&$()){let l=Bv(tr.storage),p=`${tr.keyPrefix}widget-open`,h=`${tr.keyPrefix}widget-voice`,b=`${tr.keyPrefix}widget-voice-mode`;if(l){let S=((Lc=tr.persist)==null?void 0:Lc.openState)&&l.getItem(p)==="true",B=((Pc=tr.persist)==null?void 0:Pc.voiceState)&&l.getItem(h)==="true",q=((Ic=tr.persist)==null?void 0:Ic.voiceState)&&l.getItem(b)==="true";if(S&&setTimeout(()=>{en.open(),setTimeout(()=>{var _;if(B||q)en.startVoiceRecognition();else if((_=tr.persist)!=null&&_.focusInput){let D=t.querySelector("textarea");D&&D.focus()}},100)},0),(Wc=tr.persist)!=null&&Wc.openState&&(i.on("widget:opened",()=>{l.setItem(p,"true")}),i.on("widget:closed",()=>{l.setItem(p,"false")})),(Rc=tr.persist)!=null&&Rc.voiceState&&(i.on("voice:state",_=>{l.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{l.setItem(b,_.viaVoice?"true":"false")})),tr.clearOnChatClear){let _=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(b)},D=()=>_();window.addEventListener("persona:clear-chat",D),mt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return g&&$()&&setTimeout(()=>{en.open()},0),Ko(),sa||Np().then(()=>{U&&($o++,Sr.clear(),vs(tt,U.getMessages(),ee))}).catch(()=>{}),en};var Dv=(t,e)=>{let n=t.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,e*parseFloat(o[1])/100):420},Nv=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Fv=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Ov=(t,e)=>{let n=t.parentElement;if(!n)return;let r=t.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},jm=(t,e)=>{var r,o;let n=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0"},ll=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},Vm=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",ll(t)},sl=t=>{t.style.transition=""},al=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},il=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},oi=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},_v=(t,e,n,r,o)=>{o?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,r),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(r))},$v=(t,e,n,r,o,s)=>{let a=s?e:t;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Km=(t,e,n,r,o,s,a)=>{var x,v,M,W,T,k;let i=gr(s),d=i.reveal==="push";_v(t,e,n,r,d),$v(t,e,n,r,i.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=i.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=t.ownerDocument.defaultView,u=(v=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,f=(W=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?W:640,g=c!=null?c.innerWidth<=f:!1;if(u&&g&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),al(e),sl(r),Vm(r),il(n),oi(o,r),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((k=(T=s==null?void 0:s.launcher)==null?void 0:T.zIndex)!=null?k:Cn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),Vm(r),Nv(r,i.maxHeight),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",al(e),sl(r),il(n),oi(o,r);let E=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":P;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=E,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",sl(r),ll(r),oi(o,r);let E=Dv(i.width,t.clientWidth),P=Math.max(0,t.clientWidth),C=i.animate?"margin-left 180ms ease":"none",L=i.side==="right"?a?-E:0:a?0:-E;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${P+E}px`,e.style.transition=C,e.style.marginLeft=`${L}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",al(e),ll(r),il(n),oi(o,r);let E=i.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",L=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",Fv(r,i.maxHeight),r.style.overflow=E||L?"hidden":"visible",r.style.transition=C,E&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Uv=(t,e)=>{let n=t.ownerDocument.createElement("div");return jm(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){jm(n,r)},destroy(){n.remove()}}},zv=(t,e)=>{var k,E,P,C;let{ownerDocument:n}=t,r=t.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=t.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),u=n.createElement("div"),f=(E=(k=e==null?void 0:e.launcher)==null?void 0:k.enabled)==null||E?(C=(P=e==null?void 0:e.launcher)==null?void 0:P.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),r.insertBefore(a,t),d.appendChild(t);let g=null,m=()=>{g==null||g.disconnect(),g=null},x=()=>{m(),gr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Km(a,i,d,c,u,e,f)}),g.observe(a))},v=!1,M=()=>{Km(a,i,d,c,u,e,f),x(),f&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Ov(a,gr(e)))},W=a.ownerDocument.defaultView,T=()=>{M()};return W==null||W.addEventListener("resize",T),gr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:u,shell:a,syncWidgetState(L){let F=L.launcherEnabled?L.open:!0;f!==F&&(f=F,M())},updateConfig(L){var F,O;e=L,((O=(F=e==null?void 0:e.launcher)==null?void 0:F.enabled)!=null?O:!0)===!1&&(f=!0),M()},destroy(){W==null||W.removeEventListener("resize",T),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(t,s):r.appendChild(t)),a.remove()}}},Gm=(t,e)=>yn(e)?zv(t,e):Uv(t,e);var oa={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Qm=.15,Xm=1.5,cl="persona-preview-shell-theme",qv={load:()=>null,save:()=>{},clear:()=>{}},jv=["How do I get started?","Pricing & plans","Talk to support"];function dl(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Vv(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Jm(t){let e=Vv(t);return`* { box-sizing: border-box; }
112
112
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
113
- html { color-scheme: ${n}; }
113
+ html { color-scheme: ${t}; }
114
114
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
115
115
  .preview-iframe-mock { min-height: 100%; }
116
116
  .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
@@ -132,7 +132,7 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
132
132
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
133
133
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
134
134
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
135
- .preview-workspace-card.short { height: 96px; }`}function zm(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(sl);r||(r=t.createElement("style"),r.id=sl,t.head.appendChild(r)),r.textContent=qm(e)}var Wv=`
135
+ .preview-workspace-card.short { height: 96px; }`}function Ym(t,e){let n=t.contentDocument;if(!(n!=null&&n.documentElement))return;let r=n.getElementById(cl);r||(r=n.createElement("style"),r.id=cl,n.head.appendChild(r)),r.textContent=Jm(e)}var Kv=`
136
136
  <div class="preview-iframe-mock" aria-hidden="true">
137
137
  <div class="preview-iframe-chrome">
138
138
  <span class="preview-iframe-dot"></span>
@@ -151,7 +151,7 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
151
151
  <div class="preview-iframe-line body"></div>
152
152
  <div class="preview-iframe-line body"></div>
153
153
  </div>
154
- </div>`,Rv=`
154
+ </div>`,Gv=`
155
155
  <div class="preview-workspace-content-shell" aria-hidden="true">
156
156
  <div class="preview-iframe-line hero"></div>
157
157
  <div class="preview-iframe-line body"></div>
@@ -164,9 +164,9 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
164
164
  <div class="preview-workspace-card short"></div>
165
165
  <div class="preview-workspace-card short"></div>
166
166
  </div>
167
- </div>`;function jm(n,e,t,r){let o=`
168
- ${Wv}
169
- <div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
167
+ </div>`;function Zm(t,e,n,r){let o=`
168
+ ${Kv}
169
+ <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
170
170
  <div class="preview-workspace-shell">
171
171
  <div class="preview-workspace-topbar">
172
172
  <div class="preview-workspace-topbar-left">
@@ -176,8 +176,8 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
176
176
  <span class="preview-workspace-topbar-pill"></span>
177
177
  </div>
178
178
  <div class="preview-workspace-body">
179
- <div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
180
- ${Rv}
179
+ <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
180
+ ${Gv}
181
181
  </div>
182
182
  </div>
183
183
  </div>`;return`<!DOCTYPE html>
@@ -185,16 +185,16 @@ _Details: ${t.message}_`:r}var Ns=n=>({isError:!0,content:[{type:"text",text:n}]
185
185
  <head>
186
186
  <meta charset="UTF-8">
187
187
  <meta name="viewport" content="width=device-width, initial-scale=1">
188
- <link rel="stylesheet" href="${al(r)}">
189
- <style id="${sl}">${qm(e)}</style>
188
+ <link rel="stylesheet" href="${dl(r)}">
189
+ <style id="${cl}">${Jm(e)}</style>
190
190
  </head>
191
191
  <body>
192
- ${t?s:o}
192
+ ${n?s:o}
193
193
  </body>
194
- </html>`}var Hv=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Bv=n=>{var e,t,r,o,s,a,i,d;return!!((t=(e=n==null?void 0:n.features)==null?void 0:e.toolCallDisplay)!=null&&t.activePreview||(o=(r=n==null?void 0:n.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=n==null?void 0:n.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&n.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=n==null?void 0:n.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Dv(n,e,t=[]){return n==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:n==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:n==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:n==="conversation"&&Bv(e)?[...Hv(),...t]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...t]}function Nv(n,e,t=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:e!=="minimized"},o={...n,launcher:r,suggestionChips:e==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:Pv:n.suggestionChips,initialMessages:Dv(e,n,t),storageAdapter:Lv};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Fv(n,e){var r,o;let t=n.theme?Po(n.theme,{validate:!1}):Po();return{...Dt,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function ps(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Nv(Fv(n,e),t,(o=n.appendedMessages)!=null?o:[])}function Vm(n){var r,o,s,a,i;let e=(r=n.compareMode)!=null?r:"off",t=(o=n.shellMode)!=null?o:"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:ps(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:ps(n,"dark"),shellMode:"dark"}];if(e==="baseline"&&(n.baselineConfig||n.baselineTheme)){let d={...n,config:(s=n.baselineConfig)!=null?s:n.config,theme:(a=n.baselineTheme)!=null?a:n.theme,darkTheme:(i=n.baselineDarkTheme)!=null?i:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:ps(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:ps(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:ps(n,t),shellMode:t}]}function Ov(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function m(){var M;return(M=t.device)!=null?M:"desktop"}function f(){var M;return(M=t.zoom)!=null?M:i}function g(){var E,z;let M=getComputedStyle(n),N=parseFloat(M.paddingLeft)+parseFloat(M.paddingRight),k=parseFloat(M.paddingTop)+parseFloat(M.paddingBottom),W=40,C=((E=t.compareMode)!=null?E:"off")!=="off",I=(n.clientWidth-N-W)/(C?2:1),D=n.clientHeight-k-W;if(I<=0||D<=0)return 1;let B=(z=Zs[m()])!=null?z:Zs.desktop;return Math.min(I/B.w,D/B.h,1)}function u(){var k,W,C;i=g();let M=Math.max($m,Math.min(Um,f()));d=M;let N=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let I of N){let D=(k=I.dataset.device)!=null?k:"desktop",B=(W=Zs[D])!=null?W:Zs.desktop;I.style.width=`${B.w*M}px`,I.style.height=`${B.h*M}px`,D==="mobile"&&(I.style.borderRadius=`${32*M}px`);let E=I.querySelector("iframe");E&&(E.style.width=`${B.w}px`,E.style.height=`${B.h}px`,E.style.transformOrigin="top left",E.style.transition="none",E.style.transform=`scale(${M})`)}(C=t.onScaleChange)==null||C.call(t,M)}function v(){var M;(M=t.onBeforeDestroy)==null||M.call(t);for(let N of r)N.destroy();for(let N of o)N();r=[],o=[]}function x(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function P(){var ve,Pe,Oe,Ae;if(a)return;v();let M=++c,N=Vm(t),k=m(),W=((ve=t.compareMode)!=null?ve:"off")!=="off",C=((Pe=t.scene)!=null?Pe:"conversation")==="minimized",I=(Oe=t.widgetCssPath)!=null?Oe:"/widget-dist/widget.css",D=(Ae=t.buildSrcdoc)!=null?Ae:jm,B=k==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",E=be=>`<div class="${B}" data-mount-id="${be.mountId}" data-device="${k}" data-shell-mode="${be.shellMode}">
195
- ${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${al(be.label)}</span></div>`:""}
196
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${be.mountId}"></iframe>
197
- </div>`,z=W?`<div class="preview-compare-grid">${N.map(be=>`<div class="preview-compare-cell">${E(be)}</div>`).join("")}</div>`:`<div class="preview-single">${E(N[0])}</div>`;t.morphContainer?t.morphContainer(n,z):n.innerHTML=z,u();let j=x(),te=0,We=j.length,$e=()=>{var ne,Q,ae,fe,re;if(a||M!==c)return;for(let V of j){let ee=V.dataset.mountId;if(!ee||!V.contentDocument)continue;let Ue=N.find(it=>it.mountId===ee);if(!Ue)continue;let J=()=>{},ie=mn(Ue.config),Le=ie?(()=>{var X;let it=(X=V.contentDocument)==null?void 0:X.getElementById(`preview-content-${ee}`);if(!it)return null;let nt=_m(it,Ue.config),Me=V.contentDocument.createElement("div");Me.id=ee,Me.style.height="100%",Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1",Me.style.minHeight="0",nt.host.appendChild(Me);let de=()=>nt.syncWidgetState(at.getState()),Qe=J;return J=()=>{nt.destroy(),Qe()},Me.__syncDock=de,Me.__hostLayout=nt,Me})():V.contentDocument.getElementById(ee);if(!Le)continue;let at=Dm(Le,Ue.config);if(r.push(at),ie&&Le.__syncDock){let it=Le.__syncDock,nt=at.on("widget:opened",it),Me=at.on("widget:closed",it),de=J;J=()=>{nt(),Me(),de()},it()}o.push(J),C&&at.close()}if(((ne=t.scene)!=null?ne:"conversation")==="artifact"||(fe=(ae=(Q=t.config)==null?void 0:Q.features)==null?void 0:ae.artifacts)!=null&&fe.enabled)for(let V of r)V.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
194
+ </html>`}var Qv=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Xv=t=>{var e,n,r,o,s,a,i,d;return!!((n=(e=t==null?void 0:t.features)==null?void 0:e.toolCallDisplay)!=null&&n.activePreview||(o=(r=t==null?void 0:t.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=t==null?void 0:t.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=t==null?void 0:t.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Jv(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&Xv(e)?[...Qv(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Yv(t,e,n=[]){var s,a;let r={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},o={...t,launcher:r,suggestionChips:e==="home"?(s=t.suggestionChips)!=null&&s.length?t.suggestionChips:jv:t.suggestionChips,initialMessages:Jv(e,t,n),storageAdapter:qv};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Zv(t,e){var r,o;let n=t.theme?Wo(t.theme,{validate:!1}):Wo();return{...Ht,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:(o=e!=null?e:(r=t.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function fs(t,e){var r,o;let n=(r=t.scene)!=null?r:"conversation";return Yv(Zv(t,e),n,(o=t.appendedMessages)!=null?o:[])}function eg(t){var r,o,s,a,i;let e=(r=t.compareMode)!=null?r:"off",n=(o=t.shellMode)!=null?o:"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:fs(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:fs(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let d={...t,config:(s=t.baselineConfig)!=null?s:t.config,theme:(a=t.baselineTheme)!=null?a:t.theme,darkTheme:(i=t.baselineDarkTheme)!=null?i:t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:fs(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:fs(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:fs(t,n),shellMode:n}]}function ex(t,e){let n={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function u(){var T;return(T=n.device)!=null?T:"desktop"}function f(){var T;return(T=n.zoom)!=null?T:i}function g(){var R,$;let T=getComputedStyle(t),k=parseFloat(T.paddingLeft)+parseFloat(T.paddingRight),E=parseFloat(T.paddingTop)+parseFloat(T.paddingBottom),P=40,C=((R=n.compareMode)!=null?R:"off")!=="off",L=(t.clientWidth-k-P)/(C?2:1),F=t.clientHeight-E-P;if(L<=0||F<=0)return 1;let O=($=oa[u()])!=null?$:oa.desktop;return Math.min(L/O.w,F/O.h,1)}function m(){var E,P,C;i=g();let T=Math.max(Qm,Math.min(Xm,f()));d=T;let k=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let L of k){let F=(E=L.dataset.device)!=null?E:"desktop",O=(P=oa[F])!=null?P:oa.desktop;L.style.width=`${O.w*T}px`,L.style.height=`${O.h*T}px`,F==="mobile"&&(L.style.borderRadius=`${32*T}px`);let R=L.querySelector("iframe");R&&(R.style.width=`${O.w}px`,R.style.height=`${O.h}px`,R.style.transformOrigin="top left",R.style.transition="none",R.style.transform=`scale(${T})`)}(C=n.onScaleChange)==null||C.call(n,T)}function x(){var T;(T=n.onBeforeDestroy)==null||T.call(n);for(let k of r)k.destroy();for(let k of o)k();r=[],o=[]}function v(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function M(){var ee,ve,Ie,ce;if(a)return;x();let T=++c,k=eg(n),E=u(),P=((ee=n.compareMode)!=null?ee:"off")!=="off",C=((ve=n.scene)!=null?ve:"conversation")==="minimized",L=(Ie=n.widgetCssPath)!=null?Ie:"/widget-dist/widget.css",F=(ce=n.buildSrcdoc)!=null?ce:Zm,O=E==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",R=ue=>`<div class="${O}" data-mount-id="${ue.mountId}" data-device="${E}" data-shell-mode="${ue.shellMode}">
195
+ ${P?`<div class="preview-frame-meta"><span class="preview-frame-label">${dl(ue.label)}</span></div>`:""}
196
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ue.mountId}"></iframe>
197
+ </div>`,$=P?`<div class="preview-compare-grid">${k.map(ue=>`<div class="preview-compare-cell">${R(ue)}</div>`).join("")}</div>`:`<div class="preview-single">${R(k[0])}</div>`;n.morphContainer?n.morphContainer(t,$):t.innerHTML=$,m();let N=v(),Z=0,Se=N.length,pe=()=>{var oe,se,de,$e,Ne;if(a||T!==c)return;for(let V of N){let G=V.dataset.mountId;if(!G||!V.contentDocument)continue;let be=k.find(Ze=>Ze.mountId===G);if(!be)continue;let X=()=>{},le=yn(be.config),Ee=le?(()=>{var K;let Ze=(K=V.contentDocument)==null?void 0:K.getElementById(`preview-content-${G}`);if(!Ze)return null;let wt=Gm(Ze,be.config),dt=V.contentDocument.createElement("div");dt.id=G,dt.style.height="100%",dt.style.display="flex",dt.style.flexDirection="column",dt.style.flex="1",dt.style.minHeight="0",wt.host.appendChild(dt);let Ye=()=>wt.syncWidgetState(Xe.getState()),He=X;return X=()=>{wt.destroy(),He()},dt.__syncDock=Ye,dt.__hostLayout=wt,dt})():V.contentDocument.getElementById(G);if(!Ee)continue;let Xe=qm(Ee,be.config);if(r.push(Xe),le&&Ee.__syncDock){let Ze=Ee.__syncDock,wt=Xe.on("widget:opened",Ze),dt=Xe.on("widget:closed",Ze),Ye=X;X=()=>{wt(),dt(),Ye()},Ze()}o.push(X),C&&Xe.close()}if(((oe=n.scene)!=null?oe:"conversation")==="artifact"||($e=(de=(se=n.config)==null?void 0:se.features)==null?void 0:de.artifacts)!=null&&$e.enabled)for(let V of r)V.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
198
198
 
199
199
  This is a preview of the artifact sidebar.
200
200
 
@@ -202,4 +202,4 @@ This is a preview of the artifact sidebar.
202
202
 
203
203
  - Markdown rendering
204
204
  - Document toolbar
205
- - Resizable panes`});(re=t.onAfterMount)==null||re.call(t,{iframes:j,controllers:[...r]})};for(let be of j){let ne=be.dataset.mountId;if(!ne)continue;let Q=N.find(ae=>ae.mountId===ne);Q&&(be.addEventListener("load",()=>{te++,te>=We&&$e()},{once:!0}),be.srcdoc=D(ne,Q.shellMode,mn(Q.config),I))}We===0&&$e()}function T(){var k;if(a)return;let M=Vm(t);if(r.length!==M.length){P();return}if(M.some(W=>{let C=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!C||C.dataset.shellMode!==W.shellMode})){P();return}r.forEach((W,C)=>{var I;W.update(M[C].config),((I=t.scene)!=null?I:"conversation")==="minimized"&&W.close()});for(let W of M){let C=n.querySelector(`iframe[data-mount-id="${W.mountId}"]`);C&&zm(C,W.shellMode)}(k=t.onAfterUpdate)==null||k.call(t,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(n)),P(),{update(M){if(a)return;let N=M.device!==void 0&&M.device!==t.device||M.scene!==void 0&&M.scene!==t.scene||M.compareMode!==void 0&&M.compareMode!==t.compareMode||M.widgetCssPath!==void 0&&M.widgetCssPath!==t.widgetCssPath;t={...t,...M},N?P():T()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},u())},getIframes(){return x()},getScale(){return d},setZoom(M){a||(t={...t,zoom:M},u())}}}export{Ov as createThemePreview};
205
+ - Resizable panes`});(Ne=n.onAfterMount)==null||Ne.call(n,{iframes:N,controllers:[...r]})};for(let ue of N){let oe=ue.dataset.mountId;if(!oe)continue;let se=k.find(de=>de.mountId===oe);se&&(ue.addEventListener("load",()=>{Z++,Z>=Se&&pe()},{once:!0}),ue.srcdoc=F(oe,se.shellMode,yn(se.config),L))}Se===0&&pe()}function W(){var E;if(a)return;let T=eg(n);if(r.length!==T.length){M();return}if(T.some(P=>{let C=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!C||C.dataset.shellMode!==P.shellMode})){M();return}r.forEach((P,C)=>{var L;P.update(T[C].config),((L=n.scene)!=null?L:"conversation")==="minimized"&&P.close()});for(let P of T){let C=t.querySelector(`iframe[data-mount-id="${P.mountId}"]`);C&&Ym(C,P.shellMode)}(E=n.onAfterUpdate)==null||E.call(n,{iframes:v(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(t)),M(),{update(T){if(a)return;let k=T.device!==void 0&&T.device!==n.device||T.scene!==void 0&&T.scene!==n.scene||T.compareMode!==void 0&&T.compareMode!==n.compareMode||T.widgetCssPath!==void 0&&T.widgetCssPath!==n.widgetCssPath;n={...n,...T},k?M():W()},destroy(){a||(a=!0,x(),s==null||s.disconnect(),t.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return v()},getScale(){return d},setZoom(T){a||(n={...n,zoom:T},m())}}}export{ex as createThemePreview};