@runtypelabs/persona 3.35.0 → 3.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,20 @@
1
- var rg=Object.defineProperty;var Us=(n,e)=>()=>(n&&(e=n(n=0)),e);var Op=(n,e)=>{for(var t in e)rg(n,t,{get:e[t],enumerable:!0})};var _p={};Op(_p,{DOMPurify:()=>sg,Marked:()=>og});import{Marked as og}from"marked";import sg from"dompurify";var $p=Us(()=>{"use strict"});var ms,ji=Us(()=>{"use strict";ms=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 gf(n){return n.replace(/\/+$/,"")}async function ff(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 Xa,Su=Us(()=>{"use strict";ji();Xa=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 ms(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 u;e===this.generation&&((u=r.onStart)==null||u.call(r))}),d.onFinished(()=>{var u;e===this.generation&&((u=r.onEnd)==null||u.call(r))});let c=`${gf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,g=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(!g.ok||!g.body)throw new Error(await ff(g));let f=g.body.getReader();for(;;){let{done:u,value:m}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(u)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 Ja,Tu=Us(()=>{"use strict";Ja=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 Mu={};Op(Mu,{FallbackSpeechEngine:()=>Ja,RuntypeSpeechEngine:()=>Xa});var Eu=Us(()=>{"use strict";Su();Tu()});var Up=null,qs=null,as=null;var qp=()=>qs?Promise.resolve(qs):as||(Up?(as=Up().then(n=>(qs=n,n)),as):(as=Promise.resolve().then(()=>($p(),_p)).then(n=>(qs=n,n)),as)),is=()=>qs;var ag=n=>{if(n)return n},Pi=n=>{let e=null;return t=>{var o,s;let r=is();if(!r)return fo(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=ag(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},Ha=n=>n?Pi({markedOptions:n.options,renderer:n.renderer}):Pi(),Dv=Pi();var fo=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var ig={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"]},lg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,cg=()=>{let n=null;return e=>{let t=is();if(!t)return fo(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:")&&!lg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,ig)}},Ba=n=>n===!1?null:typeof n=="function"?n:cg();var Bo="webmcp:",Ii=new Map,zp=n=>{var e;Ii.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&Ii.set(t.name,r)}},Wi=n=>Ii.get(Gp(n)),Da={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},Vp=null;function Kp(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}:${dg(e.join(""))}`}function jp(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 dg(n){let e=jp(n,0).toString(36),t=jp(n,2654435761).toString(36);return`${e}.${t}`}var Na=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 Da.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}zp(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=ug(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return br("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return br(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=Gp(e),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return br(`Failed to read WebMCP registry: ${x}`)}zp(a);let i=a.find(v=>v.name===s);if(!i)return br(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return br(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let d=Wi(s),c={toolName:s,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return br("User declined the tool call.");if(r!=null&&r.aborted)return br("Aborted by cancel()");let g=new AbortController,f=!1,u=setTimeout(()=>{f=!0,g.abort()},this.timeoutMs),m=()=>g.abort();r&&(r.aborted?g.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,hg(t),{signal:g.signal});return mg(v)}catch(v){if(f)return br(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return br(x)}finally{clearTimeout(u),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}(Vp?await Vp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Da.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,Da.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:gg;try{return await t(e)}catch(o){return Da.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=>pg(e,r))}},Gp=n=>n.startsWith(Bo)?n.slice(Bo.length):n,zs=n=>n.startsWith(Bo),pg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},ug=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},mg=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:yg(e)}]}},br=n=>({isError:!0,content:[{type:"text",text:n}]}),gg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=fg(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
1
+ var lg=Object.defineProperty;var $s=(n,t)=>()=>(n&&(t=n(n=0)),t);var $p=(n,t)=>{for(var e in t)lg(n,e,{get:t[e],enumerable:!0})};var qp={};$p(qp,{DOMPurify:()=>dg,Marked:()=>cg});import{Marked as cg}from"marked";import dg from"dompurify";var Up=$s(()=>{"use strict"});var us,Qi=$s(()=>{"use strict";us=class{constructor(t=24e3,e={}){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=t;let r=Math.max(0,(o=e.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let e=typeof window!="undefined"?window:void 0;if(!e)throw new Error("AudioPlaybackManager requires a browser environment");let r=e.AudioContext||e.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let e=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),e=o,this.remainder=null}if(e.length%2!==0&&(this.remainder=new Uint8Array([e[e.length-1]]),e=e.subarray(0,e.length-1)),e.length===0)return;let r=this.pcmToFloat32(e);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 t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let e of t)this.scheduleSamples(e)}scheduleSamples(t){if(t.length===0)return;let e=this.ensureContext(),r=e.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=e.createBufferSource();o.buffer=r,o.connect(e.destination);let s=e.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 t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let e of t)e()}}pcmToFloat32(t){let e=Math.floor(t.length/2),r=new Float32Array(e),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<e;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function xf(n){return n.replace(/\/+$/,"")}async function wf(n){var t,e;try{let r=await n.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${n.status}`}: ${r.detail}`:(e=r.error)!=null?e:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var Za,Lu=$s(()=>{"use strict";Qi();Za=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,e;return(e=this.playerPromise)!=null?e:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new us(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,e){let r=++this.generation;this.run(r,t,e)}async run(t,e,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var u;t===this.generation&&((u=r.onStart)==null||u.call(r))}),d.onFinished(()=>{var u;t===this.generation&&((u=r.onEnd)==null||u.call(r))});let c=`${xf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,g=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:e.text,voice:(o=e.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!g.ok||!g.body)throw new Error(await wf(g));let f=g.body.getReader();for(;;){let{done:u,value:m}=await f.read();if(t!==this.generation){await f.cancel().catch(()=>{});return}if(u)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(t!==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 t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var ei,Iu=$s(()=>{"use strict";ei=class{constructor(t,e,r={}){this.primary=t;this.fallback=e;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,e){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=e.onStart)==null||o.call(e)},onEnd:()=>{var o;return(o=e.onEnd)==null?void 0:o.call(e)},onError:o=>{var s,a,i;if(r){(s=e.onError)==null||s.call(e,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,e)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,e,r,o;(e=(t=this.primary).destroy)==null||e.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Pu={};$p(Pu,{FallbackSpeechEngine:()=>ei,RuntypeSpeechEngine:()=>Za});var Wu=$s(()=>{"use strict";Lu();Iu()});var zp=null,qs=null,ss=null;var jp=()=>qs?Promise.resolve(qs):ss||(zp?(ss=zp().then(n=>(qs=n,n)),ss):(ss=Promise.resolve().then(()=>(Up(),qp)).then(n=>(qs=n,n)),ss)),as=()=>qs;var pg=n=>{if(n)return n},Ri=n=>{let t=null;return e=>{var o,s;let r=as();if(!r)return fo(e);if(!t){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;t=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=pg(n==null?void 0:n.renderer);d&&t.use({renderer:d})}return t.parse(e)}},Da=n=>n?Ri({markedOptions:n.options,renderer:n.renderer}):Ri(),qv=Ri();var fo=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var ug={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"]},mg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,gg=()=>{let n=null;return t=>{let e=as();if(!e)return fo(t);if(!n){let{DOMPurify:r}=e;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:")&&!mg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(t,ug)}},Na=n=>n===!1?null:typeof n=="function"?n:gg();var Ho="webmcp:",Bi=new Map,Vp=n=>{var t;Bi.clear();for(let e of n){let r=(t=e.title)==null?void 0:t.trim();r&&Bi.set(e.name,r)}},Hi=n=>Bi.get(Xp(n)),Fa={warn(n,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...t)}},Kp=null;function Qp(n){if(n.length===0)return"0:empty";let t=n.map(e=>{var r,o;return[e.name,(r=e.description)!=null?r:"",e.parametersSchema?JSON.stringify(e.parametersSchema):"",(o=e.origin)!=null?o:"",e.annotations?JSON.stringify(e.annotations):""].join("")}).sort();return`${n.length}:${fg(t.join(""))}`}function Gp(n,t){let e=3735928559^t,r=1103547991^t;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);e=Math.imul(e^s,2654435761),r=Math.imul(r^s,1597334677)}return e=Math.imul(e^e>>>16,2246822507),e^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(e^e>>>13,3266489909),4294967296*(2097151&r)+(e>>>0)}function fg(n){let t=Gp(n,0).toString(36),e=Gp(n,2654435761).toString(36);return`${t}.${e}`}var _a=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var e;this.confirmHandler=(e=t.onConfirm)!=null?e:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let e;try{e=await t.getTools()}catch(o){return Fa.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Vp(e);let r=typeof location!="undefined"?location.origin:"";return e.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=bg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,e,r){if(await this.ensureReady(),this.config.enabled!==!0)return br("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return br(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=Xp(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return br(`Failed to read WebMCP registry: ${x}`)}Vp(a);let i=a.find(v=>v.name===s);if(!i)return br(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return br(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let d=Hi(s),c={toolName:s,args:e,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return br("User declined the tool call.");if(r!=null&&r.aborted)return br("Aborted by cancel()");let g=new AbortController,f=!1,u=setTimeout(()=>{f=!0,g.abort()},this.timeoutMs),m=()=>g.abort();r&&(r.aborted?g.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,wg(e),{signal:g.signal});return yg(v)}catch(v){if(f)return br(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return br("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return br(x)}finally{clearTimeout(u),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}(Kp?await Kp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Fa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let e=t;return typeof e.getTools!="function"||typeof e.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Fa.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let e=(r=this.confirmHandler)!=null?r:vg;try{return await e(t)}catch(o){return Fa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let e=this.config.allowlist;return!e||e.length===0?!0:e.some(r=>hg(t,r))}},Xp=n=>n.startsWith(Ho)?n.slice(Ho.length):n,Us=n=>n.startsWith(Ho),hg=(n,t)=>{if(t==="*")return!0;let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+e.replace(/\*/g,".*")+"$").test(n)},bg=n=>{if(!(n===void 0||n===""))try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:void 0}catch{return}},yg=n=>{if(n==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Cg(t)}]}},br=n=>({isError:!0,content:[{type:"text",text:n}]}),vg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=xg(n.args),e=`Allow the AI to call ${n.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
- ${e}`:"")+(n.description?`
4
+ ${t}`:"")+(n.description?`
5
5
 
6
- ${n.description}`:"");return window.confirm(t)},fg=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)}},hg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},yg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};import{parse as bg,ARR as vg,OBJ as xg,STR as wg}from"partial-json";var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Dr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var kt=(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},Vs=(...n)=>n.filter(Boolean).join(" ");var Ri="ask_user_question",js=8,ls="data-persona-ask-sheet-for",Cg="Other",Ag="Other\u2026",Xp="Type your own answer here",Jp="Send",Sg="Next",Tg="Back",Mg="Submit all",Eg="Skip",kg=3,Hi="data-ask-current-index",Bi="data-ask-question-count",Yp="data-ask-answers",Di="data-ask-grouped",Zp="data-ask-layout",Lg=n=>n.layout==="pills"?"pills":"rows",Pg=n=>n.getAttribute(Zp)==="pills"?"pills":"rows",Qp=!1,eu=n=>n.replace(/["\\]/g,"\\$&"),Do=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Ri,Ni=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},cs=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=bg(o,wg|xg|vg);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>js&&!Qp&&(Qp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${js}.`)),e.slice(0,js)},Ig=n=>{var e;return(e=Ks(n)[0])!=null?e:null},Wg=(n,e)=>{var t;return(t=Ks(n)[e])!=null?t:null},Rg=(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))},tu=(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},Hg=(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=tu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Bg=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},Dg=(n,e,t,r)=>{var g,f,u;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(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<kg;m++)s.appendChild(Bg(r));return s}if(d.forEach((m,v)=>{s.appendChild(Hg(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Cg:Ag;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"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(g=e.freeTextPlaceholder)!=null?g:Xp,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),x.appendChild(M),v.appendChild(x);let E=tu(r,a,d.length);E&&v.appendChild(E),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=(u=e.freeTextLabel)!=null?u:m,s.appendChild(v)}}return s},nu=(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:Xp,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},Ng=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},Fg=(n,e,t)=>{var c,g,f,u;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:Tg,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=(g=t.skipLabel)!=null?g:Eg,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:Mg:(u=t.nextLabel)!=null?u:Sg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},No=n=>{let e=n.getAttribute(Yp);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},ru=(n,e)=>{n.setAttribute(Yp,JSON.stringify(e))},dr=n=>{var t;let e=Number((t=n.getAttribute(Hi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Og=(n,e)=>{n.setAttribute(Hi,String(Math.max(0,Math.floor(e))))},ds=n=>{var t;let e=Number((t=n.getAttribute(Bi))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ho=n=>n.getAttribute(Di)==="true",_g=(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},$g=(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)))},Fa=(n,e)=>{let{payload:t}=cs(e),r=Ks(t),o=No(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},ou=n=>{let e=No(n),t=dr(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:"",g=o.has(c);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});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=""},su=n=>{if(!ho(n))return;let e=No(n),t=dr(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}},Fi=(n,e,t)=>{let r=Ni(t),o=Pg(n),{payload:s,complete:a}=cs(e),i=ho(n),d=dr(n),c=ds(n),g=i?Wg(s,d):Ig(s),f=!!(g!=null&&g.multiSelect),u=n.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let k=typeof(g==null?void 0:g.question)=="string"?g.question:"";v.textContent=k,v.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let k=Dg(g,r,a,o);x.replaceWith(k)}if(o!=="rows"){let k=n.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(nu(r,o))}let M=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!M?n.appendChild(Ng(r)):(!f||i)&&M&&M.remove(),n.setAttribute("data-multi-select",f?"true":"false");let E=n.querySelector('[data-ask-nav-row="true"]');if(i){let k=Fg(d,c,r);E?E.replaceWith(k):n.appendChild(k)}else E&&E.remove();ou(n),su(n)},Ug=(n,e,t)=>{let r=Ni(e),o=Lg(r),s=n.toolCall.id,a=Ks(t),i=Math.max(1,a.length),d=i>1,c=_g(n,a),g=d?$g(n,i):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ls,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(Bi,String(i)),f.setAttribute(Hi,String(g)),f.setAttribute(Di,d?"true":"false"),f.setAttribute(Zp,o),ru(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`),Rg(f,r);let u=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",u.appendChild(v),f.appendChild(u);let M=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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),f.appendChild(M),o!=="rows"&&f.appendChild(nu(r,o)),Fi(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},qg=(n,e,t)=>{let{payload:r}=cs(e),o=Math.max(1,Ks(r).length);o>ds(n)&&(n.setAttribute(Bi,String(o)),o>1&&!ho(n)&&n.setAttribute(Di,"true")),Fi(n,e,t)};var Oa=(n,e,t)=>{if(!t||!Do(n)||Ni(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${ls}]`).forEach(c=>{c.getAttribute(ls)!==o&&c.remove()});let a=t.querySelector(`[${ls}="${eu(o)}"]`);if(a){qg(a,n,e);return}let{payload:i}=cs(n),d=Ug(n,e,i);t.appendChild(d)},ps=(n,e)=>{if(!n)return;let t=e?`[${ls}="${eu(e)}"]`:`[${ls}]`;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)})},Oi=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),yo=(n,e)=>{let t=No(n),r=dr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,ru(n,t),ou(n),su(n)},_a=(n,e,t,r)=>{let o=ds(n),s=Math.max(0,Math.min(o-1,r));Og(n,s),Fi(n,e,t)};var Kr="suggest_replies";var zg={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},au={name:Kr,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:zg,origin:"sdk",annotations:{readOnlyHint:!0}},_i=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),$i=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===Kr},Vg=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},iu=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!$i(r))continue;let o=Vg((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},lu=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 jg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:js,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},Kg={name:Ri,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:jg,origin:"sdk",annotations:{readOnlyHint:!0}},Ui=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(Kg),lu(n)&&e.push(au),e};import{parse as Gg,STR as Qg,OBJ as Xg}from"partial-json";var cu=n=>n.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),us=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)}},Jg=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`},du=n=>n.status==="complete"?Jg(n):n.status==="pending"?"Waiting":"",Yg=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 pu=n=>n.status==="complete"?Yg(n):"Using tool...",$a=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Qs=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 $a(e)},Ua=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 $a(e)},qi=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Qs(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},qa=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Gs(r,t.slice(s,a.index),[]),a[1]!==void 0?Gs(r,a[1],["bold"]):a[2]!==void 0?Gs(r,a[2],["italic"]):a[3]!==void 0&&Gs(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Gs(r,t.slice(s),[]),r},Gs=(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})},Zg=()=>{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,`
6
+ ${n.description}`:"");return window.confirm(e)},xg=n=>{if(n==null)return"";try{let t=JSON.stringify(n,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(n)}},wg=n=>{if(n===void 0)return"{}";try{let t=JSON.stringify(n);return t===void 0?"{}":t}catch{return"{}"}},Cg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};import{parse as Ag,ARR as Sg,OBJ as Tg,STR as Eg}from"partial-json";var y=(n,t)=>{let e=document.createElement(n);return t&&(e.className=t),e},Hr=(n,t,e)=>{let r=n.createElement(t);return e&&(r.className=e),r};var Lt=(n,t={},...e)=>{let r=document.createElement(n);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=e.filter(s=>s!=null);return o.length>0&&r.append(...o),r},zs=(...n)=>n.filter(Boolean).join(" ");var Di="ask_user_question",js=8,is="data-persona-ask-sheet-for",Mg="Other",kg="Other\u2026",Yp="Type your own answer here",Zp="Send",Lg="Next",Ig="Back",Pg="Submit all",Wg="Skip",Rg=3,Ni="data-ask-current-index",Fi="data-ask-question-count",eu="data-ask-answers",_i="data-ask-grouped",tu="data-ask-layout",Bg=n=>n.layout==="pills"?"pills":"rows",Hg=n=>n.getAttribute(tu)==="pills"?"pills":"rows",Jp=!1,nu=n=>n.replace(/["\\]/g,"\\$&"),Do=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Di,Oi=n=>{var t,e;return(e=(t=n==null?void 0:n.features)==null?void 0:t.askUserQuestion)!=null?e:{}},ls=n=>{let t=n.toolCall;if(!t)return{payload:null,complete:!1};let e=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:e};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:e};try{let o=r.join(""),s=Ag(o,Eg|Tg|Sg);if(s&&typeof s=="object")return{payload:s,complete:e}}catch{}return{payload:null,complete:e}},Vs=n=>{let t=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return t.length>js&&!Jp&&(Jp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${js}.`)),t.slice(0,js)},Dg=n=>{var t;return(t=Vs(n)[0])!=null?t:null},Ng=(n,t)=>{var e;return(e=Vs(n)[t])!=null?e:null},Fg=(n,t)=>{let e=t.styles;e&&(e.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",e.sheetBackground),e.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",e.sheetBorder),e.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",e.sheetShadow),e.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",e.pillBackground),e.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",e.pillBackgroundSelected),e.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",e.pillTextColor),e.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",e.pillTextColorSelected),e.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",e.pillBorderRadius),e.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",e.customInputBackground))},ru=(n,t,e)=>{if(n!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(e+1),r.appendChild(o)}return r},_g=(n,t,e,r)=>{let s=y("button",e==="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(t)),s.setAttribute("data-option-label",n.label),e==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=y("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=ru(e,r,t);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Og=n=>{let e=y("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 e.setAttribute("aria-hidden","true"),e},$g=(n,t,e,r)=>{var g,f,u;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=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!e){for(let m=0;m<Rg;m++)s.appendChild(Og(r));return s}if(d.forEach((m,v)=>{s.appendChild(_g(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Mg:kg;if(r==="rows"){let v=y("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=y("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(g=t.freeTextPlaceholder)!=null?g:Yp,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:m),x.appendChild(T),v.appendChild(x);let E=ru(r,a,d.length);E&&v.appendChild(E),s.appendChild(v)}else{let v=y("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=(u=t.freeTextLabel)!=null?u:m,s.appendChild(v)}}return s},ou=(n,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");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:Yp,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:Zp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},qg=n=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let e=y("button","persona-ask-multi-submit persona-pointer-events-auto");return e.type="button",e.textContent=(r=n.submitLabel)!=null?r:Zp,e.setAttribute("data-ask-user-action","submit-multi"),e.disabled=!0,t.appendChild(e),t},Ug=(n,t,e)=>{var c,g,f,u;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=e.backLabel)!=null?c:Ig,o.setAttribute("data-ask-user-action","back"),o.disabled=n===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=(g=e.skipLabel)!=null?g:Wg,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=n===t-1;return i.textContent=d?(f=e.submitAllLabel)!=null?f:Pg:(u=e.nextLabel)!=null?u:Lg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},No=n=>{let t=n.getAttribute(eu);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}},su=(n,t)=>{n.setAttribute(eu,JSON.stringify(t))},cr=n=>{var e;let t=Number((e=n.getAttribute(Ni))!=null?e:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},zg=(n,t)=>{n.setAttribute(Ni,String(Math.max(0,Math.floor(t))))},cs=n=>{var e;let t=Number((e=n.getAttribute(Fi))!=null?e:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ho=n=>n.getAttribute(_i)==="true",jg=(n,t)=>{var o;let e=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!e||typeof e!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(e,i)){let d=e[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Vg=(n,t)=>{var r;let e=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(t-1,Math.floor(e)))},Oa=(n,t)=>{let{payload:e}=ls(t),r=Vs(e),o=No(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},au=n=>{let t=No(n),e=cr(n),r=t[e],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:"",g=o.has(c);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});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=""},iu=n=>{if(!ho(n))return;let t=No(n),e=cr(n),r=t[e],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}},$i=(n,t,e)=>{let r=Oi(e),o=Hg(n),{payload:s,complete:a}=ls(t),i=ho(n),d=cr(n),c=cs(n),g=i?Ng(s,d):Dg(s),f=!!(g!=null&&g.multiSelect),u=n.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let A=typeof(g==null?void 0:g.question)=="string"?g.question:"";v.textContent=A,v.classList.toggle("persona-ask-question-skeleton",!A&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let A=$g(g,r,a,o);x.replaceWith(A)}if(o!=="rows"){let A=n.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(ou(r,o))}let T=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!T?n.appendChild(qg(r)):(!f||i)&&T&&T.remove(),n.setAttribute("data-multi-select",f?"true":"false");let E=n.querySelector('[data-ask-nav-row="true"]');if(i){let A=Ug(d,c,r);E?E.replaceWith(A):n.appendChild(A)}else E&&E.remove();au(n),iu(n)},Kg=(n,t,e)=>{let r=Oi(t),o=Bg(r),s=n.toolCall.id,a=Vs(e),i=Math.max(1,a.length),d=i>1,c=jg(n,a),g=d?Vg(n,i):0,f=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(is,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(Fi,String(i)),f.setAttribute(Ni,String(g)),f.setAttribute(_i,d?"true":"false"),f.setAttribute(tu,o),su(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`),Fg(f,r);let u=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="",u.appendChild(m);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",u.appendChild(v),f.appendChild(u);let T=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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),o!=="rows"&&f.appendChild(ou(r,o)),$i(f,n,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Gg=(n,t,e)=>{let{payload:r}=ls(t),o=Math.max(1,Vs(r).length);o>cs(n)&&(n.setAttribute(Fi,String(o)),o>1&&!ho(n)&&n.setAttribute(_i,"true")),$i(n,t,e)};var $a=(n,t,e)=>{if(!e||!Do(n)||Oi(t).enabled===!1)return;let o=n.toolCall.id;e.querySelectorAll(`[${is}]`).forEach(c=>{c.getAttribute(is)!==o&&c.remove()});let a=e.querySelector(`[${is}="${nu(o)}"]`);if(a){Gg(a,n,t);return}let{payload:i}=ls(n),d=Kg(n,t,i);e.appendChild(d)},ds=(n,t)=>{if(!n)return;let e=t?`[${is}="${nu(t)}"]`:`[${is}]`;n.querySelectorAll(e).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)})},qi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),bo=(n,t)=>{let e=No(n),r=cr(n);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete e[r]:e[r]=t,su(n,e),au(n),iu(n)},qa=(n,t,e,r)=>{let o=cs(n),s=Math.max(0,Math.min(o-1,r));zg(n,s),$i(n,t,e)};var Kr="suggest_replies";var Qg={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},lu={name:Kr,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:Qg,origin:"sdk",annotations:{readOnlyHint:!0}},Ui=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),zi=n=>{var t;return n.variant==="tool"&&((t=n.toolCall)==null?void 0:t.name)===Kr},Xg=n=>{let t=n;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let e=t==null?void 0:t.suggestions;if(!Array.isArray(e))return[];let r=e.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},cu=n=>{var t;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.role==="user")return null;if(!zi(r))continue;let o=Xg((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},du=n=>{var e;let t=(e=n==null?void 0:n.features)==null?void 0:e.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Jg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:js,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},Yg={name:Di,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:Jg,origin:"sdk",annotations:{readOnlyHint:!0}},ji=n=>{var r;let t=[],e=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1&&t.push(Yg),du(n)&&t.push(lu),t};import{parse as Zg,STR as ef,OBJ as tf}from"partial-json";var pu=n=>n.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ps=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)}},nf=n=>{var a,i;let t=(a=n.completedAt)!=null?a:Date.now(),e=(i=n.startedAt)!=null?i:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-e))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},uu=n=>n.status==="complete"?nf(n):n.status==="pending"?"Waiting":"",rf=n=>{var o,s,a;let e=(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 e<.1?"Used tool for <0.1 seconds":`Used tool for ${e>=10?Math.round(e).toString():e.toFixed(1).replace(/\.0$/,"")} seconds`};var mu=n=>n.status==="complete"?rf(n):"Using tool...",Ua=n=>{let t=n/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Gs=n=>{var e,r,o;let t=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((e=n.completedAt)!=null?e:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ua(t)},za=n=>{var e,r,o;let t=n.durationMs!==void 0?n.durationMs:Math.max(0,((e=n.completedAt)!=null?e:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ua(t)},Vi=(n,t,e)=>{var s;if(!t)return e;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Gs(n);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},ja=(n,t)=>{let e=n.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(e))!==null;)a.index>s&&Ks(r,e.slice(s,a.index),[]),a[1]!==void 0?Ks(r,a[1],["bold"]):a[2]!==void 0?Ks(r,a[2],["italic"]):a[3]!==void 0&&Ks(r,a[3],["dim"]),s=a.index+a[0].length;return s<e.length&&Ks(r,e.slice(s),[]),r},Ks=(n,t,e)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:e}),o<r.length-1&&n.push({text:"{duration}",styles:e,isDuration:!0})},of=()=>{let n=null,t=0,e=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
8
  `).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,`
9
- `).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()=>{}}},Fo=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},uu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},mu=()=>{var e;let n=Zg();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)}},gu=()=>{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=Gg(t,Qg|Xg);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?cu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=cu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var fu=()=>{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 za=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var s,a,i;let r=(i=(s=t==null?void 0:t.seq)!=null?s:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(e,t);return}let o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(r,{payloadType:e,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of e)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var ef="https://api.runtype.com/v1/dispatch",Va="https://api.runtype.com";function tf(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 zi=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 nf(n){switch(n){case"json":return gu;case"regex-json":return mu;case"xml":return fu;default:return uu}}var hu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function rf(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=hu(t);if(!hu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Fo(n);return Fo(e)!==null&&a===null?e:n}var Xs=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:ef,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:nf(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 Na(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$/,""))||Va}/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"},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$/,""))||Va}/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"},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 P=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:P}),P}let c=await this.buildPayload(e.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(zi).map(P=>{var W,C,I;return{id:P.id,role:P.role,content:(I=(C=(W=P.contentParts)!=null?W:P.llmContent)!=null?C:P.rawContent)!=null?I:P.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},u=c.clientTools,m=!!(u&&u.length>0),v=m?Kp(u):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&x&&this.lastSentClientToolsFingerprint===v,E=!1,k=null,N;for(let P=0;;P++){let C={...f,...m&&(E||!M)&&u?{clientTools:u}:{},...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"},body:JSON.stringify(C),signal:r.signal}),N.status===409&&P===0&&m){let I=await N.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}k=I!=null?I:{error:"Chat request failed"}}break}if(!N.ok){let P=k!=null?k: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(P.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let W=new Error(P.error||"Failed to send message");throw t({type:"error",error:W}),W}if(!N.body){let P=new Error("No response body received");throw t({type:"error",error:P}),P}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$/,""))||Va}/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,g;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Va}/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:(g=r==null?void 0:r.streamResponse)!=null?g:!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(zi).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(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ui(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(zi).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ui(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=g=>{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(),...g!==void 0&&{partId:g}};return r.current=f,o(f),f},c=g=>r.current?r.current:d(g);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 g=c(i.partId);i.partId!==void 0&&!g.partId&&(g.partId=i.partId),g.content+=i.text,o(g)}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 bn,Wt,dn,wr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=$=>{let K=$.reasoning?{...$.reasoning,chunks:[...$.reasoning.chunks]}:void 0,he=$.toolCall?{...$.toolCall,chunks:$.toolCall.chunks?[...$.toolCall.chunks]:void 0}:void 0,Ge=$.tools?$.tools.map(Ze=>({...Ze,chunks:Ze.chunks?[...Ze.chunks]:void 0})):void 0;return{...$,reasoning:K,toolCall:he,tools:Ge}},f=$=>{if($.role!=="assistant"||$.variant)return!0;let K=Array.isArray($.contentParts)&&$.contentParts.length>0,he=typeof $.rawContent=="string"&&$.rawContent.trim()!=="";return typeof $.content=="string"&&$.content.trim()!==""||K||he||!!$.stopReason},u=$=>{f($)&&t({type:"message",message:g($)})},m=null,v=null,x={current:null},M={current:null},E=!1,k=new Map,N=new Map,P=new Map,W=new Map,C={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},B=($,K,he="")=>`${$}::${K}::${he}`,D=($,K)=>`${$}::${K}::`,T=($,K,he,Ge)=>{let Ze=B($,K,he),$e=P.get(Ze);if($e)return $e;let Oe=he?`-${he}`:"",Lt={id:`nested-${$}-${K}${Oe}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...he?{partId:he}:{},agentMetadata:{executionId:Ge,parentToolId:$,parentStepId:K}};return P.set(Ze,Lt),u(Lt),Lt},q=$=>{if($==null)return null;try{return String($)}catch{return null}},z=$=>{var K,he,Ge,Ze,$e;return q(($e=(Ze=(Ge=(he=(K=$.stepId)!=null?K:$.step_id)!=null?he:$.step)!=null?Ge:$.parentId)!=null?Ze:$.flowStepId)!=null?$e:$.flow_step_id)},re=$=>{var K,he,Ge,Ze,$e,Oe,Lt;return q((Lt=(Oe=($e=(Ze=(Ge=(he=(K=$.callId)!=null?K:$.call_id)!=null?he:$.requestId)!=null?Ge:$.request_id)!=null?Ze:$.toolCallId)!=null?$e:$.tool_call_id)!=null?Oe:$.stepId)!=null?Lt:$.step_id)},ke=r,Ve=!1,be=()=>{if(m)return m;let $;return!Ve&&ke?($=ke,Ve=!0):ke&&M.current?$=`${ke}_${M.current}`:$=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:$,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(m),m},He=($,K)=>{C.lastId=K,$&&C.byStep.set($,K)},Fe=($,K)=>{var $e;let he=($e=$.reasoningId)!=null?$e:$.id,Ge=z($);if(he){let Oe=String(he);return He(Ge,Oe),Oe}if(Ge){let Oe=C.byStep.get(Ge);if(Oe)return C.lastId=Oe,Oe}if(C.lastId&&!K)return C.lastId;if(!K)return null;let Ze=`reason-${c()}`;return He(Ge,Ze),Ze},Se=$=>{let K=k.get($);if(K)return K;let he={id:`reason-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"streaming",chunks:[]}};return k.set($,he),u(he),he},xe=($,K)=>{I.lastId=K,$&&I.byCall.set($,K)},oe=new Set,G=new Map,se=new Set,ge=new Map,pe=$=>{if(!$)return!1;let K=$.replace(/_+/g,"_").replace(/^_|_$/g,"");return K==="emit_artifact_markdown"||K==="emit_artifact_component"},j=($,K)=>{var $e;let he=($e=$.toolId)!=null?$e:$.id,Ge=re($);if(he){let Oe=String(he);return xe(Ge,Oe),Oe}if(Ge){let Oe=I.byCall.get(Ge);if(Oe)return I.lastId=Oe,Oe}if(I.lastId&&!K)return I.lastId;if(!K)return null;let Ze=`tool-${c()}`;return xe(Ge,Ze),Ze},ae=$=>{let K=N.get($);if(K)return K;let he={id:`tool-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:$,status:"pending"}};return N.set($,he),u(he),he},Ie=$=>{if(typeof $=="number"&&Number.isFinite($))return $;if(typeof $=="string"){let K=Number($);if(!Number.isNaN(K)&&Number.isFinite(K))return K;let he=Date.parse($);if(!Number.isNaN(he))return he}return Date.now()},ee=$=>{if(typeof $=="string")return $;if($==null)return"";try{return JSON.stringify($)}catch{return String($)}},Z=new Map,ne=new Map,at=new Map,it=new Map,ot=null,Me=($,K,he)=>{var Lt;let Ge=at.get($);Ge||(Ge=[],at.set($,Ge));let Ze=0,$e=Ge.length;for(;Ze<$e;){let jt=Ze+$e>>>1;Ge[jt].seq<K?Ze=jt+1:$e=jt}((Lt=Ge[Ze])==null?void 0:Lt.seq)===K?Ge[Ze]={seq:K,text:he}:Ge.splice(Ze,0,{seq:K,text:he});let Oe="";for(let jt=0;jt<Ge.length;jt++)Oe+=Ge[jt].text;return Oe},fe=($,K)=>{let he=ee(K),Ge=ne.get($.id),Ze=rf(Ge,he);$.rawContent=Ze;let $e=Z.get($.id),Oe=V=>{var le;let Rt=(le=$.content)!=null?le:"";V.trim()!==""&&(Rt.trim().length===0||V.startsWith(Rt)||V.trimStart().startsWith(Rt.trim()))&&($.content=V)},Lt=()=>{var V;if($e){let Rt=(V=$e.close)==null?void 0:V.call($e);Rt instanceof Promise&&Rt.catch(()=>{})}Z.delete($.id),ne.delete($.id),$.streaming=!1,u($)};if(!$e){Oe(he),Lt();return}let jt=Fo(Ze);if(jt!==null&&jt.trim()!==""){Oe(jt),Lt();return}let Xt=V=>{var we;let Rt=typeof V=="string"?V:(we=V==null?void 0:V.text)!=null?we:null;if(Rt!==null&&Rt.trim()!=="")return Rt;let le=$e.getExtractedText();return le!==null&&le.trim()!==""?le:he},kn;try{kn=$e.processChunk(Ze)}catch{Oe(he),Lt();return}if(kn instanceof Promise){kn.then(V=>{Oe(Xt(V)),Lt()}).catch(()=>{Oe(he),Lt()});return}Oe(Xt(kn)),Lt()},Xe=[],J=!1,ue,Ee=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,ue()}))},Je=new za(($,K)=>{Xe.push({payloadType:$,payload:K}),Ee()}),Ke=null,Pe=new Map,je=(bn=this.config.iterationDisplay)!=null?bn:"separate";for(ue=()=>{var $,K,he,Ge,Ze,$e,Oe,Lt,jt,Xt,kn,V,Rt,le,we,Ne,St,rn,on,vn,Dt,nt,Bt,dt,Jt,tr,Ln,sn,Fn,Cr,vt,qn,Ar,Nr,ur,yt,xo,Sr,wo,On,Vo,Jr,Fr,Yr,Zr,Co,Ao,eo,wt,zn,Vn,Pn,Tt,nr,rr,jn,to,Or,no,Kn,Nt,In,or,ro,_r,oo,Tr,Gn,ye,pt,en,pn,Mr,Ss,$r,So,Er,O,jo,kr,Lr,Ur,Pr,mr,Ko,ya,Qn,Xn,gr,fr,To,qr,Cn,Ir,Go,Mo,Qo,ba,Xo,va,Jo,ht,Ts,sr,_n,xa,wa,Yo,zr,Ms,so,Es,ks,Ls,Ps,$n,Zo,Wr,Rr,Is,Ca,Ws,Rs,Eo,Aa,Sa,Ta,Ma,Ea,ao,io,ka,Hs,lo,La,Bs,co,Ds;for(let es=0;es<Xe.length;es++){let Ue=Xe[es].payloadType,w=Xe[es].payload;if(Ue==="reason_start"){let _=($=Fe(w,!0))!=null?$:`reason-${c()}`,S=Se(_);S.reasoning=(K=S.reasoning)!=null?K:{id:_,status:"streaming",chunks:[]},S.reasoning.startedAt=(Ge=S.reasoning.startedAt)!=null?Ge:Ie((he=w.startedAt)!=null?he:w.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",u(S)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let _=($e=(Ze=Fe(w,!1))!=null?Ze:Fe(w,!0))!=null?$e:`reason-${c()}`,S=Se(_);S.reasoning=(Oe=S.reasoning)!=null?Oe:{id:_,status:"streaming",chunks:[]},S.reasoning.startedAt=(jt=S.reasoning.startedAt)!=null?jt:Ie((Lt=w.startedAt)!=null?Lt:w.timestamp);let X=(V=(kn=(Xt=w.reasoningText)!=null?Xt:w.text)!=null?kn:w.delta)!=null?V:"";if(X&&w.hidden!==!0){let ie=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(ie!==void 0){let Q=Me(_,ie,String(X));S.reasoning.chunks=[Q]}else S.reasoning.chunks.push(String(X))}if(S.reasoning.status=w.done?"complete":"streaming",w.done){S.reasoning.completedAt=Ie((Rt=w.completedAt)!=null?Rt:w.timestamp);let ie=(le=S.reasoning.startedAt)!=null?le:Date.now();S.reasoning.durationMs=Math.max(0,((we=S.reasoning.completedAt)!=null?we:Date.now())-ie)}S.streaming=S.reasoning.status!=="complete",u(S)}else if(Ue==="reason_complete"){let _=(St=(Ne=Fe(w,!1))!=null?Ne:Fe(w,!0))!=null?St:`reason-${c()}`,S=k.get(_);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=Ie((rn=w.completedAt)!=null?rn:w.timestamp);let ie=(on=S.reasoning.startedAt)!=null?on:Date.now();S.reasoning.durationMs=Math.max(0,((vn=S.reasoning.completedAt)!=null?vn:Date.now())-ie),S.streaming=!1,u(S)}let X=z(w);X&&C.byStep.delete(X)}else if(Ue==="tool_start"){let _=(Dt=j(w,!0))!=null?Dt:`tool-${c()}`,S=(nt=w.toolName)!=null?nt:w.name;if(pe(S)){oe.add(_);continue}let X=ae(_),ie=(Bt=X.toolCall)!=null?Bt:{id:_,status:"pending"};ie.name=S!=null?S:ie.name,ie.status="running",w.args!==void 0?ie.args=w.args:w.parameters!==void 0&&(ie.args=w.parameters),ie.startedAt=(Jt=ie.startedAt)!=null?Jt:Ie((dt=w.startedAt)!=null?dt:w.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,X.toolCall=ie,X.streaming=!0;let Q=w.agentContext;(Q||w.executionId)&&(X.agentMetadata={executionId:(tr=Q==null?void 0:Q.executionId)!=null?tr:w.executionId,iteration:(Ln=Q==null?void 0:Q.iteration)!=null?Ln:w.iteration}),u(X)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let _=(Fn=(sn=j(w,!1))!=null?sn:j(w,!0))!=null?Fn:`tool-${c()}`;if(oe.has(_))continue;let S=ae(_),X=(Cr=S.toolCall)!=null?Cr:{id:_,status:"running"};X.startedAt=(qn=X.startedAt)!=null?qn:Ie((vt=w.startedAt)!=null?vt:w.timestamp);let ie=(ur=(Nr=(Ar=w.text)!=null?Ar:w.delta)!=null?Nr:w.message)!=null?ur:"";ie&&(X.chunks=(yt=X.chunks)!=null?yt:[],X.chunks.push(String(ie))),X.status="running",S.toolCall=X,S.streaming=!0;let Q=w.agentContext;(Q||w.executionId)&&(S.agentMetadata=(wo=S.agentMetadata)!=null?wo:{executionId:(xo=Q==null?void 0:Q.executionId)!=null?xo:w.executionId,iteration:(Sr=Q==null?void 0:Q.iteration)!=null?Sr:w.iteration}),u(S)}else if(Ue==="tool_complete"){let _=(Vo=(On=j(w,!1))!=null?On:j(w,!0))!=null?Vo:`tool-${c()}`;if(oe.has(_)){oe.delete(_);continue}let S=ae(_),X=(Jr=S.toolCall)!=null?Jr:{id:_,status:"running"};X.status="complete",w.result!==void 0&&(X.result=w.result),typeof w.duration=="number"&&(X.duration=w.duration),X.completedAt=Ie((Fr=w.completedAt)!=null?Fr:w.timestamp);let ie=(Yr=w.duration)!=null?Yr:w.executionTime;if(typeof ie=="number")X.durationMs=ie;else{let _e=(Zr=X.startedAt)!=null?Zr:Date.now();X.durationMs=Math.max(0,((Co=X.completedAt)!=null?Co:Date.now())-_e)}S.toolCall=X,S.streaming=!1;let Q=w.agentContext;(Q||w.executionId)&&(S.agentMetadata=(wt=S.agentMetadata)!=null?wt:{executionId:(Ao=Q==null?void 0:Q.executionId)!=null?Ao:w.executionId,iteration:(eo=Q==null?void 0:Q.iteration)!=null?eo:w.iteration}),u(S);let Te=re(w);Te&&I.byCall.delete(Te)}else if(Ue==="step_await"&&w.awaitReason==="local_tool_required"&&w.toolName){let _=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,S=(zn=_!=null?_:w.toolId)!=null?zn:`local-${c()}`,X=ae(S),ie=w.toolName,Q=zs(ie),Te=(Vn=X.toolCall)!=null?Vn:{id:S,status:"pending"};Te.name=ie,Te.args=w.parameters,Te.status=Q?"running":"complete",Te.chunks=(Pn=Te.chunks)!=null?Pn:[],Te.startedAt=(nr=Te.startedAt)!=null?nr:Ie((Tt=w.startedAt)!=null?Tt:w.timestamp),Q?(Te.completedAt=void 0,Te.duration=void 0,Te.durationMs=void 0):Te.completedAt=(rr=Te.completedAt)!=null?rr:Te.startedAt,X.toolCall=Te,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(to=w.executionId)!=null?to:(jn=X.agentMetadata)==null?void 0:jn.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},u(X)}else if(Ue==="text_start"){if((Or=w.toolContext)!=null&&Or.toolId)continue;let _=w.partId;if(_!==void 0&&M.current!==null&&_!==M.current){let S=m;S&&(S.streaming=!1,u(S),ot=S,m=null,E=!0)}_!==void 0&&(M.current=_)}else if(Ue==="text_end"){if((no=w.toolContext)!=null&&no.toolId)continue;let _=m;_&&(_.streaming=!1,u(_),ot=_,m=null,E=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let _=w.stepType,S=w.executionType;if(_==="tool"||S==="context")continue;let X=w.toolContext;if(X!=null&&X.toolId){let _e=String((Nt=(Kn=w.id)!=null?Kn:X.stepId)!=null?Nt:`step-${c()}`),st=w.partId!==void 0&&w.partId!==null?String(w.partId):"",et=`${X.toolId}::${_e}`,Ht=W.get(et);if(st!==""&&Ht!==void 0&&Ht!==""&&Ht!==st){let Ct=P.get(B(X.toolId,_e,Ht));Ct&&Ct.streaming!==!1&&(Ct.streaming=!1,u(Ct))}st!==""&&W.set(et,st);let qt=T(X.toolId,_e,st,X.executionId),an=(_r=(ro=(or=(In=w.text)!=null?In:w.delta)!=null?or:w.content)!=null?ro:w.chunk)!=null?_r:"";an&&(qt.content+=String(an),qt.streaming=!0,u(qt)),w.isComplete&&(qt.streaming=!1,u(qt));continue}let ie=w.partId;if(ie!==void 0&&M.current!==null&&ie!==M.current){let _e=m;_e&&(_e.streaming=!1,u(_e),ot=_e,m=null,E=!0)}ie!==void 0&&(M.current=ie);let Q=ie!==void 0&&(oo=it.get(ie))!=null?oo:be();ie!==void 0&&(Q.partId||(Q.partId=ie),it.set(ie,Q));let Te=(pt=(ye=(Gn=(Tr=w.text)!=null?Tr:w.delta)!=null?Gn:w.content)!=null?ye:w.chunk)!=null?pt:"";if(Te){let _e=typeof w.seq=="number"?w.seq:void 0,st=ie!=null?ie:Q.id,et=_e!==void 0?Me(st,_e,String(Te)):((en=ne.get(Q.id))!=null?en:"")+Te;Q.rawContent=et,Z.has(Q.id)||Z.set(Q.id,this.createStreamParser());let Ht=Z.get(Q.id),qt=et.trim().startsWith("{")||et.trim().startsWith("[");if(qt&&ne.set(Q.id,et),Ht.__isPlainTextParser===!0){Q.content=_e!==void 0?et:Q.content+Te,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q);continue}let Ct=Ht.processChunk(et);if(Ct instanceof Promise)Ct.then(Mt=>{var Wn;let hn=typeof Mt=="string"?Mt:(Wn=Mt==null?void 0:Mt.text)!=null?Wn:null;if(hn!==null&&hn.trim()!=="")Q.content=hn,u(Q);else if(!qt&&!et.trim().startsWith("<")){let xn=m,Yt=xn&&xn.id===Q.id?xn:Q;Yt.id===Q.id&&(Yt.content=_e!==void 0?et:Yt.content+Te,ne.delete(Yt.id),Z.delete(Yt.id),Yt.rawContent=void 0,u(Yt))}}).catch(()=>{Q.content=_e!==void 0?et:Q.content+Te,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q)});else{let Mt=typeof Ct=="string"?Ct:(pn=Ct==null?void 0:Ct.text)!=null?pn:null;Mt!==null&&Mt.trim()!==""?(Q.content=Mt,u(Q)):!qt&&!et.trim().startsWith("<")&&(Q.content=_e!==void 0?et:Q.content+Te,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q))}}if(w.isComplete){let _e=(Ss=(Mr=w.result)==null?void 0:Mr.response)!=null?Ss:Q.content;if(_e){let st=ne.get(Q.id),et=st!=null?st:ee(_e);Q.rawContent=et;let Ht=Z.get(Q.id),qt=null,an=!1;if(Ht&&(qt=Ht.getExtractedText(),qt===null&&(qt=Fo(et)),qt===null)){let Ct=Ht.processChunk(et);Ct instanceof Promise?(an=!0,Ct.then(Mt=>{var Wn;let hn=typeof Mt=="string"?Mt:(Wn=Mt==null?void 0:Mt.text)!=null?Wn:null;if(hn!==null){let xn=m;xn&&xn.id===Q.id&&(xn.content=hn,xn.streaming=!1,Z.delete(xn.id),ne.delete(xn.id),u(xn))}})):qt=typeof Ct=="string"?Ct:($r=Ct==null?void 0:Ct.text)!=null?$r:null}if(!an){qt!==null&&qt.trim()!==""?Q.content=qt:ne.has(Q.id)||(Q.content=ee(_e));let Ct=Z.get(Q.id);if(Ct){let Mt=(So=Ct.close)==null?void 0:So.call(Ct);Mt instanceof Promise&&Mt.catch(()=>{}),Z.delete(Q.id)}ne.delete(Q.id),Q.streaming=!1,u(Q)}}}}else if(Ue==="step_complete"){let _=w.stepType,S=w.executionType;if(_==="tool"||S==="context")continue;let X=w.toolContext;if(X!=null&&X.toolId){let _e=String((O=(Er=w.id)!=null?Er:X.stepId)!=null?O:"");if(_e){let st=D(X.toolId,_e);for(let[et,Ht]of P)et.startsWith(st)&&Ht.streaming!==!1&&(Ht.streaming=!1,u(Ht));W.delete(`${X.toolId}::${_e}`)}continue}let ie=w.stopReason;if(E){if(m!==null){let et=m;ie&&(et.stopReason=ie),Z.delete(et.id),ne.delete(et.id),et.streaming!==!1&&(et.streaming=!1,u(et))}let _e=(jo=w.result)==null?void 0:jo.response,st=ot;st&&(ie&&(st.stopReason=ie),_e!=null?fe(st,_e):(Z.delete(st.id),ne.delete(st.id))),ot=null;continue}let Q=(kr=w.result)==null?void 0:kr.response,Te=be();if(ie&&(Te.stopReason=ie),Q!=null){let _e=Z.get(Te.id),st=!1,et=!1;if(_e){let Ht=_e.getExtractedText(),qt=ne.get(Te.id),an=qt!=null?qt:ee(Q);if(Te.rawContent=an,Ht!==null&&Ht.trim()!=="")Te.content=Ht,st=!0;else{let Ct=Fo(an);if(Ct!==null)Te.content=Ct,st=!0;else{let Mt=_e.processChunk(an);if(Mt instanceof Promise)et=!0,Mt.then(hn=>{var xn;let Wn=typeof hn=="string"?hn:(xn=hn==null?void 0:hn.text)!=null?xn:null;if(Wn!==null&&Wn.trim()!==""){let Yt=m;Yt&&Yt.id===Te.id&&(Yt.content=Wn,Yt.streaming=!1,Z.delete(Yt.id),ne.delete(Yt.id),u(Yt))}else{let Yt=_e.getExtractedText(),ar=m;ar&&ar.id===Te.id&&(Yt!==null&&Yt.trim()!==""?ar.content=Yt:ne.has(ar.id)||(ar.content=ee(Q)),ar.streaming=!1,Z.delete(ar.id),ne.delete(ar.id),u(ar))}});else{let hn=typeof Mt=="string"?Mt:(Lr=Mt==null?void 0:Mt.text)!=null?Lr:null;if(hn!==null&&hn.trim()!=="")Te.content=hn,st=!0;else{let Wn=_e.getExtractedText();Wn!==null&&Wn.trim()!==""&&(Te.content=Wn,st=!0)}}}}}if(!et){if(!Te.rawContent){let Ht=ne.get(Te.id);Te.rawContent=Ht!=null?Ht:ee(Q)}if(!st&&!ne.has(Te.id)&&(Te.content=ee(Q)),_e){let Ht=(Ur=_e.close)==null?void 0:Ur.call(_e);Ht instanceof Promise&&Ht.catch(()=>{})}Z.delete(Te.id),ne.delete(Te.id),Te.streaming=!1,u(Te)}}else Z.delete(Te.id),ne.delete(Te.id),Te.streaming=!1,u(Te)}else if(Ue==="flow_complete"){let _=(Pr=w.result)==null?void 0:Pr.response;if(E){if(m!==null){let S=m;Z.delete(S.id),ne.delete(S.id),S.streaming!==!1&&(S.streaming=!1,u(S))}}else if(_!=null){let S=be(),X=ne.get(S.id),ie=X!=null?X:ee(_);S.rawContent=ie;let Q=ee(_),Te=Z.get(S.id);if(Te){let et=Fo(ie);if(et!==null)Q=et;else{let Ht=Te.processChunk(ie);Ht instanceof Promise&&Ht.then(an=>{var Mt;let Ct=typeof an=="string"?an:(Mt=an==null?void 0:an.text)!=null?Mt:null;Ct!==null&&(S.content=Ct,S.streaming=!1,u(S))});let qt=Te.getExtractedText();qt!==null&&(Q=qt)}}Z.delete(S.id),ne.delete(S.id);let _e=Q!==S.content,st=S.streaming!==!1;_e&&(S.content=Q),S.streaming=!1,(_e||st)&&u(S)}else if(m!==null){let S=m;Z.delete(S.id),ne.delete(S.id),S.streaming!==!1&&(S.streaming=!1,u(S))}t({type:"status",status:"idle"})}else if(Ue==="agent_start")Ke={executionId:w.executionId,agentId:(mr=w.agentId)!=null?mr:"virtual",agentName:(Ko=w.agentName)!=null?Ko:"",status:"running",currentIteration:0,maxTurns:(ya=w.maxTurns)!=null?ya:1,startedAt:Ie(w.startedAt)};else if(Ue==="agent_iteration_start"){if(Ke&&(Ke.currentIteration=w.iteration),je==="separate"&&w.iteration>1){let _=m;_&&(_.streaming=!1,u(_),Pe.set(w.iteration-1,_),m=null)}}else if(Ue==="agent_turn_start")v=null;else if(Ue==="agent_turn_delta"){if(w.contentType==="text"){let _=be();_.content+=(Qn=w.delta)!=null?Qn:"",_.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId,agentName:Ke==null?void 0:Ke.agentName},v=_,u(_)}else if(w.contentType==="thinking"){let _=(Xn=w.turnId)!=null?Xn:`agent-think-${w.iteration}`,S=Se(_);S.reasoning=(gr=S.reasoning)!=null?gr:{id:_,status:"streaming",chunks:[]},S.reasoning.chunks.push((fr=w.delta)!=null?fr:""),S.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId},u(S)}else if(w.contentType==="tool_input"){let _=(To=w.toolCallId)!=null?To:I.lastId;if(_){let S=N.get(_);S!=null&&S.toolCall&&(S.toolCall.chunks=(qr=S.toolCall.chunks)!=null?qr:[],S.toolCall.chunks.push((Cn=w.delta)!=null?Cn:""),u(S))}}}else if(Ue==="agent_turn_complete"){let _=w.turnId;if(_){let ie=k.get(_);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Ie(w.completedAt);let Q=(Ir=ie.reasoning.startedAt)!=null?Ir:Date.now();ie.reasoning.durationMs=Math.max(0,((Go=ie.reasoning.completedAt)!=null?Go:Date.now())-Q),ie.streaming=!1,u(ie)}}let S=w.stopReason,X=m!=null?m:v;if(S&&X!==null){let ie=w.turnId;(!ie||((Mo=X.agentMetadata)==null?void 0:Mo.turnId)===ie)&&(X.stopReason=S,u(X))}}else if(Ue==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let _=(Qo=w.toolCallId)!=null?Qo:`agent-tool-${c()}`;xe(re(w),_);let S=ae(_),X=(ba=S.toolCall)!=null?ba:{id:_,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};X.name=(va=(Xo=w.toolName)!=null?Xo:w.name)!=null?va:X.name,X.status="running",w.parameters!==void 0&&(X.args=w.parameters),X.startedAt=Ie((Jo=w.startedAt)!=null?Jo:w.timestamp),S.toolCall=X,S.streaming=!0,S.agentMetadata={executionId:w.executionId,iteration:w.iteration},u(S)}else if(Ue==="agent_tool_delta"){let _=(ht=w.toolCallId)!=null?ht:I.lastId;if(_){let S=(Ts=N.get(_))!=null?Ts:ae(_);S.toolCall&&(S.toolCall.chunks=(sr=S.toolCall.chunks)!=null?sr:[],S.toolCall.chunks.push((_n=w.delta)!=null?_n:""),S.toolCall.status="running",S.streaming=!0,u(S))}}else if(Ue==="agent_tool_complete"){let _=(xa=w.toolCallId)!=null?xa:I.lastId;if(_){let S=(wa=N.get(_))!=null?wa:ae(_);if(S.toolCall){S.toolCall.status="complete",w.result!==void 0&&(S.toolCall.result=w.result),typeof w.executionTime=="number"&&(S.toolCall.durationMs=w.executionTime),S.toolCall.completedAt=Ie((Yo=w.completedAt)!=null?Yo:w.timestamp),S.streaming=!1,u(S);let X=re(w);X&&I.byCall.delete(X)}}}else if(Ue==="agent_media"){let _=Array.isArray(w.media)?w.media:[],S=[];for(let X of _){if(!X||typeof X!="object")continue;let ie=X,Q=typeof ie.type=="string"?ie.type:void 0,Te=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",_e=null,st="";if(Q==="media"){let et=typeof ie.data=="string"?ie.data:void 0;if(!et)continue;st=Te.length>0?Te:"application/octet-stream",_e=`data:${st};base64,${et}`}else if(Q==="image-url"){let et=typeof ie.url=="string"?ie.url:void 0;if(!et)continue;st=Te,_e=et}else if(Q==="file-url"){let et=typeof ie.url=="string"?ie.url:void 0;if(!et)continue;st=Te,_e=et}else continue;if(_e)if(Q==="image-url"||st.startsWith("image/"))S.push({type:"image",image:_e,...st?{mimeType:st}:{}});else if(st.startsWith("audio/"))S.push({type:"audio",audio:_e,mimeType:st});else if(st.startsWith("video/"))S.push({type:"video",video:_e,mimeType:st});else{let et=st||"application/octet-stream";S.push({type:"file",data:_e,mimeType:et,filename:tf(et)})}}if(S.length>0){let X=c(),ie=w.toolCallId,Te={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${X}`:String(X)}`,role:"assistant",content:"",contentParts:S,createdAt:new Date().toISOString(),streaming:!1,sequence:X,agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(Te);let _e=m;_e&&(_e.streaming=!1,u(_e)),m=null,x.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let _=`agent-reflection-${w.executionId}-${w.iteration}`,S={id:_,role:"assistant",content:(zr=w.reflection)!=null?zr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:_,status:"complete",chunks:[(Ms=w.reflection)!=null?Ms:""]},agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(S)}else if(Ue==="agent_complete"){Ke&&(Ke.status=w.success?"complete":"error",Ke.completedAt=Ie(w.completedAt),Ke.stopReason=w.stopReason);let _=m;_&&(_.streaming=!1,u(_)),t({type:"status",status:"idle"})}else if(Ue==="agent_error"){let _=typeof w.error=="string"?w.error:(Es=(so=w.error)==null?void 0:so.message)!=null?Es:"Agent execution error";w.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",_):t({type:"error",error:new Error(_)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let _=(ks=w.approvalId)!=null?ks:`approval-${c()}`,S={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:_,status:"pending",agentId:(Ls=Ke==null?void 0:Ke.agentId)!=null?Ls:"virtual",executionId:($n=(Ps=w.executionId)!=null?Ps:Ke==null?void 0:Ke.executionId)!=null?$n:"",toolName:(Zo=w.toolName)!=null?Zo:"",toolType:w.toolType,description:(Rr=w.description)!=null?Rr:`Execute ${(Wr=w.toolName)!=null?Wr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(S)}else if(Ue==="step_await"&&w.awaitReason==="approval_required"){let _=(Is=w.approvalId)!=null?Is:`approval-${c()}`,S={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:_,status:"pending",agentId:(Ca=Ke==null?void 0:Ke.agentId)!=null?Ca:"virtual",executionId:(Rs=(Ws=w.executionId)!=null?Ws:Ke==null?void 0:Ke.executionId)!=null?Rs:"",toolName:(Eo=w.toolName)!=null?Eo:"",toolType:w.toolType,description:(Sa=w.description)!=null?Sa:`Execute ${(Aa=w.toolName)!=null?Aa:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(S)}else if(Ue==="agent_approval_complete"){let _=w.approvalId;if(_){let X={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:_,status:(Ta=w.decision)!=null?Ta:"approved",agentId:(Ma=Ke==null?void 0:Ke.agentId)!=null?Ma:"virtual",executionId:(ao=(Ea=w.executionId)!=null?Ea:Ke==null?void 0:Ke.executionId)!=null?ao:"",toolName:(io=w.toolName)!=null?io:"",description:(ka=w.description)!=null?ka:"",resolvedAt:Date.now()}};u(X)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let _=w.artifactType,S=String(w.id),X=typeof w.title=="string"?w.title:void 0;if(t({type:"artifact_start",id:S,artifactType:_,title:X,component:typeof w.component=="string"?w.component:void 0}),ge.set(S,{markdown:"",title:X}),!se.has(S)){se.add(S);let ie={id:`artifact-ref-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:S,title:X,artifactType:_,status:"streaming"}})};G.set(S,ie),u(ie)}}else if(Ue==="artifact_delta"){let _=String(w.id),S=typeof w.delta=="string"?w.delta:String((Hs=w.delta)!=null?Hs:"");t({type:"artifact_delta",id:_,artDelta:S});let X=ge.get(_);X&&(X.markdown+=S)}else if(Ue==="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(Ue==="artifact_complete"){let _=String(w.id);t({type:"artifact_complete",id:_});let S=G.get(_);if(S){S.streaming=!1;try{let X=JSON.parse((lo=S.rawContent)!=null?lo:"{}");if(X.props){X.props.status="complete";let ie=ge.get(_);ie!=null&&ie.markdown&&(X.props.markdown=ie.markdown)}S.rawContent=JSON.stringify(X)}catch{}ge.delete(_),u(S),G.delete(_)}}}else if(Ue==="transcript_insert"){let _=w.message;if(!_||typeof _!="object")continue;let S=String((La=_.id)!=null?La:`msg-${c()}`),X=_.role,Q={id:S,role:X==="user"?"user":X==="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(u(Q),Q.rawContent)try{let Te=JSON.parse(Q.rawContent),_e=(Bs=Te==null?void 0:Te.props)==null?void 0:Bs.artifactId;typeof _e=="string"&&se.add(_e)}catch{}m=null,x.current=null,Z.delete(S),ne.delete(S)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let _=null;if(w.error instanceof Error)_=w.error;else if(Ue==="dispatch_error"){let S=(co=w.message)!=null?co:w.error;S!=null&&S!==""&&(_=new Error(String(S)))}else if(Ue==="step_error"||Ue==="flow_error"){let S=w.error;typeof S=="string"&&S!==""?_=new Error(S):S!=null&&typeof S=="object"&&"message"in S&&(_=new Error(String((Ds=S.message)!=null?Ds:S)))}else Ue==="error"&&w.error!=null&&w.error!==""&&(_=new Error(String(w.error)));if(_){t({type:"error",error:_});let S=m;S&&S.streaming&&(S.streaming=!1,u(S)),t({type:"status",status:"idle"})}}}}}Xe.length=0};;){let{done:$,value:K}=await o.read();if($)break;a+=s.decode(K,{stream:!0});let he=a.split(`
9
+ `).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<=t)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=e(r);return s!==null&&(n=s),t=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Fo=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},gu=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},fu=()=>{var t;let n=of();return{processChunk:async e=>{let r=e.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(e)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},hu=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:e=>{let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(e.length<=t)return n!==null||n===""?{text:n||"",raw:e}:null;try{let o=Zg(e,ef|tf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?pu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=pu(o.text)))}catch{}return t=e.length,n!==null?{text:n,raw:e}:null},close:()=>{}}};var bu=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var Va=class{constructor(t,e=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=e}push(t,e){var s,a,i;let r=(i=(s=e==null?void 0:e.seq)!=null?s:e==null?void 0:e.sequenceIndex)!=null?i:(a=e==null?void 0:e.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,e);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,e),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,e);return}let o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(r,{payloadType:t,payload:e,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((e,r)=>e[0]-r[0]);for(let[e,r]of t)this.buffer.delete(e),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var yu="webmcp:";function vu(n){return n==="execution_start"}var Ka=class{constructor(t){this.kind="agent";this.iteration=1;this.openTurnId=null;this.openStepId=null;this.openTextBlockId=null;this.openReasoningId=null;this.mediaBuffers=new Map;var e;this.executionId=(e=t==null?void 0:t.executionId)!=null?e:""}push(t,e){var r,o,s,a,i,d,c,g,f,u,m,v,x,T,E;switch(typeof e.executionId=="string"&&e.executionId&&(this.executionId=e.executionId),typeof e.iteration=="number"&&(this.iteration=e.iteration),t){case"execution_start":return this.kind=e.kind==="flow"?"flow":"agent",this.kind!=="agent"?[]:[this.out("agent_start",{executionId:this.executionId,agentId:e.agentId,agentName:e.agentName,maxTurns:e.maxTurns,startedAt:e.startedAt})];case"turn_start":return this.openTurnId=typeof e.id=="string"?e.id:null,this.kind!=="agent"?[]:[this.out("agent_turn_start",{turnId:e.id,iteration:e.iteration})];case"turn_complete":{let A=this.kind==="agent"?[this.out("agent_turn_complete",{turnId:e.id,iteration:e.iteration,stopReason:e.stopReason,completedAt:e.completedAt})]:[];return this.openTurnId===e.id&&(this.openTurnId=null),A}case"execution_complete":return((r=e.kind)!=null?r:this.kind)==="agent"?[this.out("agent_complete",{executionId:this.executionId,success:e.success,completedAt:e.completedAt,stopReason:e.stopReason})]:[this.out("flow_complete",{success:e.success,completedAt:e.completedAt,duration:e.durationMs,finalOutput:e.finalOutput,totalSteps:e.totalSteps,successfulSteps:e.successfulSteps,failedSteps:e.failedSteps})];case"execution_error":return((o=e.kind)!=null?o:this.kind)==="agent"?[this.out("agent_error",{recoverable:!1,error:e.error})]:[this.out("flow_error",{error:e.error,code:e.code,upgradeUrl:e.upgradeUrl})];case"error":return[this.out("agent_error",{recoverable:!0,error:e.error})];case"ping":return[this.out("agent_ping",{timestamp:e.timestamp})];case"text_start":return this.openTextBlockId=typeof e.id=="string"?e.id:null,[];case"text_delta":{let A=String((s=e.delta)!=null?s:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"text",delta:A,turnId:(a=this.openTurnId)!=null?a:e.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("step_delta",{id:(i=this.openStepId)!=null?i:e.id,text:A,stepType:"prompt"})]}case"text_complete":return this.openTextBlockId===e.id&&(this.openTextBlockId=null),[];case"reasoning_start":return this.openReasoningId=typeof e.id=="string"?e.id:null,this.kind==="flow"?[this.out("reason_start",{id:e.id})]:[];case"reasoning_delta":{let A=String((d=e.delta)!=null?d:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"thinking",delta:A,turnId:(c=this.openTurnId)!=null?c:e.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("reason_delta",{id:e.id,delta:A})]}case"reasoning_complete":{let A=typeof e.text=="string"&&e.text.length>0;if(this.kind==="agent")return e.scope==="loop"||A?[this.out("agent_reflection",{reflection:(g=e.text)!=null?g:"",executionId:this.executionId,iteration:this.iteration})]:[];let R=[];return A&&R.push(this.out("reason_delta",{id:e.id,delta:e.text})),R.push(this.out("reason_complete",{id:e.id})),R}case"tool_start":return this.kind==="agent"?[this.out("agent_tool_start",{toolCallId:e.toolCallId,toolName:e.toolName,parameters:e.parameters,executionId:this.executionId,iteration:(f=e.iteration)!=null?f:this.iteration,startedAt:e.startedAt})]:[this.out("tool_start",{toolId:e.toolCallId,toolName:e.toolName,parameters:e.parameters,executionId:this.executionId,iteration:(u=e.iteration)!=null?u:this.iteration,startedAt:e.startedAt})];case"tool_input_delta":return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"tool_input",delta:String((m=e.delta)!=null?m:""),toolCallId:e.toolCallId})]:[];case"tool_input_complete":return[];case"tool_output_delta":{let A=String((v=e.delta)!=null?v:"");return this.kind==="agent"?[this.out("agent_tool_delta",{toolCallId:e.toolCallId,delta:A})]:[this.out("tool_delta",{toolId:e.toolCallId,delta:A})]}case"tool_complete":return this.kind==="agent"?[this.out("agent_tool_complete",{toolCallId:e.toolCallId,result:e.result,executionTime:e.executionTime,completedAt:e.completedAt})]:[this.out("tool_complete",{toolId:e.toolCallId,result:e.result,duration:e.executionTime,completedAt:e.completedAt})];case"media_start":{let A=String(e.id);return this.mediaBuffers.set(A,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,role:typeof e.role=="string"?e.role:void 0,toolCallId:e.toolCallId,parts:[]}),[]}case"media_delta":{let A=this.mediaBuffers.get(String(e.id));return A&&typeof e.delta=="string"&&A.parts.push(e.delta),[]}case"media_complete":{let A=String(e.id),R=this.mediaBuffers.get(A);this.mediaBuffers.delete(A);let L=(T=(x=typeof e.mediaType=="string"?e.mediaType:void 0)!=null?x:R==null?void 0:R.mediaType)!=null?T:"application/octet-stream",W=typeof e.data=="string"?e.data:void 0,C=typeof e.url=="string"?e.url:R&&R.parts.length>0?R.parts.join(""):void 0,k=null;return W?k={type:"media",data:W,mediaType:L}:C&&(k={type:L.startsWith("image/")?"image-url":"file-url",url:C,mediaType:L}),k?[this.out("agent_media",{media:[k],executionId:this.executionId,iteration:this.iteration,toolCallId:(E=e.toolCallId)!=null?E:R==null?void 0:R.toolCallId})]:[]}case"approval_start":return[this.out("agent_approval_start",{approvalId:e.approvalId,toolName:e.toolName,toolType:e.toolType,description:e.description,reason:e.reason,parameters:e.parameters,executionId:this.executionId})];case"approval_complete":return[this.out("agent_approval_complete",{approvalId:e.approvalId,decision:e.decision,executionId:this.executionId,toolName:e.toolName,description:e.description})];case"await":{let A=typeof e.toolName=="string"?e.toolName:"",R=e.origin==="webmcp"&&!A.startsWith(yu)?`${yu}${A}`:A;return[this.out("step_await",{awaitReason:"local_tool_required",toolName:R,parameters:e.parameters,toolCallId:e.toolCallId,toolId:e.toolId,executionId:this.executionId,awaitedAt:e.awaitedAt})]}case"step_start":return this.openStepId=typeof e.id=="string"?e.id:null,[this.out("step_start",{id:e.id,name:e.name,stepType:e.stepType,index:e.index,totalSteps:e.totalSteps,startedAt:e.startedAt,outputVariable:e.outputVariable})];case"step_complete":{let A=this.out("step_complete",{id:e.id,name:e.name,stepType:e.stepType,success:e.success,duration:e.durationMs,result:e.result,stopReason:e.stopReason,completedAt:e.completedAt,unresolvedVariables:e.unresolvedVariables});return this.openStepId===e.id&&(this.openStepId=null),[A]}case"step_skip":return[];case"artifact_start":return[this.out("artifact_start",{id:e.id,artifactType:e.artifactType,title:e.title,component:e.component})];case"artifact_delta":return[this.out("artifact_delta",{id:e.id,delta:e.delta})];case"artifact_update":return[this.out("artifact_update",{id:e.id,component:e.component,props:e.props})];case"artifact_complete":return[this.out("artifact_complete",{id:e.id})];case"source":case"custom":return[];default:return[]}}out(t,e){let r={};for(let[o,s]of Object.entries(e))s!==void 0&&(r[o]=s);return{payloadType:t,payload:r}}};var xu="3.37.0";var Qs=xu;var af="https://api.runtype.com/v1/dispatch",Ga="https://api.runtype.com";function lf(n){var s,a;let t=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.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 Ki=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 cf(n){switch(n){case"json":return hu;case"regex-json":return fu;case"xml":return bu;default:return gu}}var wu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function df(n,t){if(!n)return t;let e=n.trim(),r=t.trim();if(e.length===0)return t;if(r.length===0)return n;let o=wu(e);if(!wu(r))return n;if(!o||r===e||r.startsWith(e))return t;let a=Fo(n);return Fo(t)!==null&&a===null?t:n}var Xs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var e,r,o,s;this.apiUrl=(e=t.apiUrl)!=null?e:af,this.headers={"Content-Type":"application/json","X-Persona-Version":Qs,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:cf(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new _a(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var e;(e=this.webMcpBridge)==null||e.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,e,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,e,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}withEventsParam(t){return this.config.events!=="unified"?t:t+(t.includes("?")?"&":"?")+"events=unified"}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,e;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(),(e=(t=this.config).onSessionInit)==null||e.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,e={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Qs},body:JSON.stringify(e)});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 e;return`${((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Qs},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(t,e){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:e})}async submitCSATFeedback(t,e){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:t,comment:e})}async submitNPSFeedback(t,e){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:t,comment:e})}async dispatch(t,e){return this.isAgentMode()?this.dispatchAgent(t,e):this.isClientTokenMode()?this.dispatchClientToken(t,e):this.dispatchProxy(t,e)}async dispatchClientToken(t,e){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({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 L=new Error("Session expired. Please refresh to continue.");throw e({type:"error",error:L}),L}let c=await this.buildPayload(t.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,f={sessionId:d.sessionId,messages:t.messages.filter(Ki).map(L=>{var W,C,k;return{id:L.id,role:L.role,content:(k=(C=(W=L.contentParts)!=null?W:L.llmContent)!=null?C:L.rawContent)!=null?k:L.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},u=c.clientTools,m=!!(u&&u.length>0),v=m?Qp(u):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&x&&this.lastSentClientToolsFingerprint===v,E=!1,A=null,R;for(let L=0;;L++){let C={...f,...m&&(E||!T)&&u?{clientTools:u}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),R=await fetch(this.withEventsParam(this.getClientApiUrl("chat")),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Qs},body:JSON.stringify(C),signal:r.signal}),R.status===409&&L===0&&m){let k=await R.json().catch(()=>null);if((k==null?void 0:k.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=k!=null?k:{error:"Chat request failed"}}break}if(!R.ok){let L=A!=null?A:await R.json().catch(()=>({error:"Chat request failed"}));if(R.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw e({type:"error",error:C}),C}if(R.status===429){let C=new Error(L.hint||"Message limit reached for this session.");throw e({type:"error",error:C}),C}let W=new Error(L.error||"Failed to send message");throw e({type:"error",error:W}),W}if(!R.body){let L=new Error("No response body received");throw e({type:"error",error:L}),L}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,e({type:"status",status:"connected"});try{await this.streamResponse(R.body,e,t.assistantMessageId)}finally{e({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")&&e({type:"error",error:c}),c}}async dispatchProxy(t,e){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let 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.withEventsParam(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 e({type:"error",error:d}),d}else a=await fetch(this.withEventsParam(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 e({type:"error",error:i}),i}e({type:"status",status:"connected"});try{await this.streamResponse(a.body,e)}finally{e({type:"status",status:"idle"})}}async dispatchAgent(t,e){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let 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.withEventsParam(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 e({type:"error",error:d}),d}else a=await fetch(this.withEventsParam(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 e({type:"error",error:i}),i}e({type:"status",status:"connected"});try{await this.streamResponse(a.body,e,t.assistantMessageId)}finally{e({type:"status",status:"idle"})}}async processStream(t,e,r){e({type:"status",status:"connected"});try{await this.streamResponse(t,e,r)}finally{e({type:"status",status:"idle"})}}async resolveApproval(t,e){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ga}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:e,streamResponse:!0})})}async resumeFlow(t,e,r){var c,g;let o=this.isClientTokenMode(),s=this.withEventsParam(o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ga}/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:t,toolOutputs:e,streamResponse:(g=r==null?void 0:r.streamResponse)!=null?g:!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(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let e=t.slice().filter(Ki).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(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:e,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...ji(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:t,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(t){var s,a;let r={messages:t.slice().filter(Ki).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...ji(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:t,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(t,e,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=g=>{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(),...g!==void 0&&{partId:g}};return r.current=f,o(f),f},c=g=>r.current?r.current:d(g);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 g=c(i.partId);i.partId!==void 0&&!g.partId&&(g.partId=i.partId),g.content+=i.text,o(g)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,e({type:"status",status:"idle"})),i.error&&(a.current=null,e({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,e,r){var xr,An,Ve,Nt;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=$=>{let Me=$.reasoning?{...$.reasoning,chunks:[...$.reasoning.chunks]}:void 0,we=$.toolCall?{...$.toolCall,chunks:$.toolCall.chunks?[...$.toolCall.chunks]:void 0}:void 0,Fe=$.tools?$.tools.map(at=>({...at,chunks:at.chunks?[...at.chunks]:void 0})):void 0;return{...$,reasoning:Me,toolCall:we,tools:Fe}},f=$=>{if($.role!=="assistant"||$.variant)return!0;let Me=Array.isArray($.contentParts)&&$.contentParts.length>0,we=typeof $.rawContent=="string"&&$.rawContent.trim()!=="";return typeof $.content=="string"&&$.content.trim()!==""||Me||we||!!$.stopReason},u=$=>{f($)&&e({type:"message",message:g($)})},m=null,v=null,x={current:null},T={current:null},E=!1,A=new Map,R=new Map,L=new Map,W=new Map,C={lastId:null,byStep:new Map},k={lastId:null,byCall:new Map},D=($,Me,we="")=>`${$}::${Me}::${we}`,N=($,Me)=>`${$}::${Me}::`,M=($,Me,we,Fe)=>{let at=D($,Me,we),dt=L.get(at);if(dt)return dt;let rt=we?`-${we}`:"",Et={id:`nested-${$}-${Me}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...we?{partId:we}:{},agentMetadata:{executionId:Fe,parentToolId:$,parentStepId:Me}};return L.set(at,Et),u(Et),Et},U=$=>{if($==null)return null;try{return String($)}catch{return null}},z=$=>{var Me,we,Fe,at,dt;return U((dt=(at=(Fe=(we=(Me=$.stepId)!=null?Me:$.step_id)!=null?we:$.step)!=null?Fe:$.parentId)!=null?at:$.flowStepId)!=null?dt:$.flow_step_id)},ne=$=>{var Me,we,Fe,at,dt,rt,Et;return U((Et=(rt=(dt=(at=(Fe=(we=(Me=$.callId)!=null?Me:$.call_id)!=null?we:$.requestId)!=null?Fe:$.request_id)!=null?at:$.toolCallId)!=null?dt:$.tool_call_id)!=null?rt:$.stepId)!=null?Et:$.step_id)},Le=r,je=!1,ye=()=>{if(m)return m;let $;return!je&&Le?($=Le,je=!0):Le&&T.current?$=`${Le}_${T.current}`:$=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:$,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(m),m},De=($,Me)=>{C.lastId=Me,$&&C.byStep.set($,Me)},$e=($,Me)=>{var dt;let we=(dt=$.reasoningId)!=null?dt:$.id,Fe=z($);if(we){let rt=String(we);return De(Fe,rt),rt}if(Fe){let rt=C.byStep.get(Fe);if(rt)return C.lastId=rt,rt}if(C.lastId&&!Me)return C.lastId;if(!Me)return null;let at=`reason-${c()}`;return De(Fe,at),at},Se=$=>{let Me=A.get($);if(Me)return Me;let we={id:`reason-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"streaming",chunks:[]}};return A.set($,we),u(we),we},xe=($,Me)=>{k.lastId=Me,$&&k.byCall.set($,Me)},re=new Set,Q=new Map,oe=new Set,ge=new Map,de=$=>{if(!$)return!1;let Me=$.replace(/_+/g,"_").replace(/^_|_$/g,"");return Me==="emit_artifact_markdown"||Me==="emit_artifact_component"},V=($,Me)=>{var dt;let we=(dt=$.toolId)!=null?dt:$.id,Fe=ne($);if(we){let rt=String(we);return xe(Fe,rt),rt}if(Fe){let rt=k.byCall.get(Fe);if(rt)return k.lastId=rt,rt}if(k.lastId&&!Me)return k.lastId;if(!Me)return null;let at=`tool-${c()}`;return xe(Fe,at),at},se=$=>{let Me=R.get($);if(Me)return Me;let we={id:`tool-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:$,status:"pending"}};return R.set($,we),u(we),we},Re=$=>{if(typeof $=="number"&&Number.isFinite($))return $;if(typeof $=="string"){let Me=Number($);if(!Number.isNaN(Me)&&Number.isFinite(Me))return Me;let we=Date.parse($);if(!Number.isNaN(we))return we}return Date.now()},Z=$=>{if(typeof $=="string")return $;if($==null)return"";try{return JSON.stringify($)}catch{return String($)}},Y=new Map,te=new Map,ot=new Map,st=new Map,tt=null,Ee=($,Me,we)=>{var Et;let Fe=ot.get($);Fe||(Fe=[],ot.set($,Fe));let at=0,dt=Fe.length;for(;at<dt;){let j=at+dt>>>1;Fe[j].seq<Me?at=j+1:dt=j}((Et=Fe[at])==null?void 0:Et.seq)===Me?Fe[at]={seq:Me,text:we}:Fe.splice(at,0,{seq:Me,text:we});let rt="";for(let j=0;j<Fe.length;j++)rt+=Fe[j].text;return rt},fe=($,Me)=>{let we=Z(Me),Fe=te.get($.id),at=df(Fe,we);$.rawContent=at;let dt=Y.get($.id),rt=ue=>{var pt;let Te=(pt=$.content)!=null?pt:"";ue.trim()!==""&&(Te.trim().length===0||ue.startsWith(Te)||ue.trimStart().startsWith(Te.trim()))&&($.content=ue)},Et=()=>{var ue;if(dt){let Te=(ue=dt.close)==null?void 0:ue.call(dt);Te instanceof Promise&&Te.catch(()=>{})}Y.delete($.id),te.delete($.id),$.streaming=!1,u($)};if(!dt){rt(we),Et();return}let j=Fo(at);if(j!==null&&j.trim()!==""){rt(j),Et();return}let At=ue=>{var Zt;let Te=typeof ue=="string"?ue:(Zt=ue==null?void 0:ue.text)!=null?Zt:null;if(Te!==null&&Te.trim()!=="")return Te;let pt=dt.getExtractedText();return pt!==null&&pt.trim()!==""?pt:we},ce;try{ce=dt.processChunk(at)}catch{rt(we),Et();return}if(ce instanceof Promise){ce.then(ue=>{rt(At(ue)),Et()}).catch(()=>{rt(we),Et()});return}rt(At(ce)),Et()},Ke=[],X=!1,pe,ke=()=>{X||(X=!0,queueMicrotask(()=>{X=!1,pe()}))},Qe=new Va(($,Me)=>{Ke.push({payloadType:$,payload:Me}),ke()}),Kt=new Ka,Ie=this.config.events==="unified",qe=!1,nt=null,Dt=new Map,bn=(xr=this.config.iterationDisplay)!=null?xr:"separate";for(pe=()=>{var $,Me,we,Fe,at,dt,rt,Et,j,At,ce,ue,Te,pt,Zt,sn,xn,_t,Ze,Ft,ut,en,nr,Pn,an,_n,wr,wt,zn,Cr,Dr,pr,vt,xo,Ar,wo,On,jo,Jr,Nr,Yr,Zr,Co,Ao,eo,St,jn,Vn,Wn,Mt,rr,or,Kn,to,Fr,no,Gn,Ot,Rn,sr,ro,_r,oo,Sr,Qn,be,mt,nn,pn,Tr,As,Or,So,Er,_,Vo,Mr,kr,$r,Lr,ur,Ko,ba,Xn,Jn,mr,gr,To,qr,Sn,Ir,Go,Eo,Qo,ya,Xo,va,Jo,yt,Ss,ar,$n,xa,wa,Yo,Ur,Ts,so,Es,Ms,ks,Ls,qn,Zo,Pr,Wr,Is,Ca,Ps,Ws,Mo,Aa,Sa,Ta,Ea,Ma,ao,io,ka,Rs,lo,La,Bs,co,Hs,Ia,zr,Pa;for(let Rr=0;Rr<Ke.length;Rr++){let he=Ke[Rr].payloadType,w=Ke[Rr].payload;if(he==="reason_start"){let O=($=$e(w,!0))!=null?$:`reason-${c()}`,I=Se(O);I.reasoning=(Me=I.reasoning)!=null?Me:{id:O,status:"streaming",chunks:[]},I.reasoning.startedAt=(Fe=I.reasoning.startedAt)!=null?Fe:Re((we=w.startedAt)!=null?we:w.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",u(I)}else if(he==="reason_delta"||he==="reason_chunk"){let O=(dt=(at=$e(w,!1))!=null?at:$e(w,!0))!=null?dt:`reason-${c()}`,I=Se(O);I.reasoning=(rt=I.reasoning)!=null?rt:{id:O,status:"streaming",chunks:[]},I.reasoning.startedAt=(j=I.reasoning.startedAt)!=null?j:Re((Et=w.startedAt)!=null?Et:w.timestamp);let K=(ue=(ce=(At=w.reasoningText)!=null?At:w.text)!=null?ce:w.delta)!=null?ue:"";if(K&&w.hidden!==!0){let ae=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(ae!==void 0){let G=Ee(O,ae,String(K));I.reasoning.chunks=[G]}else I.reasoning.chunks.push(String(K))}if(I.reasoning.status=w.done?"complete":"streaming",w.done){I.reasoning.completedAt=Re((Te=w.completedAt)!=null?Te:w.timestamp);let ae=(pt=I.reasoning.startedAt)!=null?pt:Date.now();I.reasoning.durationMs=Math.max(0,((Zt=I.reasoning.completedAt)!=null?Zt:Date.now())-ae)}I.streaming=I.reasoning.status!=="complete",u(I)}else if(he==="reason_complete"){let O=(xn=(sn=$e(w,!1))!=null?sn:$e(w,!0))!=null?xn:`reason-${c()}`,I=A.get(O);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=Re((_t=w.completedAt)!=null?_t:w.timestamp);let ae=(Ze=I.reasoning.startedAt)!=null?Ze:Date.now();I.reasoning.durationMs=Math.max(0,((Ft=I.reasoning.completedAt)!=null?Ft:Date.now())-ae),I.streaming=!1,u(I)}let K=z(w);K&&C.byStep.delete(K)}else if(he==="tool_start"){let O=(ut=V(w,!0))!=null?ut:`tool-${c()}`,I=(en=w.toolName)!=null?en:w.name;if(de(I)){re.add(O);continue}let K=se(O),ae=(nr=K.toolCall)!=null?nr:{id:O,status:"pending"};ae.name=I!=null?I:ae.name,ae.status="running",w.args!==void 0?ae.args=w.args:w.parameters!==void 0&&(ae.args=w.parameters),ae.startedAt=(an=ae.startedAt)!=null?an:Re((Pn=w.startedAt)!=null?Pn:w.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,K.toolCall=ae,K.streaming=!0;let G=w.agentContext;(G||w.executionId)&&(K.agentMetadata={executionId:(_n=G==null?void 0:G.executionId)!=null?_n:w.executionId,iteration:(wr=G==null?void 0:G.iteration)!=null?wr:w.iteration}),u(K)}else if(he==="tool_chunk"||he==="tool_delta"){let O=(zn=(wt=V(w,!1))!=null?wt:V(w,!0))!=null?zn:`tool-${c()}`;if(re.has(O))continue;let I=se(O),K=(Cr=I.toolCall)!=null?Cr:{id:O,status:"running"};K.startedAt=(pr=K.startedAt)!=null?pr:Re((Dr=w.startedAt)!=null?Dr:w.timestamp);let ae=(Ar=(xo=(vt=w.text)!=null?vt:w.delta)!=null?xo:w.message)!=null?Ar:"";ae&&(K.chunks=(wo=K.chunks)!=null?wo:[],K.chunks.push(String(ae))),K.status="running",I.toolCall=K,I.streaming=!0;let G=w.agentContext;(G||w.executionId)&&(I.agentMetadata=(Jr=I.agentMetadata)!=null?Jr:{executionId:(On=G==null?void 0:G.executionId)!=null?On:w.executionId,iteration:(jo=G==null?void 0:G.iteration)!=null?jo:w.iteration}),u(I)}else if(he==="tool_complete"){let O=(Yr=(Nr=V(w,!1))!=null?Nr:V(w,!0))!=null?Yr:`tool-${c()}`;if(re.has(O)){re.delete(O);continue}let I=se(O),K=(Zr=I.toolCall)!=null?Zr:{id:O,status:"running"};K.status="complete",w.result!==void 0&&(K.result=w.result),typeof w.duration=="number"&&(K.duration=w.duration),K.completedAt=Re((Co=w.completedAt)!=null?Co:w.timestamp);let ae=(Ao=w.duration)!=null?Ao:w.executionTime;if(typeof ae=="number")K.durationMs=ae;else{let Oe=(eo=K.startedAt)!=null?eo:Date.now();K.durationMs=Math.max(0,((St=K.completedAt)!=null?St:Date.now())-Oe)}I.toolCall=K,I.streaming=!1;let G=w.agentContext;(G||w.executionId)&&(I.agentMetadata=(Wn=I.agentMetadata)!=null?Wn:{executionId:(jn=G==null?void 0:G.executionId)!=null?jn:w.executionId,iteration:(Vn=G==null?void 0:G.iteration)!=null?Vn:w.iteration}),u(I);let We=ne(w);We&&k.byCall.delete(We)}else if(he==="step_await"&&w.awaitReason==="local_tool_required"&&w.toolName){let O=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,I=(Mt=O!=null?O:w.toolId)!=null?Mt:`local-${c()}`,K=se(I),ae=w.toolName,G=Us(ae),We=(rr=K.toolCall)!=null?rr:{id:I,status:"pending"};We.name=ae,We.args=w.parameters,We.status=G?"running":"complete",We.chunks=(or=We.chunks)!=null?or:[],We.startedAt=(to=We.startedAt)!=null?to:Re((Kn=w.startedAt)!=null?Kn:w.timestamp),G?(We.completedAt=void 0,We.duration=void 0,We.durationMs=void 0):We.completedAt=(Fr=We.completedAt)!=null?Fr:We.startedAt,K.toolCall=We,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:(Gn=w.executionId)!=null?Gn:(no=K.agentMetadata)==null?void 0:no.executionId,awaitingLocalTool:!0,...O?{webMcpToolCallId:O}:{}},u(K)}else if(he==="text_start"){if((Ot=w.toolContext)!=null&&Ot.toolId)continue;let O=w.partId;if(O!==void 0&&T.current!==null&&O!==T.current){let I=m;I&&(I.streaming=!1,u(I),tt=I,m=null,E=!0)}O!==void 0&&(T.current=O)}else if(he==="text_end"){if((Rn=w.toolContext)!=null&&Rn.toolId)continue;let O=m;O&&(O.streaming=!1,u(O),tt=O,m=null,E=!0)}else if(he==="step_chunk"||he==="step_delta"){let O=w.stepType,I=w.executionType;if(O==="tool"||I==="context")continue;let K=w.toolContext;if(K!=null&&K.toolId){let Oe=String((ro=(sr=w.id)!=null?sr:K.stepId)!=null?ro:`step-${c()}`),it=w.partId!==void 0&&w.partId!==null?String(w.partId):"",Je=`${K.toolId}::${Oe}`,It=W.get(Je);if(it!==""&&It!==void 0&&It!==""&&It!==it){let Pt=L.get(D(K.toolId,Oe,It));Pt&&Pt.streaming!==!1&&(Pt.streaming=!1,u(Pt))}it!==""&&W.set(Je,it);let $t=M(K.toolId,Oe,it,K.executionId),yn=(Qn=(Sr=(oo=(_r=w.text)!=null?_r:w.delta)!=null?oo:w.content)!=null?Sr:w.chunk)!=null?Qn:"";yn&&($t.content+=String(yn),$t.streaming=!0,u($t)),w.isComplete&&($t.streaming=!1,u($t));continue}let ae=w.partId;if(ae!==void 0&&T.current!==null&&ae!==T.current){let Oe=m;Oe&&(Oe.streaming=!1,u(Oe),tt=Oe,m=null,E=!0)}ae!==void 0&&(T.current=ae);let G=ae!==void 0&&(be=st.get(ae))!=null?be:ye();ae!==void 0&&(G.partId||(G.partId=ae),st.set(ae,G));let We=(Tr=(pn=(nn=(mt=w.text)!=null?mt:w.delta)!=null?nn:w.content)!=null?pn:w.chunk)!=null?Tr:"";if(We){let Oe=typeof w.seq=="number"?w.seq:void 0,it=ae!=null?ae:G.id,Je=Oe!==void 0?Ee(it,Oe,String(We)):((As=te.get(G.id))!=null?As:"")+We;G.rawContent=Je,Y.has(G.id)||Y.set(G.id,this.createStreamParser());let It=Y.get(G.id),$t=Je.trim().startsWith("{")||Je.trim().startsWith("[");if($t&&te.set(G.id,Je),It.__isPlainTextParser===!0){G.content=Oe!==void 0?Je:G.content+We,te.delete(G.id),Y.delete(G.id),G.rawContent=void 0,u(G);continue}let Pt=It.processChunk(Je);if(Pt instanceof Promise)Pt.then(Bt=>{var Tn;let un=typeof Bt=="string"?Bt:(Tn=Bt==null?void 0:Bt.text)!=null?Tn:null;if(un!==null&&un.trim()!=="")G.content=un,u(G);else if(!$t&&!Je.trim().startsWith("<")){let wn=m,Ht=wn&&wn.id===G.id?wn:G;Ht.id===G.id&&(Ht.content=Oe!==void 0?Je:Ht.content+We,te.delete(Ht.id),Y.delete(Ht.id),Ht.rawContent=void 0,u(Ht))}}).catch(()=>{G.content=Oe!==void 0?Je:G.content+We,te.delete(G.id),Y.delete(G.id),G.rawContent=void 0,u(G)});else{let Bt=typeof Pt=="string"?Pt:(Or=Pt==null?void 0:Pt.text)!=null?Or:null;Bt!==null&&Bt.trim()!==""?(G.content=Bt,u(G)):!$t&&!Je.trim().startsWith("<")&&(G.content=Oe!==void 0?Je:G.content+We,te.delete(G.id),Y.delete(G.id),G.rawContent=void 0,u(G))}}if(w.isComplete){let Oe=(Er=(So=w.result)==null?void 0:So.response)!=null?Er:G.content;if(Oe){let it=te.get(G.id),Je=it!=null?it:Z(Oe);G.rawContent=Je;let It=Y.get(G.id),$t=null,yn=!1;if(It&&($t=It.getExtractedText(),$t===null&&($t=Fo(Je)),$t===null)){let Pt=It.processChunk(Je);Pt instanceof Promise?(yn=!0,Pt.then(Bt=>{var Tn;let un=typeof Bt=="string"?Bt:(Tn=Bt==null?void 0:Bt.text)!=null?Tn:null;if(un!==null){let wn=m;wn&&wn.id===G.id&&(wn.content=un,wn.streaming=!1,Y.delete(wn.id),te.delete(wn.id),u(wn))}})):$t=typeof Pt=="string"?Pt:(_=Pt==null?void 0:Pt.text)!=null?_:null}if(!yn){$t!==null&&$t.trim()!==""?G.content=$t:te.has(G.id)||(G.content=Z(Oe));let Pt=Y.get(G.id);if(Pt){let Bt=(Vo=Pt.close)==null?void 0:Vo.call(Pt);Bt instanceof Promise&&Bt.catch(()=>{}),Y.delete(G.id)}te.delete(G.id),G.streaming=!1,u(G)}}}}else if(he==="step_complete"){let O=w.stepType,I=w.executionType;if(O==="tool"||I==="context")continue;let K=w.toolContext;if(K!=null&&K.toolId){let Oe=String((kr=(Mr=w.id)!=null?Mr:K.stepId)!=null?kr:"");if(Oe){let it=N(K.toolId,Oe);for(let[Je,It]of L)Je.startsWith(it)&&It.streaming!==!1&&(It.streaming=!1,u(It));W.delete(`${K.toolId}::${Oe}`)}continue}let ae=w.stopReason;if(E){if(m!==null){let Je=m;ae&&(Je.stopReason=ae),Y.delete(Je.id),te.delete(Je.id),Je.streaming!==!1&&(Je.streaming=!1,u(Je))}let Oe=($r=w.result)==null?void 0:$r.response,it=tt;it&&(ae&&(it.stopReason=ae),Oe!=null?fe(it,Oe):(Y.delete(it.id),te.delete(it.id))),tt=null;continue}let G=(Lr=w.result)==null?void 0:Lr.response,We=ye();if(ae&&(We.stopReason=ae),G!=null){let Oe=Y.get(We.id),it=!1,Je=!1;if(Oe){let It=Oe.getExtractedText(),$t=te.get(We.id),yn=$t!=null?$t:Z(G);if(We.rawContent=yn,It!==null&&It.trim()!=="")We.content=It,it=!0;else{let Pt=Fo(yn);if(Pt!==null)We.content=Pt,it=!0;else{let Bt=Oe.processChunk(yn);if(Bt instanceof Promise)Je=!0,Bt.then(un=>{var wn;let Tn=typeof un=="string"?un:(wn=un==null?void 0:un.text)!=null?wn:null;if(Tn!==null&&Tn.trim()!==""){let Ht=m;Ht&&Ht.id===We.id&&(Ht.content=Tn,Ht.streaming=!1,Y.delete(Ht.id),te.delete(Ht.id),u(Ht))}else{let Ht=Oe.getExtractedText(),ln=m;ln&&ln.id===We.id&&(Ht!==null&&Ht.trim()!==""?ln.content=Ht:te.has(ln.id)||(ln.content=Z(G)),ln.streaming=!1,Y.delete(ln.id),te.delete(ln.id),u(ln))}});else{let un=typeof Bt=="string"?Bt:(ur=Bt==null?void 0:Bt.text)!=null?ur:null;if(un!==null&&un.trim()!=="")We.content=un,it=!0;else{let Tn=Oe.getExtractedText();Tn!==null&&Tn.trim()!==""&&(We.content=Tn,it=!0)}}}}}if(!Je){if(!We.rawContent){let It=te.get(We.id);We.rawContent=It!=null?It:Z(G)}if(!it&&!te.has(We.id)&&(We.content=Z(G)),Oe){let It=(Ko=Oe.close)==null?void 0:Ko.call(Oe);It instanceof Promise&&It.catch(()=>{})}Y.delete(We.id),te.delete(We.id),We.streaming=!1,u(We)}}else Y.delete(We.id),te.delete(We.id),We.streaming=!1,u(We)}else if(he==="flow_complete"){let O=(ba=w.result)==null?void 0:ba.response;if(E){if(m!==null){let I=m;Y.delete(I.id),te.delete(I.id),I.streaming!==!1&&(I.streaming=!1,u(I))}}else if(O!=null){let I=ye(),K=te.get(I.id),ae=K!=null?K:Z(O);I.rawContent=ae;let G=Z(O),We=Y.get(I.id);if(We){let Je=Fo(ae);if(Je!==null)G=Je;else{let It=We.processChunk(ae);It instanceof Promise&&It.then(yn=>{var Bt;let Pt=typeof yn=="string"?yn:(Bt=yn==null?void 0:yn.text)!=null?Bt:null;Pt!==null&&(I.content=Pt,I.streaming=!1,u(I))});let $t=We.getExtractedText();$t!==null&&(G=$t)}}Y.delete(I.id),te.delete(I.id);let Oe=G!==I.content,it=I.streaming!==!1;Oe&&(I.content=G),I.streaming=!1,(Oe||it)&&u(I)}else if(m!==null){let I=m;Y.delete(I.id),te.delete(I.id),I.streaming!==!1&&(I.streaming=!1,u(I))}e({type:"status",status:"idle"})}else if(he==="agent_start")nt={executionId:w.executionId,agentId:(Xn=w.agentId)!=null?Xn:"virtual",agentName:(Jn=w.agentName)!=null?Jn:"",status:"running",currentIteration:0,maxTurns:(mr=w.maxTurns)!=null?mr:1,startedAt:Re(w.startedAt)};else if(he==="agent_iteration_start"){if(nt&&(nt.currentIteration=w.iteration),bn==="separate"&&w.iteration>1){let O=m;O&&(O.streaming=!1,u(O),Dt.set(w.iteration-1,O),m=null)}}else if(he==="agent_turn_start")v=null;else if(he==="agent_turn_delta"){if(w.contentType==="text"){let O=ye();O.content+=(gr=w.delta)!=null?gr:"",O.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId,agentName:nt==null?void 0:nt.agentName},v=O,u(O)}else if(w.contentType==="thinking"){let O=(To=w.turnId)!=null?To:`agent-think-${w.iteration}`,I=Se(O);I.reasoning=(qr=I.reasoning)!=null?qr:{id:O,status:"streaming",chunks:[]},I.reasoning.chunks.push((Sn=w.delta)!=null?Sn:""),I.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId},u(I)}else if(w.contentType==="tool_input"){let O=(Ir=w.toolCallId)!=null?Ir:k.lastId;if(O){let I=R.get(O);I!=null&&I.toolCall&&(I.toolCall.chunks=(Go=I.toolCall.chunks)!=null?Go:[],I.toolCall.chunks.push((Eo=w.delta)!=null?Eo:""),u(I))}}}else if(he==="agent_turn_complete"){let O=w.turnId;if(O){let ae=A.get(O);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=Re(w.completedAt);let G=(Qo=ae.reasoning.startedAt)!=null?Qo:Date.now();ae.reasoning.durationMs=Math.max(0,((ya=ae.reasoning.completedAt)!=null?ya:Date.now())-G),ae.streaming=!1,u(ae)}}let I=w.stopReason,K=m!=null?m:v;if(I&&K!==null){let ae=w.turnId;(!ae||((Xo=K.agentMetadata)==null?void 0:Xo.turnId)===ae)&&(K.stopReason=I,u(K))}}else if(he==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let O=(va=w.toolCallId)!=null?va:`agent-tool-${c()}`;xe(ne(w),O);let I=se(O),K=(Jo=I.toolCall)!=null?Jo:{id:O,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};K.name=(Ss=(yt=w.toolName)!=null?yt:w.name)!=null?Ss:K.name,K.status="running",w.parameters!==void 0&&(K.args=w.parameters),K.startedAt=Re((ar=w.startedAt)!=null?ar:w.timestamp),I.toolCall=K,I.streaming=!0,I.agentMetadata={executionId:w.executionId,iteration:w.iteration},u(I)}else if(he==="agent_tool_delta"){let O=($n=w.toolCallId)!=null?$n:k.lastId;if(O){let I=(xa=R.get(O))!=null?xa:se(O);I.toolCall&&(I.toolCall.chunks=(wa=I.toolCall.chunks)!=null?wa:[],I.toolCall.chunks.push((Yo=w.delta)!=null?Yo:""),I.toolCall.status="running",I.streaming=!0,u(I))}}else if(he==="agent_tool_complete"){let O=(Ur=w.toolCallId)!=null?Ur:k.lastId;if(O){let I=(Ts=R.get(O))!=null?Ts:se(O);if(I.toolCall){I.toolCall.status="complete",w.result!==void 0&&(I.toolCall.result=w.result),typeof w.executionTime=="number"&&(I.toolCall.durationMs=w.executionTime),I.toolCall.completedAt=Re((so=w.completedAt)!=null?so:w.timestamp),I.streaming=!1,u(I);let K=ne(w);K&&k.byCall.delete(K)}}}else if(he==="agent_media"){let O=Array.isArray(w.media)?w.media:[],I=[];for(let K of O){if(!K||typeof K!="object")continue;let ae=K,G=typeof ae.type=="string"?ae.type:void 0,We=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Oe=null,it="";if(G==="media"){let Je=typeof ae.data=="string"?ae.data:void 0;if(!Je)continue;it=We.length>0?We:"application/octet-stream",Oe=`data:${it};base64,${Je}`}else if(G==="image-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;it=We,Oe=Je}else if(G==="file-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;it=We,Oe=Je}else continue;if(Oe)if(G==="image-url"||it.startsWith("image/"))I.push({type:"image",image:Oe,...it?{mimeType:it}:{}});else if(it.startsWith("audio/"))I.push({type:"audio",audio:Oe,mimeType:it});else if(it.startsWith("video/"))I.push({type:"video",video:Oe,mimeType:it});else{let Je=it||"application/octet-stream";I.push({type:"file",data:Oe,mimeType:Je,filename:lf(Je)})}}if(I.length>0){let K=c(),ae=w.toolCallId,We={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${K}`:String(K)}`,role:"assistant",content:"",contentParts:I,createdAt:new Date().toISOString(),streaming:!1,sequence:K,agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(We);let Oe=m;Oe&&(Oe.streaming=!1,u(Oe)),m=null,x.current=null}}else if(he!=="agent_iteration_complete"){if(he==="agent_reflection"||he==="agent_reflect"){let O=`agent-reflection-${w.executionId}-${w.iteration}`,I={id:O,role:"assistant",content:(Es=w.reflection)!=null?Es:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:O,status:"complete",chunks:[(Ms=w.reflection)!=null?Ms:""]},agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(I)}else if(he==="agent_complete"){nt&&(nt.status=w.success?"complete":"error",nt.completedAt=Re(w.completedAt),nt.stopReason=w.stopReason);let O=m;O&&(O.streaming=!1,u(O)),e({type:"status",status:"idle"})}else if(he==="agent_error"){let O=typeof w.error=="string"?w.error:(Ls=(ks=w.error)==null?void 0:ks.message)!=null?Ls:"Agent execution error";w.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",O):e({type:"error",error:new Error(O)})}else if(he!=="agent_ping"){if(he==="agent_approval_start"){let O=(qn=w.approvalId)!=null?qn:`approval-${c()}`,I={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:O,status:"pending",agentId:(Zo=nt==null?void 0:nt.agentId)!=null?Zo:"virtual",executionId:(Wr=(Pr=w.executionId)!=null?Pr:nt==null?void 0:nt.executionId)!=null?Wr:"",toolName:(Is=w.toolName)!=null?Is:"",toolType:w.toolType,description:(Ps=w.description)!=null?Ps:`Execute ${(Ca=w.toolName)!=null?Ca:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(I)}else if(he==="step_await"&&w.awaitReason==="approval_required"){let O=(Ws=w.approvalId)!=null?Ws:`approval-${c()}`,I={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:O,status:"pending",agentId:(Mo=nt==null?void 0:nt.agentId)!=null?Mo:"virtual",executionId:(Sa=(Aa=w.executionId)!=null?Aa:nt==null?void 0:nt.executionId)!=null?Sa:"",toolName:(Ta=w.toolName)!=null?Ta:"",toolType:w.toolType,description:(Ma=w.description)!=null?Ma:`Execute ${(Ea=w.toolName)!=null?Ea:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(I)}else if(he==="agent_approval_complete"){let O=w.approvalId;if(O){let K={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:O,status:(ao=w.decision)!=null?ao:"approved",agentId:(io=nt==null?void 0:nt.agentId)!=null?io:"virtual",executionId:(Rs=(ka=w.executionId)!=null?ka:nt==null?void 0:nt.executionId)!=null?Rs:"",toolName:(lo=w.toolName)!=null?lo:"",description:(La=w.description)!=null?La:"",resolvedAt:Date.now()}};u(K)}}else if(he==="artifact_start"||he==="artifact_delta"||he==="artifact_update"||he==="artifact_complete"){if(he==="artifact_start"){let O=w.artifactType,I=String(w.id),K=typeof w.title=="string"?w.title:void 0;if(e({type:"artifact_start",id:I,artifactType:O,title:K,component:typeof w.component=="string"?w.component:void 0}),ge.set(I,{markdown:"",title:K}),!oe.has(I)){oe.add(I);let ae={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:I,title:K,artifactType:O,status:"streaming"}})};Q.set(I,ae),u(ae)}}else if(he==="artifact_delta"){let O=String(w.id),I=typeof w.delta=="string"?w.delta:String((Bs=w.delta)!=null?Bs:"");e({type:"artifact_delta",id:O,artDelta:I});let K=ge.get(O);K&&(K.markdown+=I)}else if(he==="artifact_update"){let O=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};e({type:"artifact_update",id:String(w.id),props:O,component:typeof w.component=="string"?w.component:void 0})}else if(he==="artifact_complete"){let O=String(w.id);e({type:"artifact_complete",id:O});let I=Q.get(O);if(I){I.streaming=!1;try{let K=JSON.parse((co=I.rawContent)!=null?co:"{}");if(K.props){K.props.status="complete";let ae=ge.get(O);ae!=null&&ae.markdown&&(K.props.markdown=ae.markdown)}I.rawContent=JSON.stringify(K)}catch{}ge.delete(O),u(I),Q.delete(O)}}}else if(he==="transcript_insert"){let O=w.message;if(!O||typeof O!="object")continue;let I=String((Hs=O.id)!=null?Hs:`msg-${c()}`),K=O.role,G={id:I,role:K==="user"?"user":K==="system"?"system":"assistant",content:typeof O.content=="string"?O.content:"",rawContent:typeof O.rawContent=="string"?O.rawContent:void 0,createdAt:typeof O.createdAt=="string"?O.createdAt:new Date().toISOString(),streaming:O.streaming===!0,...typeof O.variant=="string"?{variant:O.variant}:{},sequence:c()};if(u(G),G.rawContent)try{let We=JSON.parse(G.rawContent),Oe=(Ia=We==null?void 0:We.props)==null?void 0:Ia.artifactId;typeof Oe=="string"&&oe.add(Oe)}catch{}m=null,x.current=null,Y.delete(I),te.delete(I)}else if(he==="error"||he==="step_error"||he==="dispatch_error"||he==="flow_error"){let O=null;if(w.error instanceof Error)O=w.error;else if(he==="dispatch_error"){let I=(zr=w.message)!=null?zr:w.error;I!=null&&I!==""&&(O=new Error(String(I)))}else if(he==="step_error"||he==="flow_error"){let I=w.error;typeof I=="string"&&I!==""?O=new Error(I):I!=null&&typeof I=="object"&&"message"in I&&(O=new Error(String((Pa=I.message)!=null?Pa:I)))}else he==="error"&&w.error!=null&&w.error!==""&&(O=new Error(String(w.error)));if(O){e({type:"error",error:O});let I=m;I&&I.streaming&&(I.streaming=!1,u(I)),e({type:"status",status:"idle"})}}}}}Ke.length=0};;){let{done:$,value:Me}=await o.read();if($)break;a+=s.decode(Me,{stream:!0});let we=a.split(`
10
10
 
11
- `);a=(Wt=he.pop())!=null?Wt:"";for(let Ge of he){let Ze=Ge.split(`
12
- `),$e="message",Oe="";for(let Xt of Ze)Xt.startsWith("event:")?$e=Xt.replace("event:","").trim():Xt.startsWith("data:")&&(Oe+=Xt.replace("data:","").trim());if(!Oe)continue;let Lt;try{Lt=JSON.parse(Oe)}catch(Xt){t({type:"error",error:Xt instanceof Error?Xt:new Error("Failed to parse chat stream payload")});continue}let jt=$e!=="message"?$e:(dn=Lt.type)!=null?dn:"message";if((wr=this.onSSEEvent)==null||wr.call(this,jt,Lt),this.parseSSEEvent){x.current=m;let Xt=await this.handleCustomSSEEvent(Lt,t,x,u,c,M);if(x.current&&x.current!==m&&(m=x.current),Xt)continue}Je.push(jt,Lt),ue()}}Je.flushPending(),ue(),Je.destroy()}};function ja(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Js(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ka="[Image]";function Vi(n){return{type:"text",text:n}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],of=["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"],Gr=[...yu,...of];function sf(n){return yu.includes(n)||n.startsWith("image/")}function Ga(n){return sf(n.type)}async function bu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ga(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 vu(n,e=Gr,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 af(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function xu(n,e){let t=af(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"}ji();var wu=16e3,lf=24e3,cf=4096,df=1380533830;function pf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===df?new Uint8Array(n,44):new Uint8Array(n)}function uf(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 Ys=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:wu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let g=window.AudioContext||window.webkitAudioContext,f=new g({sampleRate:wu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ms(lf);if(o!==this.callGeneration){u.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${uf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(m,["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 M=x.code?` (code ${x.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,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(cf,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 g=0;g<d.length;g++){let f=Math.max(-1,Math.min(1,d[g]));c[g]=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=pf(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 Oo=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 gs(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(n.runtype);case"browser":if(!Oo.isSupported())throw new Error("Browser speech recognition not supported");return new Oo(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 Cu(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return gs({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return gs({type:"runtype",runtype:n.runtype});if(Oo.isSupported())return gs({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ki(n){try{return Cu(n),!0}catch{return!1}}function Qa(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 fs=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):Qa(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,g;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(g=t.onError)==null||g.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 Zs=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 Gi(n){if(!n)return"";let e=mf(n);return Au(e!==null?e:n)}function mf(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 Au(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
- `),e=e.replace(/\n{2,}/g,`
14
- `),e.trim()}var ku=null;var Qi=()=>ku?ku():Promise.resolve().then(()=>(Eu(),Mu));var hf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function yf(n,e){return hf.some(t=>n[t]!==e[t])}function Lu(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}
11
+ `);a=(An=we.pop())!=null?An:"";for(let Fe of we){let at=Fe.split(`
12
+ `),dt="message",rt="";for(let At of at)At.startsWith("event:")?dt=At.replace("event:","").trim():At.startsWith("data:")&&(rt+=At.replace("data:","").trim());if(!rt)continue;let Et;try{Et=JSON.parse(rt)}catch(At){e({type:"error",error:At instanceof Error?At:new Error("Failed to parse chat stream payload")});continue}let j=dt!=="message"?dt:(Ve=Et.type)!=null?Ve:"message";if((Nt=this.onSSEEvent)==null||Nt.call(this,j,Et),this.parseSSEEvent){x.current=m;let At=await this.handleCustomSSEEvent(Et,e,x,u,c,T);if(x.current&&x.current!==m&&(m=x.current),At)continue}if(qe||(vu(j)?(Ie=!0,qe=!0):(j==="agent_start"||j==="flow_start"||j==="step_start")&&(Ie=!1,qe=!0)),Ie){for(let At of Kt.push(j,Et))Ke.push(At);pe();continue}Qe.push(j,Et),pe()}}Qe.flushPending(),pe(),Qe.destroy()}};function Qa(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function Js(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var Xa="[Image]";function Gi(n){return{type:"text",text:n}}var Cu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],pf=["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"],Gr=[...Cu,...pf];function uf(n){return Cu.includes(n)||n.startsWith("image/")}function Ja(n){return uf(n.type)}async function Au(n){return new Promise((t,e)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ja(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>e(new Error("Failed to read file")),r.readAsDataURL(n)})}function Su(n,t=Gr,e=10*1024*1024){return t.includes(n.type)?n.size>e?{valid:!1,error:`File too large. Maximum size: ${Math.round(e/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function mf(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function Tu(n,t){let e=mf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||e||"FILE"}Qi();var Eu=16e3,gf=24e3,ff=4096,hf=1380533830;function bf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===hf?new Uint8Array(n,44):new Uint8Array(n)}function yf(n){var r;let t=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ys=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,e=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!e)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:Eu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let g=window.AudioContext||window.webkitAudioContext,f=new g({sampleRate:Eu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new us(gf);if(o!==this.callGeneration){u.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${yf(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(m,["runtype.bearer",e]);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 T=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),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(t,e,r,o){let s=t.createMediaStreamSource(e);this.sourceNode=s;let a=t.createScriptProcessor(ff,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 g=0;g<d.length;g++){let f=Math.max(-1,Math.min(1,d[g]));c[g]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,e){var o,s;if(e!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,e);return}let r;try{r=JSON.parse(t.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(t,e){if(e!==this.callGeneration||!this.playback)return;let r=bf(t);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(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(e=>e(t))}emitError(t){this.errorCallbacks.forEach(e=>e(t))}emitTranscript(t,e,r){this.transcriptCallbacks.forEach(o=>o(t,e,r))}emitMetrics(t){this.metricsCallbacks.forEach(e=>e(t))}};var _o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,e;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=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((e=this.config)==null?void 0:e.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(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ms(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(n.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(n.browser||{});case"custom":{let t=n.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let e=typeof t=="function"?t():t;if(!e||typeof e.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return e}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function Mu(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ms({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ms({type:"runtype",runtype:n.runtype});if(_o.isSupported())return ms({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Xi(n){try{return Mu(n),!0}catch{return!1}}function Ya(n){var e;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=n.find(s=>s.name===r);if(o)return o}return(e=n.find(r=>r.lang.startsWith("en")))!=null?e:n[0]}var gs=class n{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,e){var a;if(!n.isSupported()){(a=e.onError)==null||a.call(e,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Ya(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=e.onEnd)==null?void 0:i.call(e)},o.onerror=i=>{var c,g;let d=i.error;d==="canceled"||d==="interrupted"?(c=e.onEnd)==null||c.call(e):(g=e.onError)==null||g.call(e,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=e.onStart)==null||i.call(e)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Zs=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,e;return(e=(t=this.engine)==null?void 0:t.supportsPause)!=null?e:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,e){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,e)}async play(t,e){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"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(e,{onStart:()=>{r===this.generation&&this.set(t,"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 t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,e;this.stop(),(e=(t=this.engine)==null?void 0:t.destroy)==null||e.call(t),this.engine=null,this.listeners.clear()}set(t,e){this.activeId=e==="idle"?null:t,this.state=e;for(let r of this.listeners)r(this.activeId,this.state)}};function Ji(n){if(!n)return"";let t=vf(n);return ku(t!==null?t:n)}function vf(n){let t=n.trim(),e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(e&&(t=e[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function ku(n){if(!n)return"";let t=n;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
+ `),t=t.replace(/\n{2,}/g,`
14
+ `),t.trim()}var Ru=null;var Yi=()=>Ru?Ru():Promise.resolve().then(()=>(Wu(),Pu));var Cf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Af(n,t){return Cf.some(e=>n[e]!==t[e])}function Bu(n,t){let e=n instanceof Error?n:new Error(String(n));if(typeof t=="string")return t;if(typeof t=="function")return t(e);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 e.message?`${r}
15
15
 
16
- _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]}),Pu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,Iu=n=>zs(n)||n===Kr,Ya=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 Zs(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,g,f;if(e.type==="message"){this.upsertMessage(e.message);let u=e.message.toolCall,m=!!(u!=null&&u.name)&&(zs(u.name)||u.name===Kr&&((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&&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 u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":u||(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=(g=this.callbacks).onError)==null||f.call(g,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 Xs(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||Qi().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 Ki((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=fs.isSupported()?new fs({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,g=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&g)return Qi().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:m})=>{let v=new u({host:d,agentId:c,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&t?new m(v,t,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&t)return g&&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=gs(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 g=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=g.id}if(c){this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.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 g=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=g.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,g,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:((g=e.browser)==null?void 0:g.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(!yf(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 Xs(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:g,rawContent:f}=e,m={id:a!=null?a:t==="user"?ja():t==="assistant"?Js():`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},...g!==void 0&&{voiceProcessing:g},...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 t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:f=!1,voiceProcessing:u,rawContent:m}=r,x={id:d!=null?d:o==="user"?ja():o==="assistant"?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};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,g,f,u,m;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=ja(),s=Js(),a={id:o,role:"user",content:r||Ka,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 M=Lu(v,this.config.errorMessage);if(M){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(g=this.callbacks).onError)==null||f.call(g,v):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Js();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 g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let f=Lu(c,this.config.errorMessage);if(f){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(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 g,f,u,m,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:(g=a==null?void 0:a.createdAt)!=null?g: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 M=null;if(x instanceof Response){if(!x.ok){let E=await x.json().catch(()=>null);throw new Error((u=E==null?void 0:E.error)!=null?u:`Approval request failed: ${x.status}`)}M=x.body}else x instanceof ReadableStream&&(M=x);M?await this.connectStream(M,{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 M=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(v=(m=this.callbacks).onError)==null||v.call(m,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 g,f,u,m,v,x,M,E,k,N,P,W;let r=this.messages.find(C=>C.id===e.id);if(((g=r==null?void 0:r.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(u=e.toolCall)==null?void 0:u.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,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 B=typeof((M=I[0])==null?void 0:M.question)=="string"?I[0].question:"";B&&(a={[B]:t})}}this.markAskUserQuestionResolved(e,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(k=e.toolCall)==null?void 0:k.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,B])=>`${I}: ${Array.isArray(B)?B.join(", "):B}`).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,B)=>{let D=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!D)return;let T=C[D],q=Array.isArray(T)?T.join(", "):typeof T=="string"?T:"";this.appendMessage({id:`ask-user-q-${i}-${B}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${B}`,role:"user",content:q||"*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=(P=this.callbacks).onError)==null||W.call(P,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)!==Kr)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,g,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async u=>{var W,C,I,B,D,T,q;let m=(W=u.toolCall)==null?void 0:W.name,v=(C=u.toolCall)==null?void 0:C.id;if(!m||!v)return null;let x=`${e}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(x),r.push(x);let M=this.markWebMcpToolRunning(u),E=(B=(I=u.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?B:m;if(m===Kr)return{dedupeKey:x,resumeKey:E,output:_i(),toolMessage:u,startedAt:M,completedAt:Date.now()};let k=new AbortController;this.webMcpResolveControllers.add(k),o.push(k);let N=this.client.executeWebMcpToolCall(m,(D=u.toolCall)==null?void 0:D.args,k.signal),P;if(!N)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await N}catch(z){let re=z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")||z.message.includes("abort"));return re||(q=(T=this.callbacks).onError)==null||q.call(T,z instanceof Error?z:new Error(String(z))),this.markWebMcpToolComplete(u,ea(re?"Aborted by cancel()":Pu(z)),M),this.webMcpInflightKeys.delete(x),null}return k.signal.aborted?(this.markWebMcpToolComplete(u,ea("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:E,output:P,toolMessage:u,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let u={};for(let v of i)u[v.resumeKey]=v.output;let m=await this.client.resumeFlow(e,u,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.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)===Kr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(g=this.callbacks).onError)==null||f.call(g,u instanceof Error?u:new Error(String(u)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ea("Aborted by cancel()"),v.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,x,M,E,k,N,P,W,C,I,B,D;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(x=e.toolCall)==null?void 0:x.name,o=(M=e.toolCall)==null?void 0:M.id;if(!t){(k=(E=this.callbacks).onError)==null||k.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let T=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(T)||this.webMcpResolvedKeys.has(T))return;this.webMcpInflightKeys.add(T);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(T)}catch(q){(P=(N=this.callbacks).onError)==null||P.call(N,q instanceof Error?q:new Error(String(q)))}finally{this.webMcpInflightKeys.delete(T)}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===Kr,g=(W=e.toolCall)==null?void 0:W.args,f=c?null:this.client.executeWebMcpToolCall(r,g,d),u="execute",m=a;try{let T;if(c?T=_i():f?T=await f:T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,ea("Aborted by cancel()"),a);return}let q=(I=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?I:r;u="resume",await this.resumeWithToolOutput(t,q,T,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,T,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(T){let q=T instanceof Error&&(T.name==="AbortError"||T.message.includes("aborted")||T.message.includes("abort"));(u==="execute"||q||d.aborted)&&this.markWebMcpToolComplete(e,ea(q||d.aborted?"Aborted by cancel()":Pu(T)),a),q||(D=(B=this.callbacks).onError)==null||D.call(B,T instanceof Error?T:new Error(String(T)))}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=Gi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Qa(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Gi(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 g,f,u,m,v,x,M,E,k,N,P,W,C,I,B;if(s!==r)return o;let a={...o,...t};if(((g=o.agentMetadata)==null?void 0:g.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={...(u=a.agentMetadata)!=null?u:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let D=o.approval,T=t.approval;a.approval={...D,...T,executionId:T.executionId||D.executionId,toolName:T.toolName||D.toolName,description:T.description||D.description,toolType:(m=T.toolType)!=null?m:D.toolType,reason:(v=T.reason)!=null?v:D.reason,parameters:(x=T.parameters)!=null?x:D.parameters}}let i=(M=t.toolCall)==null?void 0:M.name,d=(E=t.agentMetadata)==null?void 0:E.executionId,c=(k=t.toolCall)==null?void 0:k.id;if(i&&Iu(i)&&d&&c&&((N=t.agentMetadata)==null?void 0:N.awaitingLocalTool)===!0){let D=`${d}:${c}`,T=this.webMcpInflightKeys.has(D),q=this.webMcpResolvedKeys.has(D),z=(P=o.toolCall)==null?void 0:P.name,re=((W=o.agentMetadata)==null?void 0:W.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&z!==void 0&&Iu(z)&&((I=o.toolCall)==null?void 0:I.status)==="complete";(T||q||re)&&(a.agentMetadata={...(B=a.agentMetadata)!=null?B:{},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 bf,ArrowDown as vf,ArrowUp as xf,ArrowUpRight as wf,Bot as Cf,ChevronDown as Af,ChevronUp as Sf,ChevronRight as Tf,ChevronLeft as Mf,Check as Ef,Clipboard as kf,ClipboardCopy as Lf,Copy as Pf,File as If,FileCode as Wf,FileSpreadsheet as Rf,FileText as Hf,ImagePlus as Bf,Loader as Df,LoaderCircle as Nf,Mic as Ff,Paperclip as Of,RefreshCw as _f,Search as $f,Send as Uf,ShieldAlert as qf,ShieldCheck as zf,ShieldX as Vf,Square as jf,ThumbsDown as Kf,ThumbsUp as Gf,Upload as Qf,Volume2 as Xf,X as Jf,User as Yf,Mail as Zf,Phone as eh,Calendar as th,Clock as nh,Building as rh,MapPin as oh,Lock as sh,Key as ah,CreditCard as ih,AtSign as lh,Hash as ch,Globe as dh,Link as ph,CircleCheck as uh,CircleX as mh,TriangleAlert as gh,Info as fh,Ban as hh,Shield as yh,ArrowLeft as bh,ArrowRight as vh,ExternalLink as xh,Ellipsis as wh,EllipsisVertical as Ch,Menu as Ah,House as Sh,Plus as Th,Minus as Mh,Pencil as Eh,Trash as kh,Trash2 as Lh,Save as Ph,Download as Ih,Share as Wh,Funnel as Rh,Settings as Hh,RotateCw as Bh,Maximize as Dh,Minimize as Nh,ShoppingCart as Fh,ShoppingBag as Oh,Package as _h,Truck as $h,Tag as Uh,Gift as qh,Receipt as zh,Wallet as Vh,Store as jh,DollarSign as Kh,Percent as Gh,Play as Qh,Pause as Xh,VolumeX as Jh,Camera as Yh,Image as Zh,Film as ey,Headphones as ty,MessageCircle as ny,MessageSquare as ry,Bell as oy,Heart as sy,Star as ay,Eye as iy,EyeOff as ly,Bookmark as cy,CalendarDays as dy,History as py,Timer as uy,Folder as my,FolderOpen as gy,Files as fy,Sparkles as hy,Zap as yy,Sun as by,Moon as vy,Flag as xy,Monitor as wy,Smartphone as Cy}from"lucide";var Ay={activity:bf,"arrow-down":vf,"arrow-up":xf,"arrow-up-right":wf,bot:Cf,"chevron-down":Af,"chevron-up":Sf,"chevron-right":Tf,"chevron-left":Mf,check:Ef,clipboard:kf,"clipboard-copy":Lf,copy:Pf,file:If,"file-code":Wf,"file-spreadsheet":Rf,"file-text":Hf,"image-plus":Bf,loader:Df,"loader-circle":Nf,mic:Ff,paperclip:Of,"refresh-cw":_f,search:$f,send:Uf,"shield-alert":qf,"shield-check":zf,"shield-x":Vf,square:jf,"thumbs-down":Kf,"thumbs-up":Gf,upload:Qf,"volume-2":Xf,x:Jf,user:Yf,mail:Zf,phone:eh,calendar:th,clock:nh,building:rh,"map-pin":oh,lock:sh,key:ah,"credit-card":ih,"at-sign":lh,hash:ch,globe:dh,link:ph,"circle-check":uh,"circle-x":mh,"triangle-alert":gh,info:fh,ban:hh,shield:yh,"arrow-left":bh,"arrow-right":vh,"external-link":xh,ellipsis:wh,"ellipsis-vertical":Ch,menu:Ah,house:Sh,plus:Th,minus:Mh,pencil:Eh,trash:kh,"trash-2":Lh,save:Ph,download:Ih,share:Wh,funnel:Rh,settings:Hh,"rotate-cw":Bh,maximize:Dh,minimize:Nh,"shopping-cart":Fh,"shopping-bag":Oh,package:_h,truck:$h,tag:Uh,gift:qh,receipt:zh,wallet:Vh,store:jh,"dollar-sign":Kh,percent:Gh,play:Qh,pause:Xh,"volume-x":Jh,camera:Yh,image:Zh,film:ey,headphones:ty,"message-circle":ny,"message-square":ry,bell:oy,heart:sy,star:ay,eye:iy,"eye-off":ly,bookmark:cy,"calendar-days":dy,history:py,timer:uy,folder:my,"folder-open":gy,files:fy,sparkles:hy,zap:yy,sun:by,moon:vy,flag:xy,monitor:wy,smartphone:Cy},Ae=(n,e=24,t="currentColor",r=2)=>{let o=Ay[n];return o?Sy(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 Sy(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,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}),o}var Za={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function Ty(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function My(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 ta=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Za.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Za.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Za.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:Za.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 g=vu(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let f=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await bu(c),u=Ga(c)?URL.createObjectURL(c):null,m={id:Ty(),file:c,previewUrl:u,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 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=Ga(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=My(e.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=xu(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=Ae("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 Wu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function na(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];Wu(s)&&Wu(o)?t[r]=na(s,o):t[r]=o}return t}var Qr="min(440px, calc(100vw - 24px))",Hu="440px",Ey={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:Qr,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)"},Ot={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ey,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 Ru(n,e){if(!(!n&&!e))return n?e?na(n,e):n:e}function Bu(n){var e,t,r,o,s,a,i,d,c,g,f,u,m,v,x,M,E,k,N,P,W;return n?{...Ot,...n,theme:Ru(Ot.theme,n.theme),darkTheme:Ru(Ot.darkTheme,n.darkTheme),launcher:{...Ot.launcher,...n.launcher,dock:{...(e=Ot.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Ot.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Ot.copy,...n.copy},sendButton:{...Ot.sendButton,...n.sendButton},statusIndicator:{...Ot.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ot.voiceRecognition,...n.voiceRecognition},features:(()=>{var oe,G,se,ge,pe,j,ae,Ie,ee,Z;let C=(oe=Ot.features)==null?void 0:oe.artifacts,I=(G=n.features)==null?void 0:G.artifacts,B=(se=Ot.features)==null?void 0:se.scrollToBottom,D=(ge=n.features)==null?void 0:ge.scrollToBottom,T=(pe=Ot.features)==null?void 0:pe.scrollBehavior,q=(j=n.features)==null?void 0:j.scrollBehavior,z=(ae=Ot.features)==null?void 0:ae.streamAnimation,re=(Ie=n.features)==null?void 0:Ie.streamAnimation,ke=(ee=Ot.features)==null?void 0:ee.askUserQuestion,Ve=(Z=n.features)==null?void 0:Z.askUserQuestion,be=C===void 0&&I===void 0?void 0:{...C,...I,layout:{...C==null?void 0:C.layout,...I==null?void 0:I.layout}},He=B===void 0&&D===void 0?void 0:{...B,...D},Fe=T===void 0&&q===void 0?void 0:{...T,...q},Se=z===void 0&&re===void 0?void 0:{...z,...re},xe=ke===void 0&&Ve===void 0?void 0:{...ke,...Ve,styles:{...ke==null?void 0:ke.styles,...Ve==null?void 0:Ve.styles}};return{...Ot.features,...n.features,...He!==void 0?{scrollToBottom:He}:{},...Fe!==void 0?{scrollBehavior:Fe}:{},...be!==void 0?{artifacts:be}:{},...Se!==void 0?{streamAnimation:Se}:{},...xe!==void 0?{askUserQuestion:xe}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Ot.suggestionChips,suggestionChipsConfig:{...Ot.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ot.layout,...n.layout,header:{...(a=Ot.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Ot.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(g=Ot.layout)==null?void 0:g.messages)==null?void 0:f.avatar,...(m=(u=n.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Ot.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(E=(M=n.layout)==null?void 0:M.messages)==null?void 0:E.timestamp}},slots:{...(k=Ot.layout)==null?void 0:k.slots,...(N=n.layout)==null?void 0:N.slots}},markdown:{...Ot.markdown,...n.markdown,options:{...(P=Ot.markdown)==null?void 0:P.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...Ot.messageActions,...n.messageActions}}:Ot}var ky={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"}},Ly={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"}},Py={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:Qr,maxWidth:Hu,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 hs(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."))?hs(n,r):r}function Du(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=hs(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 Iy(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 Nu(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]=Nu(s,o):t[r]=o}return t}function Wy(n,e){return e?Nu(n,e):n}function _o(n,e={}){var o,s,a,i,d,c,g,f,u,m,v,x,M;let t={palette:ky,semantic:Ly,components:Py},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,...(g=n==null?void 0:n.semantic)==null?void 0:g.colors,interactive:{...t.semantic.colors.interactive,...(u=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.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,...(M=n==null?void 0:n.semantic)==null?void 0:M.typography}},components:Wy(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let E=Iy(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(k=>k.message).join(", ")}`)}if(e.plugins)for(let E of e.plugins)r=E.transform(r);return r}function Fu(n){var x,M,E,k,N,P,W,C,I,B,D,T,q,z,re,ke,Ve,be,He,Fe,Se,xe,oe,G,se,ge,pe,j,ae,Ie,ee,Z,ne,at,it,ot,Me,fe,Xe,J,ue,Ee,Je,Ke,Pe,je,bn,Wt,dn,wr,$,K,he,Ge,Ze,$e,Oe,Lt,jt,Xt,kn,V,Rt,le,we,Ne,St,rn,on,vn,Dt,nt,Bt,dt,Jt,tr,Ln,sn,Fn,Cr,vt,qn,Ar,Nr,ur,yt,xo,Sr,wo,On,Vo,Jr,Fr,Yr,Zr,Co,Ao,eo,wt,zn,Vn,Pn,Tt,nr,rr,jn,to,Or,no,Kn,Nt,In,or,ro,_r,oo,Tr,Gn;let e=Du(n),t={};for(let[ye,pt]of Object.entries(e)){let en=ye.replace(/\./g,"-");t[`--persona-${en}`]=pt.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(E=t["--persona-semantic-colors-accent"])!=null?E:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(k=t["--persona-semantic-colors-surface"])!=null?k: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"]=(P=t["--persona-semantic-colors-container"])!=null?P: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"]=(B=t["--persona-semantic-colors-border"])!=null?B:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(D=t["--persona-semantic-colors-divider"])!=null?D:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(T=t["--persona-components-voice-recording-indicator"])!=null?T:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(q=t["--persona-components-voice-recording-background"])!=null?q:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(z=t["--persona-components-voice-processing-icon"])!=null?z:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ke=t["--persona-components-approval-requested-background"])!=null?ke:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Ve=t["--persona-components-approval-requested-border"])!=null?Ve:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(be=t["--persona-components-approval-requested-text"])!=null?be:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(He=t["--persona-components-approval-requested-shadow"])!=null?He:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(Fe=t["--persona-components-approval-approve-background"])!=null?Fe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Se=t["--persona-components-approval-deny-background"])!=null?Se:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(xe=t["--persona-components-attachment-image-background"])!=null?xe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(oe=t["--persona-components-attachment-image-border"])!=null?oe:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(G=t["--persona-semantic-typography-fontFamily"])!=null?G:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(se=t["--persona-semantic-typography-fontSize"])!=null?se:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ge=t["--persona-semantic-typography-fontWeight"])!=null?ge:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(pe=t["--persona-semantic-typography-lineHeight"])!=null?pe: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"]=(j=t["--persona-palette-radius-sm"])!=null?j:"0.125rem",t["--persona-radius-md"]=(ae=t["--persona-palette-radius-md"])!=null?ae:"0.375rem",t["--persona-radius-lg"]=(Ie=t["--persona-palette-radius-lg"])!=null?Ie:"0.5rem",t["--persona-radius-xl"]=(ee=t["--persona-palette-radius-xl"])!=null?ee:"0.75rem",t["--persona-radius-full"]=(Z=t["--persona-palette-radius-full"])!=null?Z:"9999px",t["--persona-launcher-radius"]=(at=(ne=t["--persona-components-launcher-borderRadius"])!=null?ne: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"]=(ot=t["--persona-components-launcher-foreground"])!=null?ot:t["--persona-text-inverse"],t["--persona-launcher-border"]=(Me=t["--persona-components-launcher-border"])!=null?Me:t["--persona-border"],t["--persona-button-primary-bg"]=(fe=t["--persona-components-button-primary-background"])!=null?fe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Xe=t["--persona-components-button-primary-foreground"])!=null?Xe:t["--persona-text-inverse"],t["--persona-button-radius"]=(ue=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?ue:"9999px",t["--persona-panel-radius"]=(Je=(Ee=t["--persona-components-panel-borderRadius"])!=null?Ee:t["--persona-radius-xl"])!=null?Je:"0.75rem",t["--persona-panel-border"]=(Ke=t["--persona-components-panel-border"])!=null?Ke:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(je=(Pe=t["--persona-components-panel-shadow"])!=null?Pe:t["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(bn=t["--persona-components-launcher-shadow"])!=null?bn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(dn=(Wt=t["--persona-components-input-borderRadius"])!=null?Wt:t["--persona-radius-lg"])!=null?dn:"0.5rem",t["--persona-message-user-radius"]=($=(wr=t["--persona-components-message-user-borderRadius"])!=null?wr:t["--persona-radius-lg"])!=null?$:"0.5rem",t["--persona-message-assistant-radius"]=(he=(K=t["--persona-components-message-assistant-borderRadius"])!=null?K:t["--persona-radius-lg"])!=null?he:"0.5rem",t["--persona-header-bg"]=(Ge=t["--persona-components-header-background"])!=null?Ge:t["--persona-surface"],t["--persona-header-border"]=(Ze=t["--persona-components-header-border"])!=null?Ze:t["--persona-divider"],t["--persona-header-icon-bg"]=($e=t["--persona-components-header-iconBackground"])!=null?$e:t["--persona-primary"],t["--persona-header-icon-fg"]=(Oe=t["--persona-components-header-iconForeground"])!=null?Oe:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Lt=t["--persona-components-header-titleForeground"])!=null?Lt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(jt=t["--persona-components-header-subtitleForeground"])!=null?jt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Xt=t["--persona-components-header-actionIconForeground"])!=null?Xt:t["--persona-muted"];let r=(kn=n.components)==null?void 0:kn.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(V=n.components)==null?void 0:V.introCard;t["--persona-intro-card-bg"]=(Rt=t["--persona-components-introCard-background"])!=null?Rt:t["--persona-surface"],t["--persona-intro-card-radius"]=(le=t["--persona-components-introCard-borderRadius"])!=null?le:"1rem",t["--persona-intro-card-padding"]=(we=t["--persona-components-introCard-padding"])!=null?we:"1.5rem",t["--persona-intro-card-shadow"]=(St=(Ne=o==null?void 0:o.shadow)!=null?Ne:t["--persona-components-introCard-shadow"])!=null?St:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(rn=t["--persona-components-input-background"])!=null?rn:t["--persona-surface"],t["--persona-input-placeholder"]=(on=t["--persona-components-input-placeholder"])!=null?on:t["--persona-text-muted"],t["--persona-message-user-bg"]=(vn=t["--persona-components-message-user-background"])!=null?vn:t["--persona-accent"],t["--persona-message-user-text"]=(Dt=t["--persona-components-message-user-text"])!=null?Dt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(nt=t["--persona-components-message-user-shadow"])!=null?nt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Bt=t["--persona-components-message-assistant-background"])!=null?Bt:t["--persona-surface"],t["--persona-message-assistant-text"]=(dt=t["--persona-components-message-assistant-text"])!=null?dt:t["--persona-text"],t["--persona-message-assistant-border"]=(Jt=t["--persona-components-message-assistant-border"])!=null?Jt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(tr=t["--persona-components-message-assistant-shadow"])!=null?tr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(sn=(Ln=t["--persona-components-scrollToBottom-background"])!=null?Ln:t["--persona-button-primary-bg"])!=null?sn:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Cr=(Fn=t["--persona-components-scrollToBottom-foreground"])!=null?Fn:t["--persona-button-primary-fg"])!=null?Cr: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"]=(qn=t["--persona-components-scrollToBottom-size"])!=null?qn:"40px",t["--persona-scroll-to-bottom-radius"]=(ur=(Nr=(Ar=t["--persona-components-scrollToBottom-borderRadius"])!=null?Ar:t["--persona-button-radius"])!=null?Nr:t["--persona-radius-full"])!=null?ur:"9999px",t["--persona-scroll-to-bottom-shadow"]=(xo=(yt=t["--persona-components-scrollToBottom-shadow"])!=null?yt:t["--persona-palette-shadows-sm"])!=null?xo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Sr=t["--persona-components-scrollToBottom-padding"])!=null?Sr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(wo=t["--persona-components-scrollToBottom-gap"])!=null?wo:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Vo=(On=t["--persona-components-scrollToBottom-fontSize"])!=null?On:t["--persona-palette-typography-fontSize-sm"])!=null?Vo:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Jr=t["--persona-components-scrollToBottom-iconSize"])!=null?Jr:"14px",t["--persona-tool-bubble-shadow"]=(Fr=t["--persona-components-toolBubble-shadow"])!=null?Fr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Yr=t["--persona-components-reasoningBubble-shadow"])!=null?Yr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Zr=t["--persona-components-composer-shadow"])!=null?Zr:"none",t["--persona-md-inline-code-bg"]=(Co=t["--persona-components-markdown-inlineCode-background"])!=null?Co:t["--persona-container"],t["--persona-md-inline-code-color"]=(Ao=t["--persona-components-markdown-inlineCode-foreground"])!=null?Ao:t["--persona-text"],t["--persona-md-link-color"]=(wt=(eo=t["--persona-components-markdown-link-foreground"])!=null?eo: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"]=(zn=t["--persona-components-markdown-codeBlock-background"])!=null?zn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Vn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Vn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Pn=t["--persona-components-markdown-codeBlock-textColor"])!=null?Pn:"inherit",t["--persona-md-table-header-bg"]=(Tt=t["--persona-components-markdown-table-headerBackground"])!=null?Tt:t["--persona-container"],t["--persona-md-table-border-color"]=(nr=t["--persona-components-markdown-table-borderColor"])!=null?nr:t["--persona-border"],t["--persona-md-hr-color"]=(rr=t["--persona-components-markdown-hr-color"])!=null?rr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(jn=t["--persona-components-markdown-blockquote-borderColor"])!=null?jn:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(to=t["--persona-components-markdown-blockquote-background"])!=null?to:"transparent",t["--persona-md-blockquote-text-color"]=(Or=t["--persona-components-markdown-blockquote-textColor"])!=null?Or:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(no=t["--persona-components-collapsibleWidget-container"])!=null?no:t["--persona-surface"],t["--cw-surface"]=(Kn=t["--persona-components-collapsibleWidget-surface"])!=null?Kn:t["--persona-surface"],t["--cw-border"]=(Nt=t["--persona-components-collapsibleWidget-border"])!=null?Nt:t["--persona-border"],t["--persona-message-border"]=(In=t["--persona-components-message-border"])!=null?In:t["--persona-border"];let g=n.components,f=g==null?void 0:g.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 u=g==null?void 0:g.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let m=g==null?void 0:g.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=g==null?void 0:g.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,t["--persona-dropdown-bg"]=(or=t["--persona-dropdown-bg"])!=null?or:ye.copyMenuBackground),ye.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,t["--persona-dropdown-border"]=(ro=t["--persona-dropdown-border"])!=null?ro:ye.copyMenuBorder),ye.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,t["--persona-dropdown-shadow"]=(_r=t["--persona-dropdown-shadow"])!=null?_r:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(oo=t["--persona-dropdown-radius"])!=null?oo:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Tr=t["--persona-dropdown-item-hover-bg"])!=null?Tr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(t["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(t["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(t["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(t["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(t["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(t["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let pt=(Gn=hs(n,ye.toolbarBackground))!=null?Gn:ye.toolbarBackground;t["--persona-artifact-toolbar-bg"]=pt}}return t}var Ry={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"}}},Ou=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Xi=()=>{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"},Hy=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Xi()},By=n=>Hy(n),Dy=n=>_o(n),Ny=n=>{var t;let e=_o(void 0,{validate:!1});return _o({...n,palette:{...e.palette,colors:{...Ry.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},ei=n=>{let e=By(n),t=Ou(n==null?void 0:n.theme),r=Ou(n==null?void 0:n.darkTheme);return e==="dark"?Ny(na(t!=null?t:{},r!=null?r:{})):Dy(t)},Fy=n=>Fu(n),ys=(n,e)=>{let t=ei(e),r=Fy(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},_u=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Xi())});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(Xi());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 Oy}from"idiomorph";var ti=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Oy.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 ni={index:-1,draft:""};function $u(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:{...ni}}}function Uu(n,e){var t,r,o,s,a,i,d,c,g,f,u,m,v,x,M,E,k,N,P,W,C,I,B,D,T,q,z,re,ke,Ve,be,He,Fe,Se,xe,oe,G,se;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,(g=(c=n.llmContent)==null?void 0:c.length)!=null?g:0,(u=(f=n.approval)==null?void 0:f.status)!=null?u:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(M=(x=n.toolCall)==null?void 0:x.name)!=null?M:"",(N=(k=(E=n.toolCall)==null?void 0:E.chunks)==null?void 0:k.length)!=null?N:0,(I=(C=(W=(P=n.toolCall)==null?void 0:P.chunks)==null?void 0:W[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?I:"",typeof((B=n.toolCall)==null?void 0:B.args)=="string"?n.toolCall.args.length:(D=n.toolCall)!=null&&D.args?JSON.stringify(n.toolCall.args).length:0,(z=(q=(T=n.reasoning)==null?void 0:T.chunks)==null?void 0:q.length)!=null?z:0,(be=(Ve=(ke=(re=n.reasoning)==null?void 0:re.chunks)==null?void 0:ke[n.reasoning.chunks.length-1])==null?void 0:Ve.length)!=null?be:0,(xe=(Se=(Fe=(He=n.reasoning)==null?void 0:He.chunks)==null?void 0:Fe[n.reasoning.chunks.length-1])==null?void 0:Se.slice(-32))!=null?xe:"",(G=(oe=n.contentParts)==null?void 0:oe.length)!=null?G:0,(se=n.stopReason)!=null?se:"",e].join("\0")}function qu(){return new Map}function zu(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Vu(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function ju(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function ri(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Xr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function $o(n,e){return Xr(n)-n.scrollTop<=e}function oi(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,g=t-r;return a||Math.abs(g)<s?{action:"none",delta:g,nextLastScrollTop:t}:!e&&o&&(!c||g>0)?{action:"resume",delta:g,nextLastScrollTop:t}:e&&i&&g<0?{action:"pause",delta:g,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:g,nextLastScrollTop:t}:{action:"none",delta:g,nextLastScrollTop:t}}function si(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 Ku(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function Gu(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 Qu(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var Tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Mn=1e5,bo=Mn+1;var ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},_y=["pre","code","a","script","style"],ai=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:ra.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:ra.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:ra.speed,duration:(o=n==null?void 0:n.duration)!=null?o:ra.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:ra.buffer}},$y=[{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 n of $y)Ju.set(n.name,n);var oa=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Ju.get(n))!=null?r:null},ii=(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(`
17
- `);return s<0?"":n.slice(0,s)}return n},Uy=(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},qy=(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},Ji=/\s/,zy=(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},Vy=(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(Ji.test(s[i])){let c=i;for(;c<s.length&&Ji.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 g=i;for(;g<s.length&&!Ji.test(s[g]);)c.appendChild(Uy(r,s[g],e,t.value)),t.value+=1,g+=1;a.appendChild(c),i=g}o.replaceChild(a,n)},jy=(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(qy(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},sa=(n,e,t,r)=>{var f,u;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:_y).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)zy(d,s)||i.push(d),d=a.nextNode();let c={value:(u=r==null?void 0:r.startIndex)!=null?u:0},g=e==="char"?Vy:jy;for(let m of i)g(m,t,c);return o.innerHTML},li=(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},aa=(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},Xu=new WeakMap,Ky=(n,e)=>{var s;if(!n.styles)return;let t=Xu.get(e);if(t||(t=new Set,Xu.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)},Yi=new WeakMap,Gy=(n,e)=>{if(!n.onAttach)return;let t=Yi.get(e);if(t||(t=new Map,Yi.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},Yu=n=>{let e=Yi.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Zi=(n,e)=>{Ky(n,e),Gy(n,e)};function el(n,e=Mn){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 ia=0,vo=null;function tl(n=document){var t;if(ia++,ia===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;vo={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,ia=Math.max(0,ia-1),ia===0&&vo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=vo.originalOverflow,o.style.position=vo.originalPosition,o.style.top=vo.originalTop,o.style.width=vo.originalWidth,s.scrollTo(0,vo.scrollY),vo=null}}}var la={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},wn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},ca=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},vr=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:la.side,width:(o=e==null?void 0:e.width)!=null?o:la.width,animate:(s=e==null?void 0:e.animate)!=null?s:la.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:la.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:la.maxHeight}};var xr={"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 Qy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ci=(n,e={})=>{var M,E,k,N,P,W;let{showClose:t=!0,wrapperClassName:r=Qy,buttonSize:o,iconSize:s="28px"}=e,a=(M=n==null?void 0:n.launcher)!=null?M:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=b("div",r),c=(k=a.closeButtonTooltipText)!=null?k:"Close chat",g=(N=a.closeButtonShowTooltip)!=null?N:!0,f=(P=a.closeButtonIconName)!=null?P:"x",u=(W=a.closeButtonIconText)!=null?W:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=kt("button",{className:Vs("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:t?void 0:"none",color:a.closeButtonColor||Nn.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}}),x=Ae(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=u,d.appendChild(v),g&&c){let C=null,I=()=>{if(C)return;let D=v.ownerDocument,T=D.body;if(!T)return;C=Dr(D,"div","persona-clear-chat-tooltip"),C.textContent=c;let q=Dr(D,"div");q.className="persona-clear-chat-tooltip-arrow",C.appendChild(q);let z=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(bo),C.style.left=`${z.left+z.width/2}px`,C.style.top=`${z.top-8}px`,C.style.transform="translate(-50%, -100%)",T.appendChild(C)},B=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",B),v.addEventListener("focus",I),v.addEventListener("blur",B),d._cleanupTooltip=()=>{B(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",B),v.removeEventListener("focus",I),v.removeEventListener("blur",B)}}return{button:v,wrapper:d}},Xy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",di=(n,e={})=>{var C,I,B,D,T,q,z,re,ke,Ve,be,He,Fe;let{wrapperClassName:t=Xy,buttonSize:r,iconSize:o="20px"}=e,a=(I=((C=n==null?void 0:n.launcher)!=null?C:{}).clearChat)!=null?I:{},i=(B=r!=null?r:a.size)!=null?B:"32px",d=(D=a.iconName)!=null?D:"refresh-cw",c=(T=a.iconColor)!=null?T:"",g=(q=a.backgroundColor)!=null?q:"",f=(z=a.borderWidth)!=null?z:"",u=(re=a.borderColor)!=null?re:"",m=(ke=a.borderRadius)!=null?ke:"",v=(Ve=a.paddingX)!=null?Ve:"",x=(be=a.paddingY)!=null?be:"",M=(He=a.tooltipText)!=null?He:"Clear chat",E=(Fe=a.showTooltip)!=null?Fe:!0,k=b("div",t),N=!!(f||u),P=kt("button",{className:Vs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"hover:persona-bg-gray-100",!N&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:c||Nn.actionIconColor,backgroundColor:g||void 0,border:N?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),W=Ae(d,o,"currentColor",1);if(W&&(W.style.display="block",P.appendChild(W)),k.appendChild(P),E&&M){let Se=null,xe=()=>{if(Se)return;let G=P.ownerDocument,se=G.body;if(!se)return;Se=Dr(G,"div","persona-clear-chat-tooltip"),Se.textContent=M;let ge=Dr(G,"div");ge.className="persona-clear-chat-tooltip-arrow",Se.appendChild(ge);let pe=P.getBoundingClientRect();Se.style.position="fixed",Se.style.zIndex=String(bo),Se.style.left=`${pe.left+pe.width/2}px`,Se.style.top=`${pe.top-8}px`,Se.style.transform="translate(-50%, -100%)",se.appendChild(Se)},oe=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};k.addEventListener("mouseenter",xe),k.addEventListener("mouseleave",oe),P.addEventListener("focus",xe),P.addEventListener("blur",oe),k._cleanupTooltip=()=>{oe(),k.removeEventListener("mouseenter",xe),k.removeEventListener("mouseleave",oe),P.removeEventListener("focus",xe),P.removeEventListener("blur",oe)}}return{button:P,wrapper:k}};var Nn={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))"},Uo=n=>{var W,C,I,B,D,T,q,z,re,ke,Ve,be,He,Fe,Se,xe;let{config:e,showClose:t=!0}=n,r=kt("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=(B=o.headerIconHidden)!=null?B:!1,d=o.headerIconName,c=kt("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,G=Ae(d,oe*.6,"currentColor",1);G?c.replaceChildren(G):c.textContent=(T=(D=e==null?void 0:e.launcher)==null?void 0:D.agentIconText)!=null?T:"\u{1F4AC}"}else if((q=e==null?void 0:e.launcher)!=null&&q.iconUrl){let oe=b("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=(re=(z=e==null?void 0:e.launcher)==null?void 0:z.agentIconText)!=null?re:"\u{1F4AC}";let g=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=kt("span",{className:"persona-text-base persona-font-semibold",text:(Ve=(ke=e==null?void 0:e.launcher)==null?void 0:ke.title)!=null?Ve:"Chat Assistant",style:{color:Nn.titleColor}}),u=kt("span",{className:"persona-text-xs",text:(He=(be=e==null?void 0:e.launcher)==null?void 0:be.subtitle)!=null?He:"Here to help you get answers fast",style:{color:Nn.subtitleColor}});g.append(f,u),i?r.append(g):r.append(c,g);let m=(Fe=o.clearChat)!=null?Fe:{},v=(Se=m.enabled)!=null?Se:!0,x=(xe=m.placement)!=null?xe:"inline",M=null,E=null;if(v){let G=di(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=G.button,E=G.wrapper,x==="top-right"&&(E.style.right="48px"),x==="inline"&&r.appendChild(E)}let k=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:P}=ci(e,{showClose:t,wrapperClassName:k});return a!=="top-right"&&r.appendChild(P),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:u,closeButton:N,closeButtonWrapper:P,clearChatButton:M,clearChatButtonWrapper:E}},da=(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 bs(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(bo)):(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 v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let M=Ae(m.icon,16,"currentColor",1.5);M&&v.appendChild(M)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",M=>{M.stopPropagation(),g(),t(m.id)}),a.appendChild(v)}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=v=>{!a.contains(v.target)&&!r.contains(v.target)&&g()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function g(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():g()}function u(){g(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:g,toggle:f,destroy:u}}function En(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=Ae(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[g,f]of Object.entries(i))d.setAttribute(g,f);return d}function nl(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 g=b("button",c);if(g.type="button",g.setAttribute("aria-label",t),e){let u=Ae(e,s!=null?s:14,"currentColor",2);u&&g.appendChild(u)}let f=b("span");if(f.textContent=t,g.appendChild(f),i&&g.addEventListener("click",i),d)for(let[u,m]of Object.entries(d))g.setAttribute(u,m);return g}function Zu(n){var m,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 g=b("span","persona-combo-btn-label");g.textContent=e,c.appendChild(g);let f=Ae(t,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=(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,M;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(M=d.border)!=null?M:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let u=bs({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(u.element),c.addEventListener("click",x=>{x.stopPropagation();let M=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),u.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{g.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),u.show()},close:()=>{c.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let x=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),c.remove()}}}var Jy=n=>{var r;let e=Uo({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 Yy(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=Ae(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=bs({items:a.menuItems,onSelect:g=>t==null?void 0:t(g),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",g=>{g.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var Zy=n=>{var k,N,P,W,C,I,B,D,T;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(k=e==null?void 0:e.launcher)!=null?k:{},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,g;if(d)c=Zu({label:(N=a.title)!=null?N:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Nn.titleColor,g=(P=c.querySelector(".persona-combo-btn-label"))!=null?P:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=b("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Nn.titleColor,g.textContent=(W=a.title)!=null?W:"Chat Assistant",c.appendChild(g),Yy(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 z=o.onTitleClick;c.addEventListener("click",re=>{re.target.closest("button")||z()}),c.addEventListener("keydown",re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),z())})}let q=o==null?void 0:o.titleRowHover;q&&(c.style.borderRadius=(I=q.borderRadius)!=null?I:"10px",c.style.padding=(B=q.padding)!=null?B:"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 z,re;c.style.backgroundColor=(z=q.background)!=null?z:"",c.style.borderColor=(re=q.border)!=null?re:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(D=a.closeButtonSize)!=null?D:"32px",u=b("div",""),m=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");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||Nn.actionIconColor;let v=(T=a.closeButtonIconName)!=null?T:"x",x=Ae(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),u.appendChild(m),i.appendChild(u);let M=b("div");M.style.display="none";let E=b("span");return E.style.display="none",{header:i,iconHolder:M,headerTitle:g,headerSubtitle:E,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},em={default:Jy,minimal:Zy},eb=n=>{var e;return(e=em[n])!=null?e:em.default},pi=(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}),g=b("div");g.style.display="none";let f=b("span"),u=b("span"),m=b("button");m.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:g,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=eb(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 ui=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}},mi=n=>{var W,C,I,B,D,T,q,z,re,ke,Ve,be;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=(B=e.stopIconName)!=null?B:"square",a=(D=e.tooltipText)!=null?D:"Send message",i=(T=e.stopTooltipText)!=null?T:"Stop generating",d=(z=(q=n==null?void 0:n.copy)==null?void 0:q.sendButtonLabel)!=null?z:"Send",c=(ke=(re=n==null?void 0:n.copy)==null?void 0:re.stopButtonLabel)!=null?ke:"Stop",g=(Ve=e.showTooltip)!=null?Ve:!1,f=(be=e.size)!=null?be:"40px",u=e.backgroundColor,m=e.textColor,v=b("div","persona-send-button-wrapper"),x=kt("button",{className:Vs("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&&!u&&"persona-bg-persona-primary",!t&&!m&&"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?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&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}}),M=null,E=null;if(t){let He=parseFloat(f)||24,Fe=(m==null?void 0:m.trim())||"currentColor";o?(M=Ae(o,He,Fe,2),M?x.appendChild(M):x.textContent=r):x.textContent=r,E=Ae(s,He,Fe,2)}else x.textContent=d;let k=null;g&&a&&(k=b("div","persona-send-button-tooltip"),k.textContent=a,v.appendChild(k)),x.setAttribute("aria-label",a),v.appendChild(x);let N="send";return{button:x,wrapper:v,setMode:He=>{if(He===N)return;N=He;let Fe=He==="stop"?i:a;if(x.setAttribute("aria-label",Fe),k&&(k.textContent=Fe),t){if(M&&E){let Se=He==="stop"?E:M;x.replaceChildren(Se)}}else x.textContent=He==="stop"?c:d}}},gi=n=>{var k,N,P,W,C,I,B,D,T,q,z,re;let e=(k=n==null?void 0:n.voiceRecognition)!=null?k:{};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=(P=n==null?void 0:n.sendButton)==null?void 0:P.size)!=null?W:"40px",i=(C=e.iconName)!=null?C:"mic",d=(I=e.iconSize)!=null?I:a,c=parseFloat(d)||24,g=(D=e.backgroundColor)!=null?D:(B=n==null?void 0:n.sendButton)==null?void 0:B.backgroundColor,f=(q=e.iconColor)!=null?q:(T=n==null?void 0:n.sendButton)==null?void 0:T.textColor,u=b("div","persona-send-button-wrapper"),m=kt("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: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}}),x=Ae(i,c,f||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",u.appendChild(m);let M=(z=e.tooltipText)!=null?z:"Start voice recognition";if(((re=e.showTooltip)!=null?re:!1)&&M){let ke=b("div","persona-send-button-tooltip");ke.textContent=M,u.appendChild(ke)}return{button:m,wrapper:u}},fi=n=>{var v,x,M,E,k,N,P,W;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(M=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?M:"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=((E=e.allowedTypes)!=null?E:Gr).join(","),o.multiple=((k=e.maxFiles)!=null?k: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"),g=kt("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":(P=e.buttonTooltipText)!=null?P:"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"}});g.addEventListener("mouseenter",()=>{g.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="transparent"});let f=Ae(s,d,"currentColor",1.5);f?g.appendChild(f):g.textContent="\u{1F4CE}",g.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(g);let u=(W=e.buttonTooltipText)!=null?W:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=u,c.appendChild(m),{button:g,wrapper:c,input:o,previewsContainer:r}},hi=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},yi=()=>kt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var bi=n=>{var v,x,M,E,k,N;let{config:e}=n,t=kt("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=yi(),o=kt("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}=ui(e);a();let i=mi(e),d=gi(e),c=fi(e),g=hi(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=kt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&u.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(u,m),o.append(f),o.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(c==null?void 0:c.button)&&P.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,g),{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:g,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(k=c==null?void 0:c.input)!=null?k:null,attachmentPreviewsContainer:(N=c==null?void 0:c.previewsContainer)!=null?N:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var tm=()=>{let n=kt("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=Ae("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=Ae("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},nm=n=>{var v,x,M,E,k,N;let{config:e}=n,t=kt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=yi();r.style.display="none";let o=hi(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ui(e);s.style.maxHeight="100px",a();let i=mi(e),d=gi(e),c=fi(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let g=kt("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 u=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),g.addEventListener("click",P=>{P.target!==i.button&&P.target!==i.wrapper&&P.target!==(d==null?void 0:d.button)&&P.target!==(d==null?void 0:d.wrapper)&&P.target!==(c==null?void 0:c.button)&&P.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&g.append(c.input),g.append(f,s,u),c&&t.append(c.previewsContainer),t.append(g,r,o);let m=g;return{footer:t,suggestions:r,composerForm:g,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:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(k=c==null?void 0:c.input)!=null?k:null,attachmentPreviewsContainer:(N=c==null?void 0:c.previewsContainer)!=null?N:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var rm=n=>{var g,f,u,m,v,x,M,E,k,N,P,W,C,I,B,D,T;let e=(f=(g=n==null?void 0:n.launcher)==null?void 0:g.enabled)!=null?f:!0,t=wn(n);if(ca(n)){let q=(m=(u=n==null?void 0:n.launcher)==null?void 0:u.composerBar)!=null?m:{},z=b("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(v=q.expandedSize)!=null?v:"anchored",z.style.zIndex=String((M=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?M:Mn);let re=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");re.style.width="100%",z.appendChild(re);let ke=b("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(E=q.expandedSize)!=null?E:"anchored",ke.style.zIndex=String((N=(k=n==null?void 0:n.launcher)==null?void 0:k.zIndex)!=null?N:Mn),{wrapper:z,panel:re,pillRoot:ke}}if(t){let q=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return q.appendChild(z),{wrapper:q,panel:z}}if(!e){let q=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),re=(W=(P=n==null?void 0:n.launcher)==null?void 0:P.width)!=null?W:"100%";return q.style.width=re,z.style.width="100%",q.appendChild(z),{wrapper:q,panel:z}}let o=(C=n==null?void 0:n.launcher)!=null?C:{},s=o.position&&xr[o.position]?xr[o.position]:xr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((B=(I=n==null?void 0:n.launcher)==null?void 0:I.zIndex)!=null?B:Mn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(T=(D=n==null?void 0:n.launcher)==null?void 0:D.width)!=null?T:n==null?void 0:n.launcherWidth,c=d!=null?d:Qr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},tb=(n,e)=>{var P,W,C,I,B,D,T,q,z;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}=ci(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=(P=n==null?void 0:n.launcher)==null?void 0:P.clearChat)==null?void 0:W.enabled)!=null?C:!0,a=null,i=null;if(s){let re=di(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=re.button,i=re.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=kt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=kt("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 g=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(B=(I=n==null?void 0:n.copy)==null?void 0:I.welcomeTitle)!=null?B:"Hello \u{1F44B}"}),f=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(T=(D=n==null?void 0:n.copy)==null?void 0:D.welcomeSubtitle)!=null?T:"Ask anything about your account or products."}),u=kt("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))"}},g,f),m=b("div","persona-flex persona-flex-col persona-gap-3"),v=(q=n==null?void 0:n.layout)==null?void 0:q.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((z=n==null?void 0:n.copy)==null?void 0:z.showWelcomeCard)!==!1||(u.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(u,m);let M=kt("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"}}),E=nm({config:n}),{root:k,textNode:N}=tm();return t.append(d,o,c,M),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:m,composerOverlay:M,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:g,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:k,peekTextNode:N}},om=(n,e=!0)=>{var M,E,k,N,P,W,C,I,B;if(ca(n))return tb(n,e);let t=kt("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=n==null?void 0:n.layout)==null?void 0:M.header,o=((E=n==null?void 0:n.layout)==null?void 0:E.showHeader)!==!1,s=r?pi(n,r,{showClose:e}):Uo({config:n,showClose:e}),a=kt("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=kt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(k=n==null?void 0:n.copy)==null?void 0:k.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),d=kt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(P=n==null?void 0:n.copy)==null?void 0:P.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),c=kt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:wn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),g=b("div","persona-flex persona-flex-col persona-gap-3"),f=(C=n==null?void 0:n.layout)==null?void 0:C.contentMaxWidth;f&&(g.style.maxWidth=f,g.style.marginLeft="auto",g.style.marginRight="auto",g.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,g);let m=bi({config:n}),v=((B=n==null?void 0:n.layout)==null?void 0:B.showFooter)!==!1;o?da(t,s,n):(s.header.style.display="none",da(t,s,n)),t.append(a);let x=kt("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||(m.footer.style.display="none"),t.append(m.footer),t.append(x),{container:t,body:a,messagesWrapper:g,composerOverlay:x,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 rl=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
16
+ _Details: ${e.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]}),Hu=(n,t="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:t,Du=n=>Us(n)||n===Kr,ti=class{constructor(t={},e){this.config=t;this.callbacks=e;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 Zs(()=>this.createSpeechEngine());this.handleEvent=t=>{var e,r,o,s,a,i,d,c,g,f;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall,m=!!(u!=null&&u.name)&&(Us(u.name)||u.name===Kr&&((r=(e=this.config.features)==null?void 0:e.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.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=(g=this.callbacks).onError)==null||f.call(g,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.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 Xs(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let e=(o=t.host)!=null?o:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!e||!r||!this.config.clientToken||Yi().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Xi((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,e,r;return(r=(e=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:e.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let e=gs.isSupported()?new gs({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,g=this.config.clientToken,f=t.browserFallback!==!1;if(d&&c&&g)return Yi().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:m})=>{let v=new u({host:d,agentId:c,clientToken:g,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&e?new m(v,e,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&e)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),e}return e}setupVoice(t){var e,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ms(o);let a=(r=((e=this.config.voiceRecognition)!=null?e:{}).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 g=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=g.id}if(c){this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.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 g=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=g.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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var e,r,o,s,a,i,d,c,g,f;if(!((e=this.config.voiceRecognition)!=null&&e.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=t.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,e;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(e=(t=this.callbacks).onError)==null||e.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let e={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(e)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,e){return this.client.submitMessageFeedback(t,e)}async submitCSATFeedback(t,e){return this.client.submitCSATFeedback(t,e)}async submitNPSFeedback(t,e){return this.client.submitNPSFeedback(t,e)}updateConfig(t){let e={...this.config,...t};if(!Af(this.config,e)){this.config=e,this.client.updateConfig(e);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=e,this.client=new Xs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:e,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g,rawContent:f}=t,m={id:a!=null?a:e==="user"?Qa():e==="assistant"?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:e,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},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let e=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:f=!1,voiceProcessing:u,rawContent:m}=r,x={id:d!=null?d:o==="user"?Qa():o==="assistant"?Js():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};e.push(x)}return this.messages=this.sortMessages([...this.messages,...e]),this.callbacks.onMessagesChanged([...this.messages]),e}injectComponentDirective(t){let{component:e,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:e,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(t,e){var c,g,f,u,m;let r=t.trim();if(!r&&(!(e!=null&&e.contentParts)||e.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Qa(),s=Js(),a={id:o,role:"user",content:r||Xa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(e==null?void 0:e.viaVoice)||!1,...(e==null?void 0:e.contentParts)&&e.contentParts.length>0&&{contentParts:e.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 T=Bu(v,this.config.errorMessage);if(T){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(g=this.callbacks).onError)==null||f.call(g,v):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Js();this.setStreaming(!0);let e=new AbortController;this.abortController=e;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:e.signal,assistantMessageId:t},this.handleEvent)}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let f=Bu(c,this.config.errorMessage);if(f){let u={id:t,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(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(t,e){var o,s,a;if(this.streaming&&!(e!=null&&e.allowReentry))return;e!=null&&e.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(t,this.handleEvent,e==null?void 0:e.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 t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let e={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${e.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:e}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,e){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:e,resolvedAt:Date.now()}}),r(e==="approved")}async resolveApproval(t,e,r){var g,f,u,m,v;let o=`approval-${t.id}`,s={...t,status:e,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(g=a==null?void 0:a.createdAt)!=null?g: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:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},e,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},e),x){let T=null;if(x instanceof Response){if(!x.ok){let E=await x.json().catch(()=>null);throw new Error((u=E==null?void 0:E.error)!=null?u:`Approval request failed: ${x.status}`)}T=x.body}else x instanceof ReadableStream&&(T=x);T?await this.connectStream(T,{allowReentry:!0}):(e==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let T=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,e){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:e.answers,askUserQuestionIndex:e.currentIndex}})}markAskUserQuestionResolved(t,e){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...e?{askUserQuestionAnswers:e}:{}}})}async resolveAskUserQuestion(t,e){var g,f,u,m,v,x,T,E,A,R,L,W;let r=this.messages.find(C=>C.id===t.id);if(((g=r==null?void 0:r.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0)return;let o=(f=t.agentMetadata)==null?void 0:f.executionId,s=(u=t.toolCall)==null?void 0:u.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof e=="string"?void 0:e;if(a===void 0&&typeof e=="string"){let C=(x=t.toolCall)==null?void 0:x.args,k=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(k.length===1){let D=typeof((T=k[0])==null?void 0:T.question)=="string"?k[0].question:"";D&&(a={[D]:e})}}this.markAskUserQuestionResolved(t,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(A=t.toolCall)==null?void 0:A.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof e=="string"?e:Object.entries(e).map(([k,D])=>`${k}: ${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((k,D)=>{let N=typeof(k==null?void 0:k.question)=="string"?k.question:"";if(!N)return;let M=C[N],U=Array.isArray(M)?M.join(", "):typeof M=="string"?M:"";this.appendMessage({id:`ask-user-q-${i}-${D}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${D}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:e});if(!C.ok){let k=await C.json().catch(()=>null);throw new Error((R=k==null?void 0:k.error)!=null?R:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let k=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(W=(L=this.callbacks).onError)==null||W.call(L,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let e=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!e||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(e);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(e,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let e of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(e)})}flushWebMcpAwaitBatch(t){let e=this.webMcpAwaitBatches.get(t);if(!e)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=e;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let e=this.messages.find(a=>a.id===t.id),r=[(o=e==null?void 0:e.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Kr)return!1;let e=this.messages.find(s=>s.id===t.id);return((o=(e!=null?e:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let e=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:e,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),e}markWebMcpToolComplete(t,e,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:e,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,e){var d,c,g,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(e.map(async u=>{var W,C,k,D,N,M,U;let m=(W=u.toolCall)==null?void 0:W.name,v=(C=u.toolCall)==null?void 0:C.id;if(!m||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(x),r.push(x);let T=this.markWebMcpToolRunning(u),E=(D=(k=u.agentMetadata)==null?void 0:k.webMcpToolCallId)!=null?D:m;if(m===Kr)return{dedupeKey:x,resumeKey:E,output:Ui(),toolMessage:u,startedAt:T,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),o.push(A);let R=this.client.executeWebMcpToolCall(m,(N=u.toolCall)==null?void 0:N.args,A.signal),L;if(!R)L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{L=await R}catch(z){let ne=z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")||z.message.includes("abort"));return ne||(U=(M=this.callbacks).onError)==null||U.call(M,z instanceof Error?z:new Error(String(z))),this.markWebMcpToolComplete(u,ea(ne?"Aborted by cancel()":Hu(z)),T),this.webMcpInflightKeys.delete(x),null}return A.signal.aborted?(this.markWebMcpToolComplete(u,ea("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:E,output:L,toolMessage:u,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let u={};for(let v of i)u[v.resumeKey]=v.output;let m=await this.client.resumeFlow(t,u,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.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)===Kr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(g=this.callbacks).onError)==null||f.call(g,u instanceof Error?u:new Error(String(u)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ea("Aborted by cancel()"),v.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,T,E,A,R,L,W,C,k,D,N;let e=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(T=t.toolCall)==null?void 0:T.id;if(!e){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let M=`${e}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))return;this.webMcpInflightKeys.add(M);try{await this.resumeWithToolOutput(e,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(M)}catch(U){(L=(R=this.callbacks).onError)==null||L.call(R,U instanceof Error?U:new Error(String(U)))}finally{this.webMcpInflightKeys.delete(M)}return}let s=`${e}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Kr,g=(W=t.toolCall)==null?void 0:W.args,f=c?null:this.client.executeWebMcpToolCall(r,g,d),u="execute",m=a;try{let M;if(c?M=Ui():f?M=await f:M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ea("Aborted by cancel()"),a);return}let U=(k=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?k:r;u="resume",await this.resumeWithToolOutput(e,U,M,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,M,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(M){let U=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));(u==="execute"||U||d.aborted)&&this.markWebMcpToolComplete(t,ea(U||d.aborted?"Aborted by cancel()":Hu(M)),a),U||(N=(D=this.callbacks).onError)==null||N.call(D,M instanceof Error?M:new Error(String(M)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,e,r,o){var a,i;let s=await this.client.resumeFlow(t,{[e]: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 t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let e=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:e,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(e,s),this.selectedArtifactId=e,this.emitArtifactsState(),s}let r={id:e,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(e,r),this.selectedArtifactId=e,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,e;(e=(t=this.callbacks).onArtifactsState)==null||e.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var e,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(e=t.component)!=null?e:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.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(t,e=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=e,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let e=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),e&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=Ji(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ya(t)}toggleReadAloud(t){let e=this.messages.find(s=>s.id===t);if(!e||e.role!=="assistant")return;let r=Ji(e.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let e=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,e]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let e=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===e.id);if(r===-1){this.appendMessage(e);return}this.messages=this.messages.map((o,s)=>{var g,f,u,m,v,x,T,E,A,R,L,W,C,k,D;if(s!==r)return o;let a={...o,...e};if(((g=o.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0&&e.agentMetadata&&(a.agentMetadata={...e.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&e.agentMetadata&&(a.agentMetadata={...(u=a.agentMetadata)!=null?u:e.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&e.approval&&o.approval.id===e.approval.id){let N=o.approval,M=e.approval;a.approval={...N,...M,executionId:M.executionId||N.executionId,toolName:M.toolName||N.toolName,description:M.description||N.description,toolType:(m=M.toolType)!=null?m:N.toolType,reason:(v=M.reason)!=null?v:N.reason,parameters:(x=M.parameters)!=null?x:N.parameters}}let i=(T=e.toolCall)==null?void 0:T.name,d=(E=e.agentMetadata)==null?void 0:E.executionId,c=(A=e.toolCall)==null?void 0:A.id;if(i&&Du(i)&&d&&c&&((R=e.agentMetadata)==null?void 0:R.awaitingLocalTool)===!0){let N=`${d}:${c}`,M=this.webMcpInflightKeys.has(N),U=this.webMcpResolvedKeys.has(N),z=(L=o.toolCall)==null?void 0:L.name,ne=((W=o.agentMetadata)==null?void 0:W.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&z!==void 0&&Du(z)&&((k=o.toolCall)==null?void 0:k.status)==="complete";(M||U||ne)&&(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(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((e,r)=>{var d,c;let o=new Date(e.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=e.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:e.id.localeCompare(r.id)})}};import{Activity as Sf,ArrowDown as Tf,ArrowUp as Ef,ArrowUpRight as Mf,Bot as kf,ChevronDown as Lf,ChevronUp as If,ChevronRight as Pf,ChevronLeft as Wf,Check as Rf,Clipboard as Bf,ClipboardCopy as Hf,Copy as Df,File as Nf,FileCode as Ff,FileSpreadsheet as _f,FileText as Of,ImagePlus as $f,Loader as qf,LoaderCircle as Uf,Mic as zf,Paperclip as jf,RefreshCw as Vf,Search as Kf,Send as Gf,ShieldAlert as Qf,ShieldCheck as Xf,ShieldX as Jf,Square as Yf,ThumbsDown as Zf,ThumbsUp as eh,Upload as th,Volume2 as nh,X as rh,User as oh,Mail as sh,Phone as ah,Calendar as ih,Clock as lh,Building as ch,MapPin as dh,Lock as ph,Key as uh,CreditCard as mh,AtSign as gh,Hash as fh,Globe as hh,Link as bh,CircleCheck as yh,CircleX as vh,TriangleAlert as xh,Info as wh,Ban as Ch,Shield as Ah,ArrowLeft as Sh,ArrowRight as Th,ExternalLink as Eh,Ellipsis as Mh,EllipsisVertical as kh,Menu as Lh,House as Ih,Plus as Ph,Minus as Wh,Pencil as Rh,Trash as Bh,Trash2 as Hh,Save as Dh,Download as Nh,Share as Fh,Funnel as _h,Settings as Oh,RotateCw as $h,Maximize as qh,Minimize as Uh,ShoppingCart as zh,ShoppingBag as jh,Package as Vh,Truck as Kh,Tag as Gh,Gift as Qh,Receipt as Xh,Wallet as Jh,Store as Yh,DollarSign as Zh,Percent as eb,Play as tb,Pause as nb,VolumeX as rb,Camera as ob,Image as sb,Film as ab,Headphones as ib,MessageCircle as lb,MessageSquare as cb,Bell as db,Heart as pb,Star as ub,Eye as mb,EyeOff as gb,Bookmark as fb,CalendarDays as hb,History as bb,Timer as yb,Folder as vb,FolderOpen as xb,Files as wb,Sparkles as Cb,Zap as Ab,Sun as Sb,Moon as Tb,Flag as Eb,Monitor as Mb,Smartphone as kb}from"lucide";var Lb={activity:Sf,"arrow-down":Tf,"arrow-up":Ef,"arrow-up-right":Mf,bot:kf,"chevron-down":Lf,"chevron-up":If,"chevron-right":Pf,"chevron-left":Wf,check:Rf,clipboard:Bf,"clipboard-copy":Hf,copy:Df,file:Nf,"file-code":Ff,"file-spreadsheet":_f,"file-text":Of,"image-plus":$f,loader:qf,"loader-circle":Uf,mic:zf,paperclip:jf,"refresh-cw":Vf,search:Kf,send:Gf,"shield-alert":Qf,"shield-check":Xf,"shield-x":Jf,square:Yf,"thumbs-down":Zf,"thumbs-up":eh,upload:th,"volume-2":nh,x:rh,user:oh,mail:sh,phone:ah,calendar:ih,clock:lh,building:ch,"map-pin":dh,lock:ph,key:uh,"credit-card":mh,"at-sign":gh,hash:fh,globe:hh,link:bh,"circle-check":yh,"circle-x":vh,"triangle-alert":xh,info:wh,ban:Ch,shield:Ah,"arrow-left":Sh,"arrow-right":Th,"external-link":Eh,ellipsis:Mh,"ellipsis-vertical":kh,menu:Lh,house:Ih,plus:Ph,minus:Wh,pencil:Rh,trash:Bh,"trash-2":Hh,save:Dh,download:Nh,share:Fh,funnel:_h,settings:Oh,"rotate-cw":$h,maximize:qh,minimize:Uh,"shopping-cart":zh,"shopping-bag":jh,package:Vh,truck:Kh,tag:Gh,gift:Qh,receipt:Xh,wallet:Jh,store:Yh,"dollar-sign":Zh,percent:eb,play:tb,pause:nb,"volume-x":rb,camera:ob,image:sb,film:ab,headphones:ib,"message-circle":lb,"message-square":cb,bell:db,heart:pb,star:ub,eye:mb,"eye-off":gb,bookmark:fb,"calendar-days":hb,history:bb,timer:yb,folder:vb,"folder-open":xb,files:wb,sparkles:Cb,zap:Ab,sun:Sb,moon:Tb,flag:Eb,monitor:Mb,smartphone:kb},Ae=(n,t=24,e="currentColor",r=2)=>{let o=Lb[n];return o?Ib(o,t,e,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 Ib(n,t,e,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),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,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}),o}var ni={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function Pb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Wb(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 ta=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var e,r,o;this.config={allowedTypes:(e=t.allowedTypes)!=null?e:ni.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ni.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ni.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ni.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var e,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(e=this.config).onFileRejected)==null||r.call(e,c,"count");continue}let g=Su(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let f=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await Au(c),u=Ja(c)?URL.createObjectURL(c):null,m={id:Pb(),file:c,previewUrl:u,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(t){var s,a,i;let e=this.attachments.findIndex(d=>d.id===t);if(e===-1)return;let r=this.attachments[e];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(e,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,e;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(e=(t=this.config).onAttachmentsChange)==null||e.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let e=Ja(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",e&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",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=Wb(t.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Tu(t.file.type,t.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=Ae("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(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,e){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:e})}};var Nu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function na(n,t){if(!n)return t;if(!t)return n;let e={...n};for(let[r,o]of Object.entries(t)){let s=e[r];Nu(s)&&Nu(o)?e[r]=na(s,o):e[r]=o}return e}var Qr="min(440px, calc(100vw - 24px))",_u="440px",Rb={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:Qr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Ut={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Rb,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 Fu(n,t){if(!(!n&&!t))return n?t?na(n,t):n:t}function Ou(n){var t,e,r,o,s,a,i,d,c,g,f,u,m,v,x,T,E,A,R,L,W;return n?{...Ut,...n,theme:Fu(Ut.theme,n.theme),darkTheme:Fu(Ut.darkTheme,n.darkTheme),launcher:{...Ut.launcher,...n.launcher,dock:{...(t=Ut.launcher)==null?void 0:t.dock,...(e=n.launcher)==null?void 0:e.dock},clearChat:{...(r=Ut.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Ut.copy,...n.copy},sendButton:{...Ut.sendButton,...n.sendButton},statusIndicator:{...Ut.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ut.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,Q,oe,ge,de,V,se,Re,Z,Y;let C=(re=Ut.features)==null?void 0:re.artifacts,k=(Q=n.features)==null?void 0:Q.artifacts,D=(oe=Ut.features)==null?void 0:oe.scrollToBottom,N=(ge=n.features)==null?void 0:ge.scrollToBottom,M=(de=Ut.features)==null?void 0:de.scrollBehavior,U=(V=n.features)==null?void 0:V.scrollBehavior,z=(se=Ut.features)==null?void 0:se.streamAnimation,ne=(Re=n.features)==null?void 0:Re.streamAnimation,Le=(Z=Ut.features)==null?void 0:Z.askUserQuestion,je=(Y=n.features)==null?void 0:Y.askUserQuestion,ye=C===void 0&&k===void 0?void 0:{...C,...k,layout:{...C==null?void 0:C.layout,...k==null?void 0:k.layout}},De=D===void 0&&N===void 0?void 0:{...D,...N},$e=M===void 0&&U===void 0?void 0:{...M,...U},Se=z===void 0&&ne===void 0?void 0:{...z,...ne},xe=Le===void 0&&je===void 0?void 0:{...Le,...je,styles:{...Le==null?void 0:Le.styles,...je==null?void 0:je.styles}};return{...Ut.features,...n.features,...De!==void 0?{scrollToBottom:De}:{},...$e!==void 0?{scrollBehavior:$e}:{},...ye!==void 0?{artifacts:ye}:{},...Se!==void 0?{streamAnimation:Se}:{},...xe!==void 0?{askUserQuestion:xe}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Ut.suggestionChips,suggestionChipsConfig:{...Ut.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ut.layout,...n.layout,header:{...(a=Ut.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Ut.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(g=Ut.layout)==null?void 0:g.messages)==null?void 0:f.avatar,...(m=(u=n.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Ut.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(E=(T=n.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(A=Ut.layout)==null?void 0:A.slots,...(R=n.layout)==null?void 0:R.slots}},markdown:{...Ut.markdown,...n.markdown,options:{...(L=Ut.markdown)==null?void 0:L.options,...(W=n.markdown)==null?void 0:W.options}},messageActions:{...Ut.messageActions,...n.messageActions}}:Ut}var Bb={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"}},Hb={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"}},Db={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:Qr,maxWidth:_u,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 fs(n,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let e=t.split("."),r=n;for(let o of e){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?fs(n,r):r}function $u(n){let t={};function e(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=fs(n,a);d!==void 0&&(t[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&&e(a,i)}}return e(n.palette,"palette"),e(n.semantic,"semantic"),e(n.components,"components"),t}function Nb(n){let t=[],e=[];return n.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||e.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||e.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:e}}function qu(n,t){let e={...n};for(let[r,o]of Object.entries(t)){let s=e[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?e[r]=qu(s,o):e[r]=o}return e}function Fb(n,t){return t?qu(n,t):n}function Oo(n,t={}){var o,s,a,i,d,c,g,f,u,m,v,x,T;let e={palette:Bb,semantic:Hb,components:Db},r={palette:{...e.palette,...n==null?void 0:n.palette,colors:{...e.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...e.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...e.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...e.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...e.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...e.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...e.semantic,...n==null?void 0:n.semantic,colors:{...e.semantic.colors,...(g=n==null?void 0:n.semantic)==null?void 0:g.colors,interactive:{...e.semantic.colors.interactive,...(u=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...e.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...e.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...e.semantic.typography,...(T=n==null?void 0:n.semantic)==null?void 0:T.typography}},components:Fb(e.components,n==null?void 0:n.components)};if(t.validate!==!1){let E=Nb(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)r=E.transform(r);return r}function Uu(n){var x,T,E,A,R,L,W,C,k,D,N,M,U,z,ne,Le,je,ye,De,$e,Se,xe,re,Q,oe,ge,de,V,se,Re,Z,Y,te,ot,st,tt,Ee,fe,Ke,X,pe,ke,Qe,Kt,Ie,qe,nt,Dt,bn,xr,An,Ve,Nt,$,Me,we,Fe,at,dt,rt,Et,j,At,ce,ue,Te,pt,Zt,sn,xn,_t,Ze,Ft,ut,en,nr,Pn,an,_n,wr,wt,zn,Cr,Dr,pr,vt,xo,Ar,wo,On,jo,Jr,Nr,Yr,Zr,Co,Ao,eo,St,jn,Vn,Wn,Mt,rr,or,Kn,to,Fr,no,Gn,Ot,Rn,sr,ro,_r,oo,Sr,Qn;let t=$u(n),e={};for(let[be,mt]of Object.entries(t)){let nn=be.replace(/\./g,"-");e[`--persona-${nn}`]=mt.value}e["--persona-primary"]=(x=e["--persona-semantic-colors-primary"])!=null?x:e["--persona-palette-colors-primary-500"],e["--persona-secondary"]=(T=e["--persona-semantic-colors-secondary"])!=null?T:e["--persona-palette-colors-secondary-500"],e["--persona-accent"]=(E=e["--persona-semantic-colors-accent"])!=null?E:e["--persona-palette-colors-accent-500"],e["--persona-surface"]=(A=e["--persona-semantic-colors-surface"])!=null?A:e["--persona-palette-colors-gray-50"],e["--persona-background"]=(R=e["--persona-semantic-colors-background"])!=null?R:e["--persona-palette-colors-gray-50"],e["--persona-container"]=(L=e["--persona-semantic-colors-container"])!=null?L:e["--persona-palette-colors-gray-100"],e["--persona-text"]=(W=e["--persona-semantic-colors-text"])!=null?W:e["--persona-palette-colors-gray-900"],e["--persona-text-muted"]=(C=e["--persona-semantic-colors-text-muted"])!=null?C:e["--persona-palette-colors-gray-500"],e["--persona-text-inverse"]=(k=e["--persona-semantic-colors-text-inverse"])!=null?k:e["--persona-palette-colors-gray-50"],e["--persona-border"]=(D=e["--persona-semantic-colors-border"])!=null?D:e["--persona-palette-colors-gray-200"],e["--persona-divider"]=(N=e["--persona-semantic-colors-divider"])!=null?N:e["--persona-palette-colors-gray-200"],e["--persona-muted"]=e["--persona-text-muted"],e["--persona-voice-recording-indicator"]=(M=e["--persona-components-voice-recording-indicator"])!=null?M:e["--persona-palette-colors-error-500"],e["--persona-voice-recording-bg"]=(U=e["--persona-components-voice-recording-background"])!=null?U:e["--persona-palette-colors-error-50"],e["--persona-voice-processing-icon"]=(z=e["--persona-components-voice-processing-icon"])!=null?z:e["--persona-palette-colors-primary-500"],e["--persona-voice-speaking-icon"]=(ne=e["--persona-components-voice-speaking-icon"])!=null?ne:e["--persona-palette-colors-success-500"],e["--persona-approval-bg"]=(Le=e["--persona-components-approval-requested-background"])!=null?Le:e["--persona-palette-colors-warning-50"],e["--persona-approval-border"]=(je=e["--persona-components-approval-requested-border"])!=null?je:e["--persona-palette-colors-warning-200"],e["--persona-approval-text"]=(ye=e["--persona-components-approval-requested-text"])!=null?ye:e["--persona-palette-colors-gray-900"],e["--persona-approval-shadow"]=(De=e["--persona-components-approval-requested-shadow"])!=null?De:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-approval-approve-bg"]=($e=e["--persona-components-approval-approve-background"])!=null?$e:e["--persona-palette-colors-success-500"],e["--persona-approval-deny-bg"]=(Se=e["--persona-components-approval-deny-background"])!=null?Se:e["--persona-palette-colors-error-500"],e["--persona-attachment-image-bg"]=(xe=e["--persona-components-attachment-image-background"])!=null?xe:e["--persona-palette-colors-gray-100"],e["--persona-attachment-image-border"]=(re=e["--persona-components-attachment-image-border"])!=null?re:e["--persona-palette-colors-gray-200"],e["--persona-font-family"]=(Q=e["--persona-semantic-typography-fontFamily"])!=null?Q:e["--persona-palette-typography-fontFamily-sans"],e["--persona-font-size"]=(oe=e["--persona-semantic-typography-fontSize"])!=null?oe:e["--persona-palette-typography-fontSize-base"],e["--persona-font-weight"]=(ge=e["--persona-semantic-typography-fontWeight"])!=null?ge:e["--persona-palette-typography-fontWeight-normal"],e["--persona-line-height"]=(de=e["--persona-semantic-typography-lineHeight"])!=null?de:e["--persona-palette-typography-lineHeight-normal"],e["--persona-input-font-family"]=e["--persona-font-family"],e["--persona-input-font-weight"]=e["--persona-font-weight"],e["--persona-radius-sm"]=(V=e["--persona-palette-radius-sm"])!=null?V:"0.125rem",e["--persona-radius-md"]=(se=e["--persona-palette-radius-md"])!=null?se:"0.375rem",e["--persona-radius-lg"]=(Re=e["--persona-palette-radius-lg"])!=null?Re:"0.5rem",e["--persona-radius-xl"]=(Z=e["--persona-palette-radius-xl"])!=null?Z:"0.75rem",e["--persona-radius-full"]=(Y=e["--persona-palette-radius-full"])!=null?Y:"9999px",e["--persona-launcher-radius"]=(ot=(te=e["--persona-components-launcher-borderRadius"])!=null?te:e["--persona-palette-radius-full"])!=null?ot:"9999px",e["--persona-launcher-bg"]=(st=e["--persona-components-launcher-background"])!=null?st:e["--persona-primary"],e["--persona-launcher-fg"]=(tt=e["--persona-components-launcher-foreground"])!=null?tt:e["--persona-text-inverse"],e["--persona-launcher-border"]=(Ee=e["--persona-components-launcher-border"])!=null?Ee:e["--persona-border"],e["--persona-button-primary-bg"]=(fe=e["--persona-components-button-primary-background"])!=null?fe:e["--persona-primary"],e["--persona-button-primary-fg"]=(Ke=e["--persona-components-button-primary-foreground"])!=null?Ke:e["--persona-text-inverse"],e["--persona-button-radius"]=(pe=(X=e["--persona-components-button-primary-borderRadius"])!=null?X:e["--persona-palette-radius-full"])!=null?pe:"9999px",e["--persona-panel-radius"]=(Qe=(ke=e["--persona-components-panel-borderRadius"])!=null?ke:e["--persona-radius-xl"])!=null?Qe:"0.75rem",e["--persona-panel-border"]=(Kt=e["--persona-components-panel-border"])!=null?Kt:`1px solid ${e["--persona-border"]}`,e["--persona-panel-shadow"]=(qe=(Ie=e["--persona-components-panel-shadow"])!=null?Ie:e["--persona-palette-shadows-xl"])!=null?qe:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",e["--persona-launcher-shadow"]=(nt=e["--persona-components-launcher-shadow"])!=null?nt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",e["--persona-input-radius"]=(bn=(Dt=e["--persona-components-input-borderRadius"])!=null?Dt:e["--persona-radius-lg"])!=null?bn:"0.5rem",e["--persona-message-user-radius"]=(An=(xr=e["--persona-components-message-user-borderRadius"])!=null?xr:e["--persona-radius-lg"])!=null?An:"0.5rem",e["--persona-message-assistant-radius"]=(Nt=(Ve=e["--persona-components-message-assistant-borderRadius"])!=null?Ve:e["--persona-radius-lg"])!=null?Nt:"0.5rem",e["--persona-header-bg"]=($=e["--persona-components-header-background"])!=null?$:e["--persona-surface"],e["--persona-header-border"]=(Me=e["--persona-components-header-border"])!=null?Me:e["--persona-divider"],e["--persona-header-icon-bg"]=(we=e["--persona-components-header-iconBackground"])!=null?we:e["--persona-primary"],e["--persona-header-icon-fg"]=(Fe=e["--persona-components-header-iconForeground"])!=null?Fe:e["--persona-text-inverse"],e["--persona-header-title-fg"]=(at=e["--persona-components-header-titleForeground"])!=null?at:e["--persona-primary"],e["--persona-header-subtitle-fg"]=(dt=e["--persona-components-header-subtitleForeground"])!=null?dt:e["--persona-text-muted"],e["--persona-header-action-icon-fg"]=(rt=e["--persona-components-header-actionIconForeground"])!=null?rt:e["--persona-muted"];let r=(Et=n.components)==null?void 0:Et.header;r!=null&&r.shadow&&(e["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(e["--persona-header-border-bottom"]=r.borderBottom);let o=(j=n.components)==null?void 0:j.introCard;e["--persona-intro-card-bg"]=(At=e["--persona-components-introCard-background"])!=null?At:e["--persona-surface"],e["--persona-intro-card-radius"]=(ce=e["--persona-components-introCard-borderRadius"])!=null?ce:"1rem",e["--persona-intro-card-padding"]=(ue=e["--persona-components-introCard-padding"])!=null?ue:"1.5rem",e["--persona-intro-card-shadow"]=(pt=(Te=o==null?void 0:o.shadow)!=null?Te:e["--persona-components-introCard-shadow"])!=null?pt:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-input-background"]=(Zt=e["--persona-components-input-background"])!=null?Zt:e["--persona-surface"],e["--persona-input-placeholder"]=(sn=e["--persona-components-input-placeholder"])!=null?sn:e["--persona-text-muted"],e["--persona-message-user-bg"]=(xn=e["--persona-components-message-user-background"])!=null?xn:e["--persona-accent"],e["--persona-message-user-text"]=(_t=e["--persona-components-message-user-text"])!=null?_t:e["--persona-text-inverse"],e["--persona-message-user-shadow"]=(Ze=e["--persona-components-message-user-shadow"])!=null?Ze:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-message-assistant-bg"]=(Ft=e["--persona-components-message-assistant-background"])!=null?Ft:e["--persona-surface"],e["--persona-message-assistant-text"]=(ut=e["--persona-components-message-assistant-text"])!=null?ut:e["--persona-text"],e["--persona-message-assistant-border"]=(en=e["--persona-components-message-assistant-border"])!=null?en:e["--persona-border"],e["--persona-message-assistant-shadow"]=(nr=e["--persona-components-message-assistant-shadow"])!=null?nr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",e["--persona-scroll-to-bottom-bg"]=(an=(Pn=e["--persona-components-scrollToBottom-background"])!=null?Pn:e["--persona-button-primary-bg"])!=null?an:e["--persona-accent"],e["--persona-scroll-to-bottom-fg"]=(wr=(_n=e["--persona-components-scrollToBottom-foreground"])!=null?_n:e["--persona-button-primary-fg"])!=null?wr:e["--persona-text-inverse"],e["--persona-scroll-to-bottom-border"]=(wt=e["--persona-components-scrollToBottom-border"])!=null?wt:e["--persona-primary"],e["--persona-scroll-to-bottom-size"]=(zn=e["--persona-components-scrollToBottom-size"])!=null?zn:"40px",e["--persona-scroll-to-bottom-radius"]=(pr=(Dr=(Cr=e["--persona-components-scrollToBottom-borderRadius"])!=null?Cr:e["--persona-button-radius"])!=null?Dr:e["--persona-radius-full"])!=null?pr:"9999px",e["--persona-scroll-to-bottom-shadow"]=(xo=(vt=e["--persona-components-scrollToBottom-shadow"])!=null?vt:e["--persona-palette-shadows-sm"])!=null?xo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",e["--persona-scroll-to-bottom-padding"]=(Ar=e["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",e["--persona-scroll-to-bottom-gap"]=(wo=e["--persona-components-scrollToBottom-gap"])!=null?wo:"0.5rem",e["--persona-scroll-to-bottom-font-size"]=(jo=(On=e["--persona-components-scrollToBottom-fontSize"])!=null?On:e["--persona-palette-typography-fontSize-sm"])!=null?jo:"0.875rem",e["--persona-scroll-to-bottom-icon-size"]=(Jr=e["--persona-components-scrollToBottom-iconSize"])!=null?Jr:"14px",e["--persona-tool-bubble-shadow"]=(Nr=e["--persona-components-toolBubble-shadow"])!=null?Nr:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-reasoning-bubble-shadow"]=(Yr=e["--persona-components-reasoningBubble-shadow"])!=null?Yr:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-composer-shadow"]=(Zr=e["--persona-components-composer-shadow"])!=null?Zr:"none",e["--persona-md-inline-code-bg"]=(Co=e["--persona-components-markdown-inlineCode-background"])!=null?Co:e["--persona-container"],e["--persona-md-inline-code-color"]=(Ao=e["--persona-components-markdown-inlineCode-foreground"])!=null?Ao:e["--persona-text"],e["--persona-md-link-color"]=(St=(eo=e["--persona-components-markdown-link-foreground"])!=null?eo:e["--persona-accent"])!=null?St:"#0f0f0f";let s=e["--persona-components-markdown-heading-h1-fontSize"];s&&(e["--persona-md-h1-size"]=s);let a=e["--persona-components-markdown-heading-h1-fontWeight"];a&&(e["--persona-md-h1-weight"]=a);let i=e["--persona-components-markdown-heading-h2-fontSize"];i&&(e["--persona-md-h2-size"]=i);let d=e["--persona-components-markdown-heading-h2-fontWeight"];d&&(e["--persona-md-h2-weight"]=d);let c=e["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(e["--persona-md-prose-font-family"]=c),e["--persona-md-code-block-bg"]=(jn=e["--persona-components-markdown-codeBlock-background"])!=null?jn:e["--persona-container"],e["--persona-md-code-block-border-color"]=(Vn=e["--persona-components-markdown-codeBlock-borderColor"])!=null?Vn:e["--persona-border"],e["--persona-md-code-block-text-color"]=(Wn=e["--persona-components-markdown-codeBlock-textColor"])!=null?Wn:"inherit",e["--persona-md-table-header-bg"]=(Mt=e["--persona-components-markdown-table-headerBackground"])!=null?Mt:e["--persona-container"],e["--persona-md-table-border-color"]=(rr=e["--persona-components-markdown-table-borderColor"])!=null?rr:e["--persona-border"],e["--persona-md-hr-color"]=(or=e["--persona-components-markdown-hr-color"])!=null?or:e["--persona-divider"],e["--persona-md-blockquote-border-color"]=(Kn=e["--persona-components-markdown-blockquote-borderColor"])!=null?Kn:e["--persona-palette-colors-gray-900"],e["--persona-md-blockquote-bg"]=(to=e["--persona-components-markdown-blockquote-background"])!=null?to:"transparent",e["--persona-md-blockquote-text-color"]=(Fr=e["--persona-components-markdown-blockquote-textColor"])!=null?Fr:e["--persona-palette-colors-gray-500"],e["--cw-container"]=(no=e["--persona-components-collapsibleWidget-container"])!=null?no:e["--persona-surface"],e["--cw-surface"]=(Gn=e["--persona-components-collapsibleWidget-surface"])!=null?Gn:e["--persona-surface"],e["--cw-border"]=(Ot=e["--persona-components-collapsibleWidget-border"])!=null?Ot:e["--persona-border"],e["--persona-message-border"]=(Rn=e["--persona-components-message-border"])!=null?Rn:e["--persona-border"];let g=n.components,f=g==null?void 0:g.iconButton;f&&(f.background&&(e["--persona-icon-btn-bg"]=f.background),f.border&&(e["--persona-icon-btn-border"]=f.border),f.color&&(e["--persona-icon-btn-color"]=f.color),f.padding&&(e["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(e["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(e["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(e["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(e["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(e["--persona-icon-btn-active-border"]=f.activeBorder));let u=g==null?void 0:g.labelButton;u&&(u.background&&(e["--persona-label-btn-bg"]=u.background),u.border&&(e["--persona-label-btn-border"]=u.border),u.color&&(e["--persona-label-btn-color"]=u.color),u.padding&&(e["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(e["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(e["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(e["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(e["--persona-label-btn-gap"]=u.gap));let m=g==null?void 0:g.toggleGroup;m&&(m.gap&&(e["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(e["--persona-toggle-group-radius"]=m.borderRadius));let v=g==null?void 0:g.artifact;if(v!=null&&v.toolbar){let be=v.toolbar;be.iconHoverColor&&(e["--persona-artifact-toolbar-icon-hover-color"]=be.iconHoverColor),be.iconHoverBackground&&(e["--persona-artifact-toolbar-icon-hover-bg"]=be.iconHoverBackground),be.iconPadding&&(e["--persona-artifact-toolbar-icon-padding"]=be.iconPadding),be.iconBorderRadius&&(e["--persona-artifact-toolbar-icon-radius"]=be.iconBorderRadius),be.iconBorder&&(e["--persona-artifact-toolbar-icon-border"]=be.iconBorder),be.toggleGroupGap&&(e["--persona-artifact-toolbar-toggle-group-gap"]=be.toggleGroupGap),be.toggleBorderRadius&&(e["--persona-artifact-toolbar-toggle-radius"]=be.toggleBorderRadius),be.copyBackground&&(e["--persona-artifact-toolbar-copy-bg"]=be.copyBackground),be.copyBorder&&(e["--persona-artifact-toolbar-copy-border"]=be.copyBorder),be.copyColor&&(e["--persona-artifact-toolbar-copy-color"]=be.copyColor),be.copyBorderRadius&&(e["--persona-artifact-toolbar-copy-radius"]=be.copyBorderRadius),be.copyPadding&&(e["--persona-artifact-toolbar-copy-padding"]=be.copyPadding),be.copyMenuBackground&&(e["--persona-artifact-toolbar-copy-menu-bg"]=be.copyMenuBackground,e["--persona-dropdown-bg"]=(sr=e["--persona-dropdown-bg"])!=null?sr:be.copyMenuBackground),be.copyMenuBorder&&(e["--persona-artifact-toolbar-copy-menu-border"]=be.copyMenuBorder,e["--persona-dropdown-border"]=(ro=e["--persona-dropdown-border"])!=null?ro:be.copyMenuBorder),be.copyMenuShadow&&(e["--persona-artifact-toolbar-copy-menu-shadow"]=be.copyMenuShadow,e["--persona-dropdown-shadow"]=(_r=e["--persona-dropdown-shadow"])!=null?_r:be.copyMenuShadow),be.copyMenuBorderRadius&&(e["--persona-artifact-toolbar-copy-menu-radius"]=be.copyMenuBorderRadius,e["--persona-dropdown-radius"]=(oo=e["--persona-dropdown-radius"])!=null?oo:be.copyMenuBorderRadius),be.copyMenuItemHoverBackground&&(e["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=be.copyMenuItemHoverBackground,e["--persona-dropdown-item-hover-bg"]=(Sr=e["--persona-dropdown-item-hover-bg"])!=null?Sr:be.copyMenuItemHoverBackground),be.iconBackground&&(e["--persona-artifact-toolbar-icon-bg"]=be.iconBackground),be.toolbarBorder&&(e["--persona-artifact-toolbar-border"]=be.toolbarBorder)}if(v!=null&&v.tab){let be=v.tab;be.background&&(e["--persona-artifact-tab-bg"]=be.background),be.activeBackground&&(e["--persona-artifact-tab-active-bg"]=be.activeBackground),be.activeBorder&&(e["--persona-artifact-tab-active-border"]=be.activeBorder),be.borderRadius&&(e["--persona-artifact-tab-radius"]=be.borderRadius),be.textColor&&(e["--persona-artifact-tab-color"]=be.textColor),be.hoverBackground&&(e["--persona-artifact-tab-hover-bg"]=be.hoverBackground),be.listBackground&&(e["--persona-artifact-tab-list-bg"]=be.listBackground),be.listBorderColor&&(e["--persona-artifact-tab-list-border-color"]=be.listBorderColor),be.listPadding&&(e["--persona-artifact-tab-list-padding"]=be.listPadding)}if(v!=null&&v.pane){let be=v.pane;if(be.toolbarBackground){let mt=(Qn=fs(n,be.toolbarBackground))!=null?Qn:be.toolbarBackground;e["--persona-artifact-toolbar-bg"]=mt}}return e}var _b={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},zu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Zi=()=>{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"},Ob=n=>{var e;let t=(e=n==null?void 0:n.colorScheme)!=null?e:"light";return t==="light"?"light":t==="dark"?"dark":Zi()},$b=n=>Ob(n),qb=n=>Oo(n),Ub=n=>{var e;let t=Oo(void 0,{validate:!1});return Oo({...n,palette:{...t.palette,colors:{..._b.colors,...(e=n==null?void 0:n.palette)==null?void 0:e.colors}}},{validate:!1})},ri=n=>{let t=$b(n),e=zu(n==null?void 0:n.theme),r=zu(n==null?void 0:n.darkTheme);return t==="dark"?Ub(na(e!=null?e:{},r!=null?r:{})):qb(e)},zb=n=>Uu(n),hs=(n,t)=>{let e=ri(t),r=zb(e);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},ju=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let e=new MutationObserver(()=>{n(Zi())});e.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>e.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let e=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Zi());e.addEventListener?(e.addEventListener("change",r),t.push(()=>e.removeEventListener("change",r))):e.addListener&&(e.addListener(r),t.push(()=>e.removeListener(r)))}return()=>{t.forEach(e=>e())}};import{Idiomorph as jb}from"idiomorph";var oi=(n,t,e={})=>{let{preserveTypingAnimation:r=!0}=e;jb.morph(n,t.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 si={index:-1,draft:""};function Vu(n){let{direction:t,history:e,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(e.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=e.length-1;return{handled:!0,value:e[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:e[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<e.length-1){let i=s.index+1;return{handled:!0,value:e[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...si}}}function Ku(n,t){var e,r,o,s,a,i,d,c,g,f,u,m,v,x,T,E,A,R,L,W,C,k,D,N,M,U,z,ne,Le,je,ye,De,$e,Se,xe,re,Q,oe;return[n.id,n.role,(r=(e=n.content)==null?void 0:e.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,(g=(c=n.llmContent)==null?void 0:c.length)!=null?g:0,(u=(f=n.approval)==null?void 0:f.status)!=null?u:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(T=(x=n.toolCall)==null?void 0:x.name)!=null?T:"",(R=(A=(E=n.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?R:0,(k=(C=(W=(L=n.toolCall)==null?void 0:L.chunks)==null?void 0:W[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?k:"",typeof((D=n.toolCall)==null?void 0:D.args)=="string"?n.toolCall.args.length:(N=n.toolCall)!=null&&N.args?JSON.stringify(n.toolCall.args).length:0,(z=(U=(M=n.reasoning)==null?void 0:M.chunks)==null?void 0:U.length)!=null?z:0,(ye=(je=(Le=(ne=n.reasoning)==null?void 0:ne.chunks)==null?void 0:Le[n.reasoning.chunks.length-1])==null?void 0:je.length)!=null?ye:0,(xe=(Se=($e=(De=n.reasoning)==null?void 0:De.chunks)==null?void 0:$e[n.reasoning.chunks.length-1])==null?void 0:Se.slice(-32))!=null?xe:"",(Q=(re=n.contentParts)==null?void 0:re.length)!=null?Q:0,(oe=n.stopReason)!=null?oe:"",t].join("\0")}function Gu(){return new Map}function Qu(n,t,e){let r=n.get(t);return r&&r.fingerprint===e?r.wrapper:null}function Xu(n,t,e,r){n.set(t,{fingerprint:e,wrapper:r})}function Ju(n,t){for(let e of n.keys())t.has(e)||n.delete(e)}function ai(n=!0){let t=n;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Xr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function $o(n,t){return Xr(n)-n.scrollTop<=t}function ii(n){let{following:t,currentScrollTop:e,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,g=e-r;return a||Math.abs(g)<s?{action:"none",delta:g,nextLastScrollTop:e}:!t&&o&&(!c||g>0)?{action:"resume",delta:g,nextLastScrollTop:e}:t&&i&&g<0?{action:"pause",delta:g,nextLastScrollTop:e}:t&&d&&!o?{action:"pause",delta:g,nextLastScrollTop:e}:{action:"none",delta:g,nextLastScrollTop:e}}function li(n){let{following:t,deltaY:e,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return t&&e<0?"pause":!t&&o&&e>0&&r?"resume":"none"}function Yu(n,t){return!n||n.isCollapsed?!1:t.contains(n.anchorNode)||t.contains(n.focusNode)}function Zu(n){let t=Math.max(0,n.anchorOffsetTop-n.topOffset),e=Math.max(0,t+n.viewportHeight-n.contentHeight);return{targetScrollTop:t,spacerHeight:e}}function em(n){let t=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-t)}var kn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Ln=1e5,yo=Ln+1;var ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Vb=["pre","code","a","script","style"],ci=n=>{var t,e,r,o,s;return{type:(t=n==null?void 0:n.type)!=null?t:ra.type,placeholder:(e=n==null?void 0:n.placeholder)!=null?e:ra.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:ra.speed,duration:(o=n==null?void 0:n.duration)!=null?o:ra.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:ra.buffer}},Kb=[{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"}],nm=new Map;for(let n of Kb)nm.set(n.name,n);var oa=(n,t)=>{var e,r;return n==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,n)?(e=t[n])!=null?e:null:(r=nm.get(n))!=null?r:null},di=(n,t,e,r,o)=>{if(!o)return n;if(e!=null&&e.bufferContent)return e.bufferContent(n,r);if(!n)return n;if(t==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(t==="line"){let s=n.lastIndexOf(`
17
+ `);return s<0?"":n.slice(0,s)}return n},Gb=(n,t,e,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${e}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Qb=(n,t,e,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${e}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},el=/\s/,Xb=(n,t)=>{let e=n.parentNode;for(;e;){if(e.nodeType===1){let r=e;if(t.has(r.tagName.toLowerCase()))return!0}e=e.parentNode}return!1},Jb=(n,t,e)=>{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(el.test(s[i])){let c=i;for(;c<s.length&&el.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 g=i;for(;g<s.length&&!el.test(s[g]);)c.appendChild(Gb(r,s[g],t,e.value)),e.value+=1,g+=1;a.appendChild(c),i=g}o.replaceChild(a,n)},Yb=(n,t,e)=>{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(Qb(r,c,t,e.value)),e.value+=1));o.replaceChild(a,n)},sa=(n,t,e,r)=>{var f,u;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:Vb).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Xb(d,s)||i.push(d),d=a.nextNode();let c={value:(u=r==null?void 0:r.startIndex)!=null?u:0},g=t==="char"?Jb:Yb;for(let m of i)g(m,e,c);return o.innerHTML},pi=(n=document)=>{let t=n.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},aa=(n=document)=>{let t=n.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let e=n.createElement("div");return e.className="persona-stream-skeleton-line",t.appendChild(e),t},tm=new WeakMap,Zb=(n,t)=>{var s;if(!n.styles)return;let e=tm.get(t);if(e||(e=new Set,tm.set(t,e)),e.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;e.delete(n.name)}e.add(n.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,t.appendChild(o)},tl=new WeakMap,ey=(n,t)=>{if(!n.onAttach)return;let e=tl.get(t);if(e||(e=new Map,tl.set(t,e)),e.has(n.name))return;let r=n.onAttach(t);e.set(n.name,r)},rm=n=>{let t=tl.get(n);if(t){for(let e of t.values())typeof e=="function"&&e();t.clear()}},nl=(n,t)=>{Zb(n,t),ey(n,t)};function rl(n,t=Ln){let e=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(t),n.style.isolation="isolate",()=>{a&&(n.style.position=e),n.style.zIndex=r,n.style.isolation=o}}var ia=0,vo=null;function ol(n=document){var e;if(ia++,ia===1){let r=n.body,s=((e=n.defaultView)!=null?e:window).scrollY||n.documentElement.scrollTop;vo={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 t=!1;return()=>{var r;if(!t&&(t=!0,ia=Math.max(0,ia-1),ia===0&&vo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=vo.originalOverflow,o.style.position=vo.originalPosition,o.style.top=vo.originalTop,o.style.width=vo.originalWidth,s.scrollTo(0,vo.scrollY),vo=null}}}var la={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Cn=n=>{var t,e;return((e=(t=n==null?void 0:n.launcher)==null?void 0:t.mountMode)!=null?e:"floating")==="docked"},ca=n=>{var t,e;return((e=(t=n==null?void 0:n.launcher)==null?void 0:t.mountMode)!=null?e:"floating")==="composer-bar"},yr=n=>{var e,r,o,s,a,i;let t=(e=n==null?void 0:n.launcher)==null?void 0:e.dock;return{side:(r=t==null?void 0:t.side)!=null?r:la.side,width:(o=t==null?void 0:t.width)!=null?o:la.width,animate:(s=t==null?void 0:t.animate)!=null?s:la.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:la.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:la.maxHeight}};var vr={"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 ty="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ui=(n,t={})=>{var T,E,A,R,L,W;let{showClose:e=!0,wrapperClassName:r=ty,buttonSize:o,iconSize:s="28px"}=t,a=(T=n==null?void 0:n.launcher)!=null?T:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=y("div",r),c=(A=a.closeButtonTooltipText)!=null?A:"Close chat",g=(R=a.closeButtonShowTooltip)!=null?R:!0,f=(L=a.closeButtonIconName)!=null?L:"x",u=(W=a.closeButtonIconText)!=null?W:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Lt("button",{className:zs("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:e?void 0:"none",color:a.closeButtonColor||Fn.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}}),x=Ae(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=u,d.appendChild(v),g&&c){let C=null,k=()=>{if(C)return;let N=v.ownerDocument,M=N.body;if(!M)return;C=Hr(N,"div","persona-clear-chat-tooltip"),C.textContent=c;let U=Hr(N,"div");U.className="persona-clear-chat-tooltip-arrow",C.appendChild(U);let z=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(yo),C.style.left=`${z.left+z.width/2}px`,C.style.top=`${z.top-8}px`,C.style.transform="translate(-50%, -100%)",M.appendChild(C)},D=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",k),d.addEventListener("mouseleave",D),v.addEventListener("focus",k),v.addEventListener("blur",D),d._cleanupTooltip=()=>{D(),d.removeEventListener("mouseenter",k),d.removeEventListener("mouseleave",D),v.removeEventListener("focus",k),v.removeEventListener("blur",D)}}return{button:v,wrapper:d}},ny="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mi=(n,t={})=>{var C,k,D,N,M,U,z,ne,Le,je,ye,De,$e;let{wrapperClassName:e=ny,buttonSize:r,iconSize:o="20px"}=t,a=(k=((C=n==null?void 0:n.launcher)!=null?C:{}).clearChat)!=null?k:{},i=(D=r!=null?r:a.size)!=null?D:"32px",d=(N=a.iconName)!=null?N:"refresh-cw",c=(M=a.iconColor)!=null?M:"",g=(U=a.backgroundColor)!=null?U:"",f=(z=a.borderWidth)!=null?z:"",u=(ne=a.borderColor)!=null?ne:"",m=(Le=a.borderRadius)!=null?Le:"",v=(je=a.paddingX)!=null?je:"",x=(ye=a.paddingY)!=null?ye:"",T=(De=a.tooltipText)!=null?De:"Clear chat",E=($e=a.showTooltip)!=null?$e:!0,A=y("div",e),R=!!(f||u),L=Lt("button",{className:zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"hover:persona-bg-gray-100",!R&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:c||Fn.actionIconColor,backgroundColor:g||void 0,border:R?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),W=Ae(d,o,"currentColor",1);if(W&&(W.style.display="block",L.appendChild(W)),A.appendChild(L),E&&T){let Se=null,xe=()=>{if(Se)return;let Q=L.ownerDocument,oe=Q.body;if(!oe)return;Se=Hr(Q,"div","persona-clear-chat-tooltip"),Se.textContent=T;let ge=Hr(Q,"div");ge.className="persona-clear-chat-tooltip-arrow",Se.appendChild(ge);let de=L.getBoundingClientRect();Se.style.position="fixed",Se.style.zIndex=String(yo),Se.style.left=`${de.left+de.width/2}px`,Se.style.top=`${de.top-8}px`,Se.style.transform="translate(-50%, -100%)",oe.appendChild(Se)},re=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};A.addEventListener("mouseenter",xe),A.addEventListener("mouseleave",re),L.addEventListener("focus",xe),L.addEventListener("blur",re),A._cleanupTooltip=()=>{re(),A.removeEventListener("mouseenter",xe),A.removeEventListener("mouseleave",re),L.removeEventListener("focus",xe),L.removeEventListener("blur",re)}}return{button:L,wrapper:A}};var Fn={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))"},qo=n=>{var W,C,k,D,N,M,U,z,ne,Le,je,ye,De,$e,Se,xe;let{config:t,showClose:e=!0}=n,r=Lt("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=t==null?void 0:t.launcher)!=null?W:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(k=o.closeButtonPlacement)!=null?k:"inline",i=(D=o.headerIconHidden)!=null?D:!1,d=o.headerIconName,c=Lt("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 re=parseFloat(s)||24,Q=Ae(d,re*.6,"currentColor",1);Q?c.replaceChildren(Q):c.textContent=(M=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?M:"\u{1F4AC}"}else if((U=t==null?void 0:t.launcher)!=null&&U.iconUrl){let re=y("img");re.src=t.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(ne=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?ne:"\u{1F4AC}";let g=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Lt("span",{className:"persona-text-base persona-font-semibold",text:(je=(Le=t==null?void 0:t.launcher)==null?void 0:Le.title)!=null?je:"Chat Assistant",style:{color:Fn.titleColor}}),u=Lt("span",{className:"persona-text-xs",text:(De=(ye=t==null?void 0:t.launcher)==null?void 0:ye.subtitle)!=null?De:"Here to help you get answers fast",style:{color:Fn.subtitleColor}});g.append(f,u),i?r.append(g):r.append(c,g);let m=($e=o.clearChat)!=null?$e:{},v=(Se=m.enabled)!=null?Se:!0,x=(xe=m.placement)!=null?xe:"inline",T=null,E=null;if(v){let Q=mi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=Q.button,E=Q.wrapper,x==="top-right"&&(E.style.right="48px"),x==="inline"&&r.appendChild(E)}let A=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:R,wrapper:L}=ui(t,{showClose:e,wrapperClassName:A});return a!=="top-right"&&r.appendChild(L),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:u,closeButton:R,closeButtonWrapper:L,clearChatButton:T,clearChatButtonWrapper:E}},da=(n,t,e)=>{var a,i,d,c;let r=(a=e==null?void 0:e.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(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};function bs(n){let{items:t,onSelect:e,anchor:r,position:o="bottom-left",portal:s}=n,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(yo)):(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 t){if(m.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let T=Ae(m.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",T=>{T.stopPropagation(),g(),e(m.id)}),a.appendChild(v)}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=v=>{!a.contains(v.target)&&!r.contains(v.target)&&g()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function g(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():g()}function u(){g(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:g,toggle:f,destroy:u}}function In(n){let{icon:t,label:e,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",e),d.title=e;let c=Ae(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[g,f]of Object.entries(i))d.setAttribute(g,f);return d}function sl(n){let{icon:t,label:e,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 g=y("button",c);if(g.type="button",g.setAttribute("aria-label",e),t){let u=Ae(t,s!=null?s:14,"currentColor",2);u&&g.appendChild(u)}let f=y("span");if(f.textContent=e,g.appendChild(f),i&&g.addEventListener("click",i),d)for(let[u,m]of Object.entries(d))g.setAttribute(u,m);return g}function om(n){var m,v;let{label:t,icon:e="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,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",t);let g=y("span","persona-combo-btn-label");g.textContent=t,c.appendChild(g);let f=Ae(e,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=(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,T;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(T=d.border)!=null?T:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let u=bs({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(u.element),c.addEventListener("click",x=>{x.stopPropagation();let T=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),u.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{g.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),u.show()},close:()=>{c.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let x=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),c.remove()}}}var ry=n=>{var r;let t=qo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),e=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(e){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>e()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),e())}))}return t};function oy(n,t,e){var r,o,s;if(t!=null&&t.length)for(let a of t){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=Ae(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=bs({items:a.menuItems,onSelect:g=>e==null?void 0:e(g),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",g=>{g.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>e==null?void 0:e(a.id)),n.appendChild(i)}}var sy=n=>{var A,R,L,W,C,k,D,N,M;let{config:t,showClose:e=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(A=t==null?void 0:t.launcher)!=null?A:{},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,g;if(d)c=om({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Fn.titleColor,g=(L=c.querySelector(".persona-combo-btn-label"))!=null?L:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=y("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Fn.titleColor,g.textContent=(W=a.title)!=null?W:"Chat Assistant",c.appendChild(g),oy(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 z=o.onTitleClick;c.addEventListener("click",ne=>{ne.target.closest("button")||z()}),c.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),z())})}let U=o==null?void 0:o.titleRowHover;U&&(c.style.borderRadius=(k=U.borderRadius)!=null?k:"10px",c.style.padding=(D=U.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 z,ne;c.style.backgroundColor=(z=U.background)!=null?z:"",c.style.borderColor=(ne=U.border)!=null?ne:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(N=a.closeButtonSize)!=null?N:"32px",u=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=e?"":"none",m.style.color=a.closeButtonColor||Fn.actionIconColor;let v=(M=a.closeButtonIconName)!=null?M:"x",x=Ae(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),u.appendChild(m),i.appendChild(u);let T=y("div");T.style.display="none";let E=y("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:g,headerSubtitle:E,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},sm={default:ry,minimal:sy},ay=n=>{var t;return(t=sm[n])!=null?t:sm.default},gi=(n,t,e)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:e==null?void 0:e.onClose,onClearChat:e==null?void 0:e.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),g=y("div");g.style.display="none";let f=y("span"),u=y("span"),m=y("button");m.style.display="none";let v=y("div");return v.style.display="none",{header:c,iconHolder:g,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=ay(r)({config:n,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:e==null?void 0:e.showClose)!=null?d:!0,onClose:e==null?void 0:e.onClose,onClearChat:e==null?void 0:e.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var fi=n=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let e=3,r=20;t.style.maxHeight=`${e*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:e*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},hi=n=>{var W,C,k,D,N,M,U,z,ne,Le,je,ye;let t=(W=n==null?void 0:n.sendButton)!=null?W:{},e=(C=t.useIcon)!=null?C:!1,r=(k=t.iconText)!=null?k:"\u2191",o=t.iconName,s=(D=t.stopIconName)!=null?D:"square",a=(N=t.tooltipText)!=null?N:"Send message",i=(M=t.stopTooltipText)!=null?M:"Stop generating",d=(z=(U=n==null?void 0:n.copy)==null?void 0:U.sendButtonLabel)!=null?z:"Send",c=(Le=(ne=n==null?void 0:n.copy)==null?void 0:ne.stopButtonLabel)!=null?Le:"Stop",g=(je=t.showTooltip)!=null?je:!1,f=(ye=t.size)!=null?ye:"40px",u=t.backgroundColor,m=t.textColor,v=y("div","persona-send-button-wrapper"),x=Lt("button",{className:zs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",e?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",e&&!u&&"persona-bg-persona-primary",!e&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:e?f:void 0,height:e?f:void 0,minWidth:e?f:void 0,minHeight:e?f:void 0,fontSize:e?"18px":void 0,lineHeight:e?"1":void 0,color:e?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:e&&u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,E=null;if(e){let De=parseFloat(f)||24,$e=(m==null?void 0:m.trim())||"currentColor";o?(T=Ae(o,De,$e,2),T?x.appendChild(T):x.textContent=r):x.textContent=r,E=Ae(s,De,$e,2)}else x.textContent=d;let A=null;g&&a&&(A=y("div","persona-send-button-tooltip"),A.textContent=a,v.appendChild(A)),x.setAttribute("aria-label",a),v.appendChild(x);let R="send";return{button:x,wrapper:v,setMode:De=>{if(De===R)return;R=De;let $e=De==="stop"?i:a;if(x.setAttribute("aria-label",$e),A&&(A.textContent=$e),e){if(T&&E){let Se=De==="stop"?E:T;x.replaceChildren(Se)}}else x.textContent=De==="stop"?c:d}}},bi=n=>{var A,R,L,W,C,k,D,N,M,U,z,ne;let t=(A=n==null?void 0:n.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((R=t.provider)==null?void 0:R.type)==="runtype";if(!(r||o))return null;let a=(W=(L=n==null?void 0:n.sendButton)==null?void 0:L.size)!=null?W:"40px",i=(C=t.iconName)!=null?C:"mic",d=(k=t.iconSize)!=null?k:a,c=parseFloat(d)||24,g=(N=t.backgroundColor)!=null?N:(D=n==null?void 0:n.sendButton)==null?void 0:D.backgroundColor,f=(U=t.iconColor)!=null?U:(M=n==null?void 0:n.sendButton)==null?void 0:M.textColor,u=y("div","persona-send-button-wrapper"),m=Lt("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:g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=Ae(i,c,f||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",u.appendChild(m);let T=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((ne=t.showTooltip)!=null?ne:!1)&&T){let Le=y("div","persona-send-button-tooltip");Le.textContent=T,u.appendChild(Le)}return{button:m,wrapper:u}},yi=n=>{var v,x,T,E,A,R,L,W;let t=(v=n==null?void 0:n.attachments)!=null?v:{};if(t.enabled!==!0)return null;let e=(T=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?T:"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=((E=t.allowedTypes)!=null?E:Gr).join(","),o.multiple=((A=t.maxFiles)!=null?A:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(R=t.buttonIconName)!=null?R:"paperclip",a=e,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),g=Lt("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":(L=t.buttonTooltipText)!=null?L:"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"}});g.addEventListener("mouseenter",()=>{g.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="transparent"});let f=Ae(s,d,"currentColor",1.5);f?g.appendChild(f):g.textContent="\u{1F4CE}",g.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(g);let u=(W=t.buttonTooltipText)!=null?W:"Attach file",m=y("div","persona-send-button-tooltip");return m.textContent=u,c.appendChild(m),{button:g,wrapper:c,input:o,previewsContainer:r}},vi=n=>{var a,i,d;let t=(a=n==null?void 0:n.statusIndicator)!=null?a:{},e=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${e} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.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},xi=()=>Lt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var wi=n=>{var v,x,T,E,A,R;let{config:t}=n,e=Lt("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=xi(),o=Lt("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}=fi(t);a();let i=hi(t),d=bi(t),c=yi(t),g=vi(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Lt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=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&&u.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(u,m),o.append(f),o.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),e.append(r,o,g),{footer:e,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:g,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(A=c==null?void 0:c.input)!=null?A:null,attachmentPreviewsContainer:(R=c==null?void 0:c.previewsContainer)!=null?R:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var am=()=>{let n=Lt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),e=Ae("message-square",16,"currentColor",1.5);e&&t.appendChild(e);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=Ae("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(t,r,o),{root:n,textNode:r}},im=n=>{var v,x,T,E,A,R;let{config:t}=n,e=Lt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=xi();r.style.display="none";let o=vi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=fi(t);s.style.maxHeight="100px",a();let i=hi(t),d=bi(t),c=yi(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let g=Lt("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 u=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),g.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&g.append(c.input),g.append(f,s,u),c&&e.append(c.previewsContainer),e.append(g,r,o);let m=g;return{footer:e,suggestions:r,composerForm:g,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:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(A=c==null?void 0:c.input)!=null?A:null,attachmentPreviewsContainer:(R=c==null?void 0:c.previewsContainer)!=null?R:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var lm=n=>{var g,f,u,m,v,x,T,E,A,R,L,W,C,k,D,N,M;let t=(f=(g=n==null?void 0:n.launcher)==null?void 0:g.enabled)!=null?f:!0,e=Cn(n);if(ca(n)){let U=(m=(u=n==null?void 0:n.launcher)==null?void 0:u.composerBar)!=null?m:{},z=y("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(v=U.expandedSize)!=null?v:"anchored",z.style.zIndex=String((T=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?T:Ln);let ne=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",z.appendChild(ne);let Le=y("div","persona-widget-pill-root");return Le.setAttribute("data-persona-composer-bar",""),Le.dataset.state="collapsed",Le.dataset.expandedSize=(E=U.expandedSize)!=null?E:"anchored",Le.style.zIndex=String((R=(A=n==null?void 0:n.launcher)==null?void 0:A.zIndex)!=null?R:Ln),{wrapper:z,panel:ne,pillRoot:Le}}if(e){let U=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(z),{wrapper:U,panel:z}}if(!t){let U=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(W=(L=n==null?void 0:n.launcher)==null?void 0:L.width)!=null?W:"100%";return U.style.width=ne,z.style.width="100%",U.appendChild(z),{wrapper:U,panel:z}}let o=(C=n==null?void 0:n.launcher)!=null?C:{},s=o.position&&vr[o.position]?vr[o.position]:vr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((D=(k=n==null?void 0:n.launcher)==null?void 0:k.zIndex)!=null?D:Ln);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(M=(N=n==null?void 0:n.launcher)==null?void 0:N.width)!=null?M:n==null?void 0:n.launcherWidth,c=d!=null?d:Qr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},iy=(n,t)=>{var L,W,C,k,D,N,M,U,z;let e=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");e.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=ui(n,{showClose:t,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=(L=n==null?void 0:n.launcher)==null?void 0:L.clearChat)==null?void 0:W.enabled)!=null?C:!0,a=null,i=null;if(s){let ne=mi(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Lt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Lt("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 g=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(k=n==null?void 0:n.copy)==null?void 0:k.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),f=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(M=(N=n==null?void 0:n.copy)==null?void 0:N.welcomeSubtitle)!=null?M:"Ask anything about your account or products."}),u=Lt("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))"}},g,f),m=y("div","persona-flex persona-flex-col persona-gap-3"),v=(U=n==null?void 0:n.layout)==null?void 0:U.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((z=n==null?void 0:n.copy)==null?void 0:z.showWelcomeCard)!==!1||(u.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(u,m);let T=Lt("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"}}),E=im({config:n}),{root:A,textNode:R}=am();return e.append(d,o,c,T),i&&e.appendChild(i),{container:e,body:c,messagesWrapper:m,composerOverlay:T,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:g,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:R}},cm=(n,t=!0)=>{var T,E,A,R,L,W,C,k,D;if(ca(n))return iy(n,t);let e=Lt("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=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=((E=n==null?void 0:n.layout)==null?void 0:E.showHeader)!==!1,s=r?gi(n,r,{showClose:t}):qo({config:n,showClose:t}),a=Lt("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=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(R=(A=n==null?void 0:n.copy)==null?void 0:A.welcomeTitle)!=null?R:"Hello \u{1F44B}"}),d=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),c=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:Cn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),g=y("div","persona-flex persona-flex-col persona-gap-3"),f=(C=n==null?void 0:n.layout)==null?void 0:C.contentMaxWidth;f&&(g.style.maxWidth=f,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((k=n==null?void 0:n.copy)==null?void 0:k.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,g);let m=wi({config:n}),v=((D=n==null?void 0:n.layout)==null?void 0:D.showFooter)!==!1;o?da(e,s,n):(s.header.style.display="none",da(e,s,n)),e.append(a);let x=Lt("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||(m.footer.style.display="none"),e.append(m.footer),e.append(x),{container:e,body:a,messagesWrapper:g,composerOverlay:x,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 al=(n,t)=>{let e=y("button");e.type="button",e.innerHTML=`
18
18
  <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>
19
19
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
20
20
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -22,14 +22,14 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
22
22
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
23
23
  </span>
24
24
  <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>
25
- `,t.addEventListener("click",e);let r=s=>{var N,P,W,C,I,B,D,T,q,z,re,ke,Ve;let a=(N=s.launcher)!=null?N:{},i=wn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let be=(P=a.title)!=null?P:"Chat Assistant";d.textContent=be,d.setAttribute("title",be)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let be=(W=a.subtitle)!=null?W:"Here to help you get answers fast";c.textContent=be,c.setAttribute("title",be)}let g=t.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let be=(C=a.agentIconSize)!=null?C:"40px";if(f.style.height=be,f.style.width=be,f.innerHTML="",a.agentIconName){let He=parseFloat(be)||24,Fe=Ae(a.agentIconName,He*.6,"var(--persona-text-inverse, #ffffff)",2);Fe?(f.appendChild(Fe),f.style.display=""):(f.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",f.style.display="")}let u=t.querySelector("[data-role='launcher-image']");if(u){let be=(D=a.agentIconSize)!=null?D:"40px";u.style.height=be,u.style.width=be,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let be=(T=a.callToActionIconSize)!=null?T:"32px";m.style.height=be,m.style.width=be,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 He=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,He=(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 Fe=parseFloat(be)||24,Se=Math.max(Fe-He,8),xe=Ae(a.callToActionIconName,Se,"currentColor",2);xe?m.appendChild(xe):m.textContent=(q=a.callToActionIconText)!=null?q:"\u2197"}else m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let v=a.position&&xr[a.position]?xr[a.position]:xr["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",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";t.className=i?M:`${x} ${v}`,i||(t.style.zIndex=String((re=a.zIndex)!=null?re:Mn));let E="1px solid var(--persona-border, #e5e7eb)",k="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=(ke=a.border)!=null?ke:E,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:k,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=(Ve=a.collapsedMaxWidth)!=null?Ve:"",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 sm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=rm(n),s=om(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:u=>(d.element.replaceWith(u.header),d.element=u.header,d.iconHolder=u.iconHolder,d.headerTitle=u.headerTitle,d.headerSubtitle=u.headerSubtitle,d.closeButton=u.closeButton,d.closeButtonWrapper=u.closeButtonWrapper,d.clearChatButton=u.clearChatButton,d.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{c.footer.replaceWith(u),c.footer=u}}},ol=({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:()=>rl(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=rl(n,t);return{instance:o,element:o.element}};var nb=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}},rb=(n,e)=>{if(!n)return null;let t=nb(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},ob=(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},sb=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},sl=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(":"))},al=320,im=320,ab=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ib=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),lb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),cb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),db=(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=`${al}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 g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),sb(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},pb=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(!sl(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=`${al}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},ub=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(!sl(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=`${al}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),t+=1}),t===0?(e.remove(),null):e}catch{return null}},mb=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(!sl(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}},pa=()=>{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},gb=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:pa};if(e){let o=e(r);if(o!==null)return o}return pa()},fb=(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},am=(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},hb=(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},yb=(n,e,t)=>{var v,x,M,E,k,N,P;let r=(v=e.showCopy)!=null?v:!0,o=(x=e.showUpvote)!=null?x:!0,s=(M=e.showDownvote)!=null?M:!0,a=(E=e.showReadAloud)!=null?E:!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=(k=e.visibility)!=null?k:"hover",d=(N=e.align)!=null?N:"right",c=(P=e.layout)!=null?P:"pill-inside",g={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],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${g} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${n.id}`,u.setAttribute("data-actions-for",n.id);let m=(W,C,I)=>{let B=En({icon:W,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",I),B};return r&&u.appendChild(m("copy","Copy message","copy")),a&&u.appendChild(m("volume-2","Read aloud","read-aloud")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},il=(n,e,t,r,o,s)=>{var oe,G,se,ge,pe,j,ae,Ie,ee,Z,ne,at,it,ot,Me,fe,Xe;let a=t!=null?t:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,g=(G=d==null?void 0:d.show)!=null?G:!1,f=(se=c==null?void 0:c.show)!=null?se:!1,u=(ge=d==null?void 0:d.position)!=null?ge:"left",m=(pe=c==null?void 0:c.position)!=null?pe:"below",v=hb(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 M=ab(n),E=(ae=(j=n.content)==null?void 0:j.trim())!=null?ae:"",N=M.length>0&&E===Ka,P=ai((ee=(Ie=s==null?void 0:s.widgetConfig)==null?void 0:Ie.features)==null?void 0:ee.streamAnimation),W=(at=(ne=(Z=s==null?void 0:s.widgetConfig)==null?void 0:Z.features)==null?void 0:ne.streamAnimation)==null?void 0:at.plugins,C=n.role==="assistant"&&P.type!=="none"?oa(P.type,W):null,I=n.role==="assistant"&&((it=C==null?void 0:C.isAnimating)==null?void 0:it.call(C,n))===!0,B=n.role==="assistant"&&C!==null&&(!!n.streaming||I);B&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),B&&C&&(C.containerClass&&D.classList.add(C.containerClass),D.style.setProperty("--persona-stream-step",`${P.speed}ms`),D.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let T=B?ii((ot=n.content)!=null?ot:"",P.buffer,C,n,!!n.streaming):(Me=n.content)!=null?Me:"",q=e({text:T,message:n,streaming:!!n.streaming,raw:n.rawContent}),z=q;B&&(C==null?void 0:C.wrap)==="char"?z=sa(q,"char",n.id,{skipTags:C.skipTags}):B&&(C==null?void 0:C.wrap)==="word"&&(z=sa(q,"word",n.id,{skipTags:C.skipTags}));let re=null;if(N?(re=document.createElement("div"),re.innerHTML=z,re.style.display="none",D.appendChild(re)):D.innerHTML=z,B&&(C!=null&&C.useCaret)&&!N&&E){let J=li(),ue=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ee=ue[ue.length-1];if(Ee!=null&&Ee.parentNode)Ee.parentNode.insertBefore(J,Ee.nextSibling);else{let Je=D.lastElementChild;Je?Je.appendChild(J):D.appendChild(J)}}if(f&&m==="inline"&&n.createdAt){let J=am(n,c,"span");J.classList.add("persona-timestamp-inline");let ue=D.lastElementChild;ue?ue.appendChild(J):D.appendChild(J)}if(M.length>0){let J=db(M,!N&&!!E,()=>{N&&re&&(re.style.display="")});J?x.appendChild(J):N&&re&&(re.style.display="")}let ke=ib(n);if(ke.length>0){let J=pb(ke);J&&x.appendChild(J)}let Ve=lb(n);if(Ve.length>0){let J=ub(Ve);J&&x.appendChild(J)}let be=cb(n);if(be.length>0){let J=mb(be);J&&x.appendChild(J)}if(x.appendChild(D),f&&m==="below"&&n.createdAt){let J=am(n,c);J.classList.add("persona-mt-1"),x.appendChild(J)}let He=n.role==="assistant"?rb(n.stopReason,(Xe=(fe=s==null?void 0:s.widgetConfig)==null?void 0:fe.copy)==null?void 0:Xe.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let J=!!(T&&T.trim()),ue=P.placeholder==="skeleton",Ee=ue&&P.buffer==="line"&&J;if(J)Ee&&x.appendChild(aa());else if(ue)x.appendChild(aa());else{let Je=gb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Je&&x.appendChild(Je)}}if(He&&n.stopReason&&!n.streaming&&(E||(D.style.display="none"),x.appendChild(ob(n.stopReason,He))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=yb(n,r,o);x.appendChild(J)}if(!g||n.role==="system")return x;let Se=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),xe=fb(d,n.role);return u==="right"||u==="left"&&n.role==="user"?Se.append(x,xe):Se.append(xe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Se};var vs=new Set,bb=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),vb=(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(`
26
- `):""},lm=(n,e)=>{let t=vs.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=Ae(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")},ll=(n,e)=>{var Ve,be,He,Fe,Se,xe,oe,G,se,ge,pe;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=(be=(Ve=e==null?void 0:e.features)==null?void 0:Ve.reasoningDisplay)!=null?be:{},s=o.expandable!==!1,a=s&&vs.has(n.id),i=t.status!=="complete",d=vb(n,(He=o.previewMaxLines)!=null?He: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 g=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(Fe=e==null?void 0:e.reasoning)!=null?Fe:{},v=String((Se=t.startedAt)!=null?Se:Date.now()),x=()=>{let j=b("span","");return j.setAttribute("data-tool-elapsed",v),j.textContent=Ua(t),j},M=(xe=m.renderCollapsedSummary)==null?void 0:xe.call(m,{message:n,reasoning:t,defaultSummary:u,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ua(t),createElapsedElement:x});typeof M=="string"&&M.trim()?(f.textContent=M,g.appendChild(f)):M instanceof HTMLElement?g.appendChild(M):(f.textContent=u,g.appendChild(f));let E=b("span","persona-text-xs persona-text-persona-primary");E.textContent=du(t),g.appendChild(E);let k=(oe=o.loadingAnimation)!=null?oe:"none",N=m.activeTextTemplate,P=m.completeTextTemplate,W=i?N:P,C=M instanceof HTMLElement,I=(j,ae,Ie)=>{let ee=Ie;for(let Z of ae){let ne=b("span","persona-tool-char");ne.style.setProperty("--char-index",String(ee)),ne.textContent=Z===" "?"\xA0":Z,j.appendChild(ne),ee++}return ee},B=(j,ae)=>{f.textContent="";let Ie=qa(j,""),ee=0;for(let Z of Ie){let ne=Z.styles.length>0?(()=>{let at=b("span",Z.styles.map(it=>`persona-tool-text-${it}`).join(" "));return f.appendChild(at),at})():f;if(Z.isDuration&&i)ne.appendChild(x());else{let at=Z.isDuration?Ua(t):Z.text;ae?ee=I(ne,at,ee):ne.appendChild(document.createTextNode(at))}}};if(!C&&W)if(E.style.display="none",f.style.display="",i&&k!=="none"){let j=(G=m.loadingAnimationDuration)!=null?G:2e3;f.setAttribute("data-preserve-animation","true"),k==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),B(W,!1)):(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),k==="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)),B(W,!0))}else B(W,!1);else if(!C&&i&&k!=="none"){f.style.display="";let j=(se=m.loadingAnimationDuration)!=null?se:2e3;if(f.setAttribute("data-preserve-animation","true"),k==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`);else{f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${j}ms`),k==="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 ae=f.textContent||u;f.textContent="",I(f,ae,0)}t.status==="complete"&&(f.style.display="none")}else C||(t.status==="complete"?f.style.display="none":f.style.display="");let D=null;if(s){D=b("div","persona-flex persona-items-center");let ae=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?D.appendChild(ae):D.textContent=a?"Hide":"Show";let Ie=b("div","persona-flex persona-items-center persona-ml-auto");Ie.append(D),c.append(g,Ie)}else c.append(g);let T=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(T.setAttribute("data-persona-collapsed-preview","reasoning"),T.style.display="none",T.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let j=(pe=(ge=e==null?void 0:e.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:pe.call(ge,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});bb(T,j)||(T.textContent=d),T.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,T),r;let q=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");q.style.display=a?"":"none";let z=t.chunks.join(""),re=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return re.textContent=z||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),q.appendChild(re),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let ae=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?D.appendChild(ae):D.textContent=a?"Hide":"Show"}q.style.display=a?"":"none",T.style.display=a?"none":T.textContent||T.childNodes.length?"":"none"})(),r.append(c,T,q),r};var xs=new Set,xb=(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(`
27
- `);let o=us(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
28
- `):""},Cb=(n,e)=>{var g,f,u,m,v;let t=n.toolCall,r=(g=e==null?void 0:e.features)==null?void 0:g.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=wb(n,(u=r==null?void 0:r.previewMaxLines)!=null?u:3),a=t?pu(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},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=qi(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=qi(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},cm=(n,e,t)=>{var g;let r=xs.has(n),o=(g=t==null?void 0:t.toolCall)!=null?g:{},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||"currentColor",u=Ae(r?"chevron-up":"chevron-down",16,f,2);u?c.appendChild(u):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},cl=(n,e)=>{var z,re,ke,Ve,be,He,Fe,Se,xe;let t=n.toolCall,r=(z=e==null?void 0:e.toolCall)!=null?z:{},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=(ke=(re=e==null?void 0:e.features)==null?void 0:re.toolCallDisplay)!=null?ke:{},a=s.expandable!==!1,i=a&&xs.has(n.id),{summary:d,previewText:c,isActive:g}=Cb(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 u=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((Ve=t.startedAt)!=null?Ve:Date.now()),x=()=>{let oe=b("span","");return oe.setAttribute("data-tool-elapsed",v),oe.textContent=Qs(t),oe},M=(He=r.renderCollapsedSummary)==null?void 0:He.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(be=s.collapsedMode)!=null?be:"tool-call",isActive:g,config:e!=null?e:{},elapsed:Qs(t),createElapsedElement:x});typeof M=="string"&&M.trim()?(m.textContent=M,u.appendChild(m)):M instanceof HTMLElement?u.appendChild(M):(m.textContent=d,u.appendChild(m));let E=(Fe=s.loadingAnimation)!=null?Fe:"none",k=r.activeTextTemplate,N=r.completeTextTemplate,P=g?k:N,W=M instanceof HTMLElement,C=(oe,G,se)=>{let ge=se;for(let pe of G){let j=b("span","persona-tool-char");j.style.setProperty("--char-index",String(ge)),j.textContent=pe===" "?"\xA0":pe,oe.appendChild(j),ge++}return ge},I=(oe,G)=>{var j;m.textContent="";let se=((j=t.name)==null?void 0:j.trim())||"tool",ge=qa(oe,se),pe=0;for(let ae of ge){let Ie=ae.styles.length>0?(()=>{let ee=b("span",ae.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(ee),ee})():m;if(ae.isDuration&&g)Ie.appendChild(x());else{let ee=ae.isDuration?Qs(t):ae.text;G?pe=C(Ie,ee,pe):Ie.appendChild(document.createTextNode(ee))}}};if(!W)if(g&&E!=="none"){let oe=(Se=r.loadingAnimationDuration)!=null?Se:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),P&&I(P,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),E==="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)),P)I(P,!0);else{let G=m.textContent||d;m.textContent="",C(m,G,0)}}else P&&I(P,!1);let B=null;if(a){B=b("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"currentColor",G=Ae(i?"chevron-up":"chevron-down",16,oe,2);G?B.appendChild(G):B.textContent=i?"Hide":"Show";let se=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(B),f.append(u,se)}else f.append(u);let D=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&g&&s.activePreview&&c){let oe=(xe=r.renderCollapsedPreview)==null?void 0:xe.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:g,config:e!=null?e:{}});xb(D,oe)||(D.textContent=c),D.style.display=""}if(!i&&g&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,D),o;let T=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(T.style.display=i?"":"none",r.contentBackgroundColor&&(T.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(T.style.color=r.contentTextColor),r.contentPaddingX&&(T.style.paddingLeft=r.contentPaddingX,T.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(T.style.paddingTop=r.contentPaddingY,T.style.paddingBottom=r.contentPaddingY),t.name){let oe=b("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=t.name,T.appendChild(oe)}if(t.args!==void 0){let oe=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(G.style.color=r.labelTextColor),G.textContent="Arguments";let se=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=us(t.args),oe.append(G,se),T.appendChild(oe)}if(t.chunks&&t.chunks.length){let oe=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(G.style.color=r.labelTextColor),G.textContent="Activity";let se=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=t.chunks.join(""),oe.append(G,se),T.appendChild(oe)}if(t.status==="complete"&&t.result!==void 0){let oe=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(G.style.color=r.labelTextColor),G.textContent="Result";let se=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=us(t.result),oe.append(G,se),T.appendChild(oe)}if(t.status==="complete"&&typeof t.duration=="number"){let oe=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${t.duration}ms`,T.appendChild(oe)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),B){B.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"currentColor",G=Ae(i?"chevron-up":"chevron-down",16,oe,2);G?B.appendChild(G):B.textContent=i?"Hide":"Show"}T.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),o.append(f,D,T),o};var vi=new Map,Ab=n=>{let t=(n.startsWith(Bo)?n.slice(Bo.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)},dm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,pm=(n,e)=>{var r,o,s;let t=(o=(r=dm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=vi.get(n))!=null?s:t==="expanded"},um=(n,e,t)=>{var a,i;let r=dm(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=Ae(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},mm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=pm(n,t);um(r,s,t),o.style.display=s?"":"none"};var xi=(n,e)=>{var I,B,D,T,q,z,re,ke,Ve,be,He,Fe,Se,xe,oe;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=(B=r==null?void 0:r.borderColor)!=null?B:"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)":(D=r==null?void 0:r.titleColor)!=null?D:"currentColor",g=Ae(d,20,c,2);g&&i.appendChild(g);let f=b("div","persona-flex-1 persona-min-w-0"),u=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(T=r==null?void 0:r.title)!=null?T:"Approval Required",u.appendChild(m),!o){let G=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");G.setAttribute("data-approval-status",t.status),t.status==="approved"?(G.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",G.style.color="var(--persona-palette-colors-success-700, #15803d)",G.textContent="Approved"):t.status==="denied"?(G.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",G.style.color="var(--persona-palette-colors-error-700, #b91c1c)",G.textContent="Denied"):t.status==="timeout"&&(G.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",G.style.color="var(--persona-palette-colors-warning-700, #b45309)",G.textContent="Timeout"),u.appendChild(G)}f.appendChild(u);let x=t.toolType==="webmcp"||t.toolName.startsWith(Bo)?Wi(t.toolName):void 0,M=(q=r==null?void 0:r.formatDescription)==null?void 0:q.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),E=!t.toolName,k=M||(E?t.description:`The assistant wants to use \u201C${x!=null?x:Ab(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=k,f.appendChild(N),t.reason){let G=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");G.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?G.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(G.style.color=r.descriptionColor);let se=b("span","persona-font-medium");se.textContent=`${(z=r==null?void 0:r.reasonLabel)!=null?z:"Agent's stated reason:"} `,G.appendChild(se),G.appendChild(document.createTextNode(t.reason)),f.appendChild(G)}let P=(re=r==null?void 0:r.detailsDisplay)!=null?re:"collapsed",W=!!t.description&&!E,C=W||!!t.parameters;if(P!=="hidden"&&C){let G=pm(n.id,e),se=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");se.type="button",se.setAttribute("data-expand-header","true"),se.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let ge=b("span");ge.setAttribute("data-approval-details-label","true");let pe=b("span","persona-inline-flex persona-items-center");pe.setAttribute("data-approval-details-chevron","true"),se.append(ge,pe),um(se,G,e),f.appendChild(se);let j=b("div");if(j.setAttribute("data-approval-details","true"),j.style.display=G?"":"none",W){let ae=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor),ae.textContent=t.description,j.appendChild(ae)}if(t.parameters){let ae=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&&(ae.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ae.style.color=r.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=us(t.parameters),j.appendChild(ae)}f.appendChild(j)}if(o){let G=b("div","persona-flex persona-gap-2 persona-mt-2");G.setAttribute("data-approval-buttons","true");let se=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");se.type="button",se.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",se.style.color=(Ve=r==null?void 0:r.approveButtonTextColor)!=null?Ve:"#ffffff",se.setAttribute("data-approval-action","approve");let ge=Ae("shield-check",14,(be=r==null?void 0:r.approveButtonTextColor)!=null?be:"#ffffff",2);ge&&(ge.style.marginRight="4px",se.appendChild(ge));let pe=document.createTextNode((He=r==null?void 0:r.approveLabel)!=null?He:"Approve");se.appendChild(pe);let j=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");j.type="button",j.style.backgroundColor=(Fe=r==null?void 0:r.denyButtonColor)!=null?Fe:"transparent",j.style.color=(Se=r==null?void 0:r.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let ae=Ae("shield-x",14,(xe=r==null?void 0:r.denyButtonTextColor)!=null?xe:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",j.appendChild(ae));let Ie=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");j.appendChild(Ie),G.append(se,j),f.appendChild(G)}return a.append(i,f),s.appendChild(a),s};var gm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let g=(c==null?void 0:c.agentPushed)===!0;if(g||(t=null),!o||!o.length||!g&&(i!=null?i:s?s.getMessages():[]).some(M=>M.role==="user"))return;let f=document.createDocumentFragment(),u=s?s.isStreaming():!1,m=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=u,d!=null&&d.fontFamily&&(x.style.fontFamily=m(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="",g&&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),g){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ua=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 ma=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 Sb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Tb=new Set(["step_start","execution_start"]),Mb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Eb=new Set(["step_complete","agent_turn_complete"]),kb=new Set(["flow_complete","agent_complete"]),fm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),ym=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),er=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,qo=(n,e)=>{let t=n[e];return ym(t)?t:void 0};function dl(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function wi(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Lb(n,e){return typeof e.type=="string"?e.type:n}function Pb(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 Ib(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 hm(n){var r,o,s,a,i;let e=qo(n,"result"),t=[qo(n,"tokens"),qo(n,"totalTokens"),e?qo(e,"tokens"):void 0,qo(n,"usage"),e?qo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=er(d.output))!=null?r:er(d.outputTokens))!=null?o:er(d.completionTokens);if(c!==void 0)return c}return(i=(s=er(n.outputTokens))!=null?s:er(n.completionTokens))!=null?i:e?(a=er(e.outputTokens))!=null?a:er(e.completionTokens):void 0}function Wb(n){var t,r,o,s,a;let e=qo(n,"result");return(a=(o=(r=(t=er(n.executionTime))!=null?t:er(n.executionTimeMs))!=null?r:er(n.execution_time))!=null?o:er(n.duration))!=null?a:e?(s=er(e.executionTime))!=null?s:er(e.executionTimeMs):void 0}function Rb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ga=class{constructor(e=Rb){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:wi(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(!ym(t)){fm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Lb(e,t),o=this.now();if(Sb.has(r)){this.startRun(o);return}if(Tb.has(r)){this.run||this.startRun(o);return}if(Mb.has(r)){if(!Ib(r,t))return;let a=Pb(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+dl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:wi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Eb.has(r)){if(!this.run)return;let a=this.run,i=hm(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+dl(a.visibleCharCount),g=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:wi(c,g),outputTokens:c,durationMs:g,source:d?"usage":"estimate"};return}if(kb.has(r)){if(!this.run)return;let a=this.run,i=hm(t),d=i!=null?i:a.exactOutputTokens+dl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",g=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:wi(d,g),outputTokens:d,durationMs:g,source:c},this.run=null;return}if(fm.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=Wb(t);return s!=null?s:r-e.startedAt}};function ws(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Hb={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)"}},Bb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Db=["flowName","stepName","reasoningText","text","name","tool","toolName"],Nb=100;function Fb(n,e){let t={...Hb,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Bb}function Ob(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function _b(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 $b(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 Ub(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 qb(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 zb(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Vb(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 jb(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 pl(n,e,t,r,o,s,a,i){var u;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");ws(c,(u=r.classNames)==null?void 0:u.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var z,re;let m=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"),M=Ae(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&x.appendChild(M);let E=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(z=r.timestampFormat)!=null?z:"relative";E.textContent=k==="relative"?Ob(n.timestamp,t):_b(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 P=Fb(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=P.bg,W.style.color=P.text,W.style.borderColor=P.text+"50",W.textContent=n.type;let C=(re=r.descriptionFields)!=null?re:Db,I=$b(n.payload,C),B=null;I&&(B=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=I);let D=b("div","persona-flex-1 persona-min-w-0"),T=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"),q=Ae("clipboard","12px","currentColor",1.5);return q&&T.appendChild(q),T.addEventListener("click",async ke=>{ke.stopPropagation(),await Ub(qb(n)),T.innerHTML="";let Ve=Ae("check","12px","currentColor",1.5);Ve&&T.appendChild(Ve),setTimeout(()=>{T.innerHTML="";let be=Ae("clipboard","12px","currentColor",1.5);be&&T.appendChild(be)},1500)}),v.appendChild(x),v.appendChild(E),N&&v.appendChild(N),v.appendChild(W),B&&v.appendChild(B),v.appendChild(D),v.appendChild(T),m.appendChild(v),d&&m.appendChild(jb(n,a,i)),m}}function bm(n){var v,x,M,E,k;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",g=(M=i==null?void 0:i.label)!=null?M:"",f=(k=(E=o==null?void 0:o.features)==null?void 0:E.eventStream)!=null?k:{},u=s.find(N=>N.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let N=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(N)return{element:N,update:()=>{},destroy:()=>{}}}return m();function m(){let N=f.classNames,P=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ws(P,N==null?void 0:N.panel);let W=[],C="",I="",B=null,D=[],T={},q=0,z=ri(),re=0,ke=0,Ve=!1,be=null,He=!1,Fe=0,Se=new Set,xe=new Map,oe="",G="",se=null,ge,pe,j,ae,Ie,ee=null,Z=null,ne=null;function at(){let le=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),we=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");ws(we,N==null?void 0:N.headerBar);let Ne=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ne.textContent="Events",ge=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"),ge.textContent="0",a){Z=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let tr=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");tr.textContent="Throughput",ee=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"),ee.textContent="-- tok/s",ne=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"),ne.style.display="none",ne.style.pointerEvents="none";let Ln=Z,sn=ne,Fn=()=>{if(!sn.textContent)return;let vt=Ln.getBoundingClientRect(),qn=le.getBoundingClientRect();sn.style.left=`${vt.left-qn.left}px`,sn.style.top=`${vt.bottom-qn.top+4}px`,sn.style.display="block"},Cr=()=>{sn.style.display="none"};Z.addEventListener("mouseenter",Fn),Z.addEventListener("mouseleave",Cr),Z.appendChild(tr),Z.appendChild(ee)}let St=b("div","persona-flex-1");pe=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 rn=b("option","");rn.value="",rn.textContent="All events",pe.appendChild(rn),j=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"),j.type="button",j.title="Copy All";let vn=Ae("clipboard-copy","12px","currentColor",1.5);vn&&j.appendChild(vn);let Dt=b("span","persona-text-xs");Dt.textContent="Copy All",j.appendChild(Dt),we.appendChild(Ne),we.appendChild(ge),Z&&we.appendChild(Z),we.appendChild(St),we.appendChild(pe),we.appendChild(j);let nt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ws(nt,N==null?void 0:N.searchBar);let Bt=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),dt=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");Bt&&dt.appendChild(Bt),ae=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"),ws(ae,N==null?void 0:N.searchInput),ae.type="text",ae.placeholder="Search event payloads...",Ie=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"),Ie.type="button",Ie.style.display="none";let Jt=Ae("x","12px","currentColor",2);return Jt&&Ie.appendChild(Jt),nt.appendChild(dt),nt.appendChild(ae),nt.appendChild(Ie),le.appendChild(we),le.appendChild(nt),ne&&le.appendChild(ne),le}let it,ot=s.find(le=>le.renderEventStreamToolbar);if(ot!=null&&ot.renderEventStreamToolbar&&o){let le=ot.renderEventStreamToolbar({config:o,defaultRenderer:()=>at(),eventCount:e.getSize(),filteredCount:0,onFilterChange:we=>{C=we,Wt(),$()},onSearchChange:we=>{I=we,Wt(),$()}});it=le!=null?le: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 fe(){if(!a||!ee||!Z)return;let le=a();ee.textContent=zb(le);let we=Vb(le);ne&&(ne.textContent=we,we||(ne.style.display="none")),we?Z.setAttribute("aria-label",we):Z.removeAttribute("aria-label")}let Xe=b("div","persona-flex-1 persona-min-h-0 persona-relative"),J=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ue=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");ws(ue,N==null?void 0:N.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",g?"true":"false");let Ee=Ae(c,"14px","currentColor",2);Ee&&ue.appendChild(Ee);let Je=b("span","");Je.textContent=g,ue.appendChild(Je);let Ke=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ke.style.display="none",Xe.appendChild(J),Xe.appendChild(Ke),Xe.appendChild(ue),P.setAttribute("tabindex","0"),P.appendChild(it),P.appendChild(Me),P.appendChild(Xe);function Pe(){let le=e.getAll(),we={};for(let Dt of le)we[Dt.type]=(we[Dt.type]||0)+1;let Ne=Object.keys(we).sort(),St=Ne.length!==D.length||!Ne.every((Dt,nt)=>Dt===D[nt]),rn=!St&&Ne.some(Dt=>we[Dt]!==T[Dt]),on=le.length!==Object.values(T).reduce((Dt,nt)=>Dt+nt,0);if(!St&&!rn&&!on||(D=Ne,T=we,!pe))return;let vn=pe.value;if(pe.options[0].textContent="All events",St){for(;pe.options.length>1;)pe.remove(1);for(let Dt of Ne){let nt=b("option","");nt.value=Dt,nt.textContent=`${Dt} (${we[Dt]||0})`,pe.appendChild(nt)}vn&&Ne.includes(vn)?pe.value=vn:vn&&(pe.value="",C="")}else for(let Dt=1;Dt<pe.options.length;Dt++){let nt=pe.options[Dt];nt.textContent=`${nt.value} (${we[nt.value]||0})`}}function je(){let le=e.getAll();if(C&&(le=le.filter(we=>we.type===C)),I){let we=I.toLowerCase();le=le.filter(Ne=>Ne.type.toLowerCase().includes(we)||Ne.payload.toLowerCase().includes(we))}return le}function bn(){return C!==""||I!==""}function Wt(){q=0,re=0,z.resume(),ue.style.display="none"}function dn(le){Se.has(le)?Se.delete(le):Se.add(le),se=le;let we=J.scrollTop,Ne=z.isFollowing();He=!0,z.pause(),$(),J.scrollTop=we,Ne&&z.resume(),He=!1}function wr(){return $o(J,50)}function $(){ke=Date.now(),Ve=!1,fe(),Pe();let le=e.getEvictedCount();le>0?(Me.textContent=`${le.toLocaleString()} older events truncated`,Me.style.display=""):Me.style.display="none",W=je();let we=W.length,Ne=e.getSize()>0;ge&&(ge.textContent=String(e.getSize())),we===0&&Ne&&bn()?(Ke.textContent=I?`No events matching '${I}'`:"No events matching filter",Ke.style.display="",J.style.display="none"):(Ke.style.display="none",J.style.display=""),j&&(j.title=bn()?`Copy Filtered (${we})`:"Copy All"),d&&!z.isFollowing()&&we>q&&(re+=we-q,Je.textContent=g?`${g}${re>0?` (${re})`:""}`:"",ue.style.display=""),q=we;let St=e.getAll(),rn=St.length>0?St[0].timestamp:0,on=new Set(W.map(nt=>nt.id));for(let nt of Se)on.has(nt)||Se.delete(nt);let vn=C!==oe||I!==G,Dt=xe.size===0&&W.length>0;if(vn||Dt||W.length===0){J.innerHTML="",xe.clear();let nt=document.createDocumentFragment();for(let Bt=0;Bt<W.length;Bt++){let dt=pl(W[Bt],Bt,rn,f,Se,dn,s,o);xe.set(W[Bt].id,dt),nt.appendChild(dt)}J.appendChild(nt),oe=C,G=I,se=null}else{if(se!==null){let Bt=xe.get(se);if(Bt&&Bt.parentNode===J){let dt=W.findIndex(Jt=>Jt.id===se);if(dt>=0){let Jt=pl(W[dt],dt,rn,f,Se,dn,s,o);J.insertBefore(Jt,Bt),Bt.remove(),xe.set(se,Jt)}}se=null}let nt=new Set(W.map(Bt=>Bt.id));for(let[Bt,dt]of xe)nt.has(Bt)||(dt.remove(),xe.delete(Bt));for(let Bt=0;Bt<W.length;Bt++){let dt=W[Bt];if(!xe.has(dt.id)){let Jt=pl(dt,Bt,rn,f,Se,dn,s,o);xe.set(dt.id,Jt),J.appendChild(Jt)}}}z.isFollowing()&&(J.scrollTop=J.scrollHeight)}function K(){if(Date.now()-ke>=Nb){be!==null&&(cancelAnimationFrame(be),be=null),$();return}Ve||(Ve=!0,be=requestAnimationFrame(()=>{be=null,$()}))}let he=(le,we)=>{if(!j)return;j.innerHTML="";let Ne=Ae(le,"12px","currentColor",1.5);Ne&&j.appendChild(Ne);let St=b("span","persona-text-xs");St.textContent="Copy All",j.appendChild(St),setTimeout(()=>{j.innerHTML="";let rn=Ae("clipboard-copy","12px","currentColor",1.5);rn&&j.appendChild(rn);let on=b("span","persona-text-xs");on.textContent="Copy All",j.appendChild(on),j.disabled=!1},we)},Ge=async()=>{if(j){j.disabled=!0;try{let le;bn()?le=W:t?(le=await t(),le.length===0&&(le=e.getAll())):le=e.getAll();let we=le.map(Ne=>{try{return JSON.parse(Ne.payload)}catch{return Ne.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),he("check",1500)}catch{he("x",1500)}}},Ze=()=>{pe&&(C=pe.value,Wt(),$())},$e=()=>{!ae||!Ie||(Ie.style.display=ae.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{I=ae.value,Wt(),$()},150))},Oe=()=>{!ae||!Ie||(ae.value="",I="",Ie.style.display="none",B&&clearTimeout(B),Wt(),$())},Lt=()=>{if(He)return;let le=J.scrollTop,{action:we,nextLastScrollTop:Ne}=oi({following:z.isFollowing(),currentScrollTop:le,lastScrollTop:Fe,nearBottom:wr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Fe=Ne,we==="resume"?(z.resume(),re=0,ue.style.display="none"):we==="pause"&&(z.pause(),d&&(Je.textContent=g,ue.style.display=""))},jt=le=>{let we=si({following:z.isFollowing(),deltaY:le.deltaY,nearBottom:wr(),resumeWhenNearBottom:!0});we==="pause"?(z.pause(),d&&(Je.textContent=g,ue.style.display="")):we==="resume"&&(z.resume(),re=0,ue.style.display="none")},Xt=()=>{d&&(J.scrollTop=J.scrollHeight,z.resume(),re=0,ue.style.display="none")},kn=le=>{let we=le.target;if(!we||we.closest("button"))return;let Ne=we.closest("[data-event-id]");if(!Ne)return;let St=Ne.getAttribute("data-event-id");St&&dn(St)},V=le=>{if((le.metaKey||le.ctrlKey)&&le.key==="f"){le.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}le.key==="Escape"&&(ae&&document.activeElement===ae?(Oe(),ae.blur(),P.focus()):r&&r())};j&&j.addEventListener("click",Ge),pe&&pe.addEventListener("change",Ze),ae&&ae.addEventListener("input",$e),Ie&&Ie.addEventListener("click",Oe),J.addEventListener("scroll",Lt),J.addEventListener("wheel",jt,{passive:!0}),J.addEventListener("click",kn),ue.addEventListener("click",Xt),P.addEventListener("keydown",V);function Rt(){B&&clearTimeout(B),be!==null&&(cancelAnimationFrame(be),be=null),Ve=!1,xe.clear(),j&&j.removeEventListener("click",Ge),pe&&pe.removeEventListener("change",Ze),ae&&ae.removeEventListener("input",$e),Ie&&Ie.removeEventListener("click",Oe),J.removeEventListener("scroll",Lt),J.removeEventListener("wheel",jt),J.removeEventListener("click",kn),ue.removeEventListener("click",Xt),P.removeEventListener("keydown",V)}return{element:P,update:K,destroy:Rt}}}function vm(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 g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.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 u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(g,f),i.append(d,c),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${t}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",r),i.append(u)}return i}var xm=(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",g=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>vm(n,e)});if(g)return g}return vm(n,e)};var ul=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)})}},zo=new ul;zo.register("PersonaArtifactCard",xm);function Kb(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 wm(n,e){var pe,j,ae,Ie;let t=(j=(pe=n.features)==null?void 0:pe.artifacts)==null?void 0:j.layout,o=((ae=t==null?void 0:t.toolbarPreset)!=null?ae:"default")==="document",s=(Ie=t==null?void 0:t.panePadding)==null?void 0:Ie.trim(),a=n.markdown?Ha(n.markdown):null,i=Ba(n.sanitize),d=ee=>{let Z=a?a(ee):fo(ee);return i?i(Z):Z},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,g=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),q==null||q.hide()};c&&c.addEventListener("click",()=>{var ee;g(),(ee=e.onDismiss)==null||ee.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 u=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");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.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 ee;g(),(ee=e.onDismiss)==null||ee.call(e)});let x="rendered",M=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=o?En({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):En({icon:"eye",label:"Rendered view"}),k=o?En({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):En({icon:"code-2",label:"Source"}),N=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),P=(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),B=null,D,T=null,q=null;if(o&&(P||W)&&!I){if(D=P?nl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):En({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let ee=Ae("chevron-down",14,"currentColor",2);ee&&D.appendChild(ee)}}else o&&I?(B=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=P?nl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):En({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),T=En({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"}}),B.append(D,T)):o?D=En({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=En({icon:"copy",label:"Copy"});let z=o?En({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):En({icon:"refresh-cw",label:"Refresh"}),re=o?En({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):En({icon:"x",label:"Close"}),ke=()=>{var it,ot,Me;let ee=(it=xe.find(fe=>fe.id===oe))!=null?it:xe[xe.length-1],Z=(ot=ee==null?void 0:ee.id)!=null?ot:null,ne=(ee==null?void 0:ee.artifactType)==="markdown"&&(Me=ee.markdown)!=null?Me:"",at=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:ne,jsonPayload:at,id:Z}},Ve=async()=>{var it;let{markdown:ee,jsonPayload:Z}=ke(),ne=(it=xe.find(ot=>ot.id===oe))!=null?it:xe[xe.length-1],at=(ne==null?void 0:ne.artifactType)==="markdown"?ee:ne?Z:"";try{await navigator.clipboard.writeText(at)}catch{}};if(D.addEventListener("click",async()=>{let ee=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(ee&&I){let{markdown:Z,jsonPayload:ne,id:at}=ke();try{await ee({actionId:"primary",artifactId:at,markdown:Z,jsonPayload:ne})}catch{}return}await Ve()}),T&&(C!=null&&C.length)){let ee=()=>{var ne;return(ne=f.closest("[data-persona-root]"))!=null?ne:document.body},Z=()=>{q=bs({items:C.map(ne=>({id:ne.id,label:ne.label})),onSelect:async ne=>{let{markdown:at,jsonPayload:it,id:ot}=ke(),Me=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Me?await Me({actionId:ne,artifactId:ot,markdown:at,jsonPayload:it}):ne==="markdown"||ne==="md"?await navigator.clipboard.writeText(at):ne==="json"||ne==="source"?await navigator.clipboard.writeText(it):await navigator.clipboard.writeText(at||it)}catch{}},anchor:B!=null?B:T,position:"bottom-right",portal:ee()})};f.isConnected?Z():requestAnimationFrame(Z),T.addEventListener("click",ne=>{ne.stopPropagation(),q==null||q.toggle()})}z.addEventListener("click",async()=>{var ee;try{await((ee=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:ee.call(t))}catch{}se()}),re.addEventListener("click",()=>{var ee;g(),(ee=e.onDismiss)==null||ee.call(e)});let be=()=>{o&&(E.setAttribute("aria-pressed",x==="rendered"?"true":"false"),k.setAttribute("aria-pressed",x==="source"?"true":"false"))};E.addEventListener("click",()=>{x="rendered",be(),se()}),k.addEventListener("click",()=>{x="source",be(),se()});let He=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?(u.replaceChildren(),M.append(E,k),B?N.append(B,z,re):N.append(D,z,re),u.append(M,He,N),be()):(u.appendChild(m),u.appendChild(v)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let Fe=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"),Se=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Fe.style.paddingLeft=s,Fe.style.paddingRight=s,Se.style.padding=s),f.appendChild(u),f.appendChild(Fe),f.appendChild(Se);let xe=[],oe=null,G=!1,se=()=>{var at,it,ot,Me;let ee=o&&xe.length<=1;Fe.classList.toggle("persona-hidden",ee),Fe.replaceChildren();for(let fe of xe){let Xe=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");Xe.type="button",Xe.textContent=fe.title||fe.id.slice(0,8),fe.id===oe&&Xe.classList.add("persona-bg-persona-container","persona-border-persona-border"),Xe.addEventListener("click",()=>e.onSelect(fe.id)),Fe.appendChild(Xe)}Se.replaceChildren();let Z=oe&&xe.find(fe=>fe.id===oe)||xe[xe.length-1];if(!Z)return;if(o){let fe=Z.artifactType==="markdown"?"MD":(at=Z.component)!=null?at:"Component",J=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";He.textContent=`${J} \xB7 ${fe}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(o&&x==="source"){let Xe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Xe.textContent=(it=Z.markdown)!=null?it:"",Se.appendChild(Xe);return}let fe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");fe.innerHTML=d((ot=Z.markdown)!=null?ot:""),Se.appendChild(fe);return}let ne=Z.component?zo.get(Z.component):void 0;if(ne){let Xe={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let J=ne((Me=Z.props)!=null?Me:{},Xe);if(J){Se.appendChild(J);return}}catch{}}Se.appendChild(Kb(Z))},ge=()=>{var Z;let ee=xe.length>0;if(f.classList.toggle("persona-hidden",!ee),c){let ne=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,it=((Z=ne==null?void 0:ne.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ee&&it&&G?(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(ee){var Z,ne,at;xe=ee.artifacts,oe=(at=(ne=ee.selectedId)!=null?ne:(Z=ee.artifacts[ee.artifacts.length-1])==null?void 0:Z.id)!=null?at:null,xe.length>0&&(G=!0),se(),ge()},setMobileOpen(ee){G=ee,!ee&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):ge()}}}function pr(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 Cm(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"),!pr(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 Gb(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 Ci(n,e){var d,c,g,f,u,m,v,x,M,E;if(!pr(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"),Gb(n),Cm(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",(g=t==null?void 0:t.splitGap)!=null?g:"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",(u=t==null?void 0:t.paneMaxWidth)!=null?u:"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=(m=t==null?void 0:t.paneBackground)==null?void 0:m.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=(M=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Cm(n,e)}var Am=["panel","seamless"];function Ai(n,e){var i,d,c,g,f,u;for(let m of Am)n.classList.remove(`persona-artifact-appearance-${m}`);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"),!pr(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=Am.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.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 m=((u=t.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Sm(n,e){var t,r,o;return!e||!pr(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Qb(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 Xb(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 Jb(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function Yb(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Tm(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 Mm(n,e,t,r,o,s){let a=Qb(o,200),i=Yb(e,t,r,200);i=Math.max(a,i);let d=Xb(s);return d!==null&&(i=Math.min(i,d)),Jb(n,a,i)}var Em={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"}},ml=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,M;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Em[a])!=null?x:Em.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 E=b("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,d.appendChild(E)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var C,I;let k=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${e.id}-${a}-${E.name}`;let N=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");N.textContent=E.label,k.appendChild(N);let P=(C=E.type)!=null?C:"text",W;P==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=P),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}-${E.name}`,W.name=E.name,W.placeholder=(I=E.placeholder)!=null?I:"",E.required&&(W.required=!0),k.appendChild(W),g.appendChild(k)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=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");m.type="submit",m.textContent=(M=i.submitLabel)!=null?M:"Submit",f.appendChild(u),f.appendChild(m),g.appendChild(f),s.replaceChildren(d,g),g.addEventListener("submit",async E=>{var W,C;E.preventDefault();let k=(W=t.formEndpoint)!=null?W:"/form",N=new FormData(g),P={};N.forEach((I,B)=>{P[B]=I}),P.type=a,m.disabled=!0,u.textContent="Submitting\u2026";try{let I=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(P)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let B=await I.json();u.textContent=(C=B.message)!=null?C:"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await r.sendMessage(String(B.nextPrompt))}catch(I){u.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var gl=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()}},fl=new gl;var km=()=>{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 Zb=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},ev=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},yl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Zb(n),t=ev(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}},hl=n=>typeof n=="string"?n:n==null?"":String(n),fa={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:hl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=hl(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:hl(t.text)}}},Lm=n=>Array.isArray(n)?n.map(e=>String(e)):[],bl=n=>{let e=new Set(Lm(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Lm(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,g)=>c||(g==null?void 0:g({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 g=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:t}};var tv=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}},nv=n=>n.map(e=>({...e,streaming:!1})),rv=n=>n.map(e=>({...e,status:"complete"})),Pm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?tv(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?nv(t.messages):void 0,artifacts:t.artifacts?rv(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 lA,STR as cA,OBJ as dA}from"partial-json";function Im(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=zo.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 Wm(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 Rm(n){let e=Wm(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 Hm(n){let e=Wm(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 ov=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Bm(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=ov}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),u.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 E=[];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=`
25
+ `,e.addEventListener("click",t);let r=s=>{var R,L,W,C,k,D,N,M,U,z,ne,Le,je;let a=(R=s.launcher)!=null?R:{},i=Cn(s),d=e.querySelector("[data-role='launcher-title']");if(d){let ye=(L=a.title)!=null?L:"Chat Assistant";d.textContent=ye,d.setAttribute("title",ye)}let c=e.querySelector("[data-role='launcher-subtitle']");if(c){let ye=(W=a.subtitle)!=null?W:"Here to help you get answers fast";c.textContent=ye,c.setAttribute("title",ye)}let g=e.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let f=e.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let ye=(C=a.agentIconSize)!=null?C:"40px";if(f.style.height=ye,f.style.width=ye,f.innerHTML="",a.agentIconName){let De=parseFloat(ye)||24,$e=Ae(a.agentIconName,De*.6,"var(--persona-text-inverse, #ffffff)",2);$e?(f.appendChild($e),f.style.display=""):(f.textContent=(k=a.agentIconText)!=null?k:"\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 u=e.querySelector("[data-role='launcher-image']");if(u){let ye=(N=a.agentIconSize)!=null?N:"40px";u.style.height=ye,u.style.width=ye,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let m=e.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(M=a.callToActionIconSize)!=null?M:"32px";m.style.height=ye,m.style.width=ye,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 De=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,De=(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 $e=parseFloat(ye)||24,Se=Math.max($e-De,8),xe=Ae(a.callToActionIconName,Se,"currentColor",2);xe?m.appendChild(xe):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let v=a.position&&vr[a.position]?vr[a.position]:vr["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",T="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";e.className=i?T:`${x} ${v}`,i||(e.style.zIndex=String((ne=a.zIndex)!=null?ne:Ln));let E="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";e.style.border=(Le=a.border)!=null?Le:E,e.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:A,i?(e.style.width="0",e.style.minWidth="0",e.style.maxWidth="0",e.style.padding="0",e.style.overflow="hidden",e.style.border="none",e.style.boxShadow="none"):(e.style.width="",e.style.minWidth="",e.style.maxWidth=(je=a.collapsedMaxWidth)!=null?je:"",e.style.justifyContent="",e.style.padding="",e.style.overflow="")},o=()=>{e.removeEventListener("click",t),e.remove()};return n&&r(n),{element:e,update:r,destroy:o}};var dm=({config:n,showClose:t})=>{let{wrapper:e,panel:r,pillRoot:o}=lm(n),s=cm(n,t),a={wrapper:e,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:u=>(d.element.replaceWith(u.header),d.element=u.header,d.iconHolder=u.iconHolder,d.headerTitle=u.headerTitle,d.headerSubtitle=u.headerSubtitle,d.closeButton=u.closeButton,d.closeButtonWrapper=u.closeButtonWrapper,d.clearChatButton=u.clearChatButton,d.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{c.footer.replaceWith(u),c.footer=u}}},il=({config:n,plugins:t,onToggle:e})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>al(n,e).element,onToggle:e});if(s)return{instance:null,element:s}}let o=al(n,e);return{instance:o,element:o.element}};var ly=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}},cy=(n,t)=>{if(!n)return null;let e=ly(n);if(e===null)return null;let r=t==null?void 0:t[n],o=r!==void 0?r:e;return o||null},dy=(n,t)=>{let e=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return e.setAttribute("data-stop-reason",n),e.setAttribute("role","note"),e.style.opacity="0.75",e.textContent=t,e},py=n=>{let t=n.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||t.startsWith("data:image/")||!n.includes(":"))},ll=n=>{let t=n.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||t.startsWith("data:")||!n.includes(":"))},cl=320,um=320,uy=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),my=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),gy=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),fy=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),hy=(n,t,e)=>{if(n.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),e==null||e())};return n.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=`${cl}px`,c.style.maxHeight=`${um}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 g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),py(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return e==null||e(),null}},by=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let e=0;return n.forEach(r=>{if(!ll(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=`${cl}px`,t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},yy=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let e=0;return n.forEach(r=>{if(!ll(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=`${cl}px`,o.style.maxHeight=`${um}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},vy=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let e=0;return n.forEach(r=>{if(!ll(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",t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},pa=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let 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="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(t),n.appendChild(e),n.appendChild(r),n.appendChild(o),n},xy=(n,t,e)=>{let r={config:e!=null?e:{},streaming:!0,location:n,defaultRenderer:pa};if(t){let o=t(r);if(o!==null)return o}return pa()},wy=(n,t)=>{let e=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=t==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",e.appendChild(o)}else e.textContent=r,e.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else e.textContent=t==="user"?"U":"A",e.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return e},pm=(n,t,e="div")=>{let r=y(e,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Cy=(n,t="bubble")=>{let e=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):e.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":e.push("persona-text-sm","persona-leading-relaxed"),n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):e.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:e.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):e.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 e},Ay=(n,t,e)=>{var v,x,T,E,A,R,L;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(T=t.showDownvote)!=null?T:!0,a=(E=t.showReadAloud)!=null?E:!1;if(!r&&!o&&!s&&!a){let W=y("div");return W.style.display="none",W.id=`actions-${n.id}`,W.setAttribute("data-actions-for",n.id),W}let i=(A=t.visibility)!=null?A:"hover",d=(R=t.align)!=null?R:"right",c=(L=t.layout)!=null?L:"pill-inside",g={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],u=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${g} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${n.id}`,u.setAttribute("data-actions-for",n.id);let m=(W,C,k)=>{let D=In({icon:W,label:C,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",k),D};return r&&u.appendChild(m("copy","Copy message","copy")),a&&u.appendChild(m("volume-2","Read aloud","read-aloud")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},dl=(n,t,e,r,o,s)=>{var re,Q,oe,ge,de,V,se,Re,Z,Y,te,ot,st,tt,Ee,fe,Ke;let a=e!=null?e:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,g=(Q=d==null?void 0:d.show)!=null?Q:!1,f=(oe=c==null?void 0:c.show)!=null?oe:!1,u=(ge=d==null?void 0:d.position)!=null?ge:"left",m=(de=c==null?void 0:c.position)!=null?de:"below",v=Cy(n.role,i),x=y("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 T=uy(n),E=(se=(V=n.content)==null?void 0:V.trim())!=null?se:"",R=T.length>0&&E===Xa,L=ci((Z=(Re=s==null?void 0:s.widgetConfig)==null?void 0:Re.features)==null?void 0:Z.streamAnimation),W=(ot=(te=(Y=s==null?void 0:s.widgetConfig)==null?void 0:Y.features)==null?void 0:te.streamAnimation)==null?void 0:ot.plugins,C=n.role==="assistant"&&L.type!=="none"?oa(L.type,W):null,k=n.role==="assistant"&&((st=C==null?void 0:C.isAnimating)==null?void 0:st.call(C,n))===!0,D=n.role==="assistant"&&C!==null&&(!!n.streaming||k);D&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),D&&C&&(C.containerClass&&N.classList.add(C.containerClass),N.style.setProperty("--persona-stream-step",`${L.speed}ms`),N.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let M=D?di((tt=n.content)!=null?tt:"",L.buffer,C,n,!!n.streaming):(Ee=n.content)!=null?Ee:"",U=t({text:M,message:n,streaming:!!n.streaming,raw:n.rawContent}),z=U;D&&(C==null?void 0:C.wrap)==="char"?z=sa(U,"char",n.id,{skipTags:C.skipTags}):D&&(C==null?void 0:C.wrap)==="word"&&(z=sa(U,"word",n.id,{skipTags:C.skipTags}));let ne=null;if(R?(ne=document.createElement("div"),ne.innerHTML=z,ne.style.display="none",N.appendChild(ne)):N.innerHTML=z,D&&(C!=null&&C.useCaret)&&!R&&E){let X=pi(),pe=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),ke=pe[pe.length-1];if(ke!=null&&ke.parentNode)ke.parentNode.insertBefore(X,ke.nextSibling);else{let Qe=N.lastElementChild;Qe?Qe.appendChild(X):N.appendChild(X)}}if(f&&m==="inline"&&n.createdAt){let X=pm(n,c,"span");X.classList.add("persona-timestamp-inline");let pe=N.lastElementChild;pe?pe.appendChild(X):N.appendChild(X)}if(T.length>0){let X=hy(T,!R&&!!E,()=>{R&&ne&&(ne.style.display="")});X?x.appendChild(X):R&&ne&&(ne.style.display="")}let Le=my(n);if(Le.length>0){let X=by(Le);X&&x.appendChild(X)}let je=gy(n);if(je.length>0){let X=yy(je);X&&x.appendChild(X)}let ye=fy(n);if(ye.length>0){let X=vy(ye);X&&x.appendChild(X)}if(x.appendChild(N),f&&m==="below"&&n.createdAt){let X=pm(n,c);X.classList.add("persona-mt-1"),x.appendChild(X)}let De=n.role==="assistant"?cy(n.stopReason,(Ke=(fe=s==null?void 0:s.widgetConfig)==null?void 0:fe.copy)==null?void 0:Ke.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let X=!!(M&&M.trim()),pe=L.placeholder==="skeleton",ke=pe&&L.buffer==="line"&&X;if(X)ke&&x.appendChild(aa());else if(pe)x.appendChild(aa());else{let Qe=xy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Qe&&x.appendChild(Qe)}}if(De&&n.stopReason&&!n.streaming&&(E||(N.style.display="none"),x.appendChild(dy(n.stopReason,De))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=Ay(n,r,o);x.appendChild(X)}if(!g||n.role==="system")return x;let Se=y("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),xe=wy(d,n.role);return u==="right"||u==="left"&&n.role==="user"?Se.append(x,xe):Se.append(xe,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Se};var ys=new Set,Sy=(n,t)=>t==null?!1:typeof t=="string"?(n.textContent=t,!0):(n.appendChild(t),!0),Ty=(n,t)=>{var r,o;let e=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return e?e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},mm=(n,t)=>{let e=ys.has(n),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",e?"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=Ae(e?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=e?"Hide":"Show"}o.style.display=e?"":"none",s&&(s.style.display=e?"none":s.textContent||s.childNodes.length?"":"none")},pl=(n,t)=>{var je,ye,De,$e,Se,xe,re,Q,oe,ge,de;let e=n.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-${n.id}`,r.setAttribute("data-message-id",n.id),!e)return r;let o=(ye=(je=t==null?void 0:t.features)==null?void 0:je.reasoningDisplay)!=null?ye:{},s=o.expandable!==!1,a=s&&ys.has(n.id),i=e.status!=="complete",d=Ty(n,(De=o.previewMaxLines)!=null?De: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 g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=($e=t==null?void 0:t.reasoning)!=null?$e:{},v=String((Se=e.startedAt)!=null?Se:Date.now()),x=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=za(e),V},T=(xe=m.renderCollapsedSummary)==null?void 0:xe.call(m,{message:n,reasoning:e,defaultSummary:u,previewText:d,isActive:i,config:t!=null?t:{},elapsed:za(e),createElapsedElement:x});typeof T=="string"&&T.trim()?(f.textContent=T,g.appendChild(f)):T instanceof HTMLElement?g.appendChild(T):(f.textContent=u,g.appendChild(f));let E=y("span","persona-text-xs persona-text-persona-primary");E.textContent=uu(e),g.appendChild(E);let A=(re=o.loadingAnimation)!=null?re:"none",R=m.activeTextTemplate,L=m.completeTextTemplate,W=i?R:L,C=T instanceof HTMLElement,k=(V,se,Re)=>{let Z=Re;for(let Y of se){let te=y("span","persona-tool-char");te.style.setProperty("--char-index",String(Z)),te.textContent=Y===" "?"\xA0":Y,V.appendChild(te),Z++}return Z},D=(V,se)=>{f.textContent="";let Re=ja(V,""),Z=0;for(let Y of Re){let te=Y.styles.length>0?(()=>{let ot=y("span",Y.styles.map(st=>`persona-tool-text-${st}`).join(" "));return f.appendChild(ot),ot})():f;if(Y.isDuration&&i)te.appendChild(x());else{let ot=Y.isDuration?za(e):Y.text;se?Z=k(te,ot,Z):te.appendChild(document.createTextNode(ot))}}};if(!C&&W)if(E.style.display="none",f.style.display="",i&&A!=="none"){let V=(Q=m.loadingAnimationDuration)!=null?Q:2e3;f.setAttribute("data-preserve-animation","true"),A==="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-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),A==="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)),D(W,!0))}else D(W,!1);else if(!C&&i&&A!=="none"){f.style.display="";let V=(oe=m.loadingAnimationDuration)!=null?oe:2e3;if(f.setAttribute("data-preserve-animation","true"),A==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${V}ms`),A==="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 se=f.textContent||u;f.textContent="",k(f,se,0)}e.status==="complete"&&(f.style.display="none")}else C||(e.status==="complete"?f.style.display="none":f.style.display="");let N=null;if(s){N=y("div","persona-flex persona-items-center");let se=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);se?N.appendChild(se):N.textContent=a?"Hide":"Show";let Re=y("div","persona-flex persona-items-center persona-ml-auto");Re.append(N),c.append(g,Re)}else c.append(g);let M=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(M.setAttribute("data-persona-collapsed-preview","reasoning"),M.style.display="none",M.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(de=(ge=t==null?void 0:t.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:de.call(ge,{message:n,reasoning:e,defaultPreview:d,isActive:i,config:t!=null?t:{}});Sy(M,V)||(M.textContent=d),M.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,M),r;let U=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let z=e.chunks.join(""),ne=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=z||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(ne),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),N){N.innerHTML="";let se=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);se?N.appendChild(se):N.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",M.style.display=a?"none":M.textContent||M.childNodes.length?"":"none"})(),r.append(c,M,U),r};var vs=new Set,Ey=(n,t)=>t==null?!1:typeof t=="string"?(n.textContent=t,!0):(n.appendChild(t),!0),My=(n,t)=>{var s;let e=n.toolCall;if(!e)return"";let r=((s=e.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
27
+ `);let o=ps(e.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
28
+ `):""},ky=(n,t)=>{var g,f,u,m,v;let e=n.toolCall,r=(g=t==null?void 0:t.features)==null?void 0:g.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=My(n,(u=r==null?void 0:r.previewMaxLines)!=null?u:3),a=e?mu(e):"";if(!e)return{summary:a,previewText:s,isActive:!1};let i=e.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((v=e.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Vi(e,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Vi(e,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},gm=(n,t,e)=>{var g;let r=vs.has(n),o=(g=e==null?void 0:e.toolCall)!=null?g:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.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||"currentColor",u=Ae(r?"chevron-up":"chevron-down",16,f,2);u?c.appendChild(u):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},ul=(n,t)=>{var z,ne,Le,je,ye,De,$e,Se,xe;let e=n.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},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-${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))",!e)return o;let s=(Le=(ne=t==null?void 0:t.features)==null?void 0:ne.toolCallDisplay)!=null?Le:{},a=s.expandable!==!1,i=a&&vs.has(n.id),{summary:d,previewText:c,isActive:g}=ky(n,t),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 u=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 v=String((je=e.startedAt)!=null?je:Date.now()),x=()=>{let re=y("span","");return re.setAttribute("data-tool-elapsed",v),re.textContent=Gs(e),re},T=(De=r.renderCollapsedSummary)==null?void 0:De.call(r,{message:n,toolCall:e,defaultSummary:d,previewText:c,collapsedMode:(ye=s.collapsedMode)!=null?ye:"tool-call",isActive:g,config:t!=null?t:{},elapsed:Gs(e),createElapsedElement:x});typeof T=="string"&&T.trim()?(m.textContent=T,u.appendChild(m)):T instanceof HTMLElement?u.appendChild(T):(m.textContent=d,u.appendChild(m));let E=($e=s.loadingAnimation)!=null?$e:"none",A=r.activeTextTemplate,R=r.completeTextTemplate,L=g?A:R,W=T instanceof HTMLElement,C=(re,Q,oe)=>{let ge=oe;for(let de of Q){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(ge)),V.textContent=de===" "?"\xA0":de,re.appendChild(V),ge++}return ge},k=(re,Q)=>{var V;m.textContent="";let oe=((V=e.name)==null?void 0:V.trim())||"tool",ge=ja(re,oe),de=0;for(let se of ge){let Re=se.styles.length>0?(()=>{let Z=y("span",se.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return m.appendChild(Z),Z})():m;if(se.isDuration&&g)Re.appendChild(x());else{let Z=se.isDuration?Gs(e):se.text;Q?de=C(Re,Z,de):Re.appendChild(document.createTextNode(Z))}}};if(!W)if(g&&E!=="none"){let re=(Se=r.loadingAnimationDuration)!=null?Se:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),L&&k(L,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),E==="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)),L)k(L,!0);else{let Q=m.textContent||d;m.textContent="",C(m,Q,0)}}else L&&k(L,!1);let D=null;if(a){D=y("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Ae(i?"chevron-up":"chevron-down",16,re,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show";let oe=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");oe.append(D),f.append(u,oe)}else f.append(u);let N=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","tool"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&g&&s.activePreview&&c){let re=(xe=r.renderCollapsedPreview)==null?void 0:xe.call(r,{message:n,toolCall:e,defaultPreview:c,isActive:g,config:t!=null?t:{}});Ey(N,re)||(N.textContent=c),N.style.display=""}if(!i&&g&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,N),o;let M=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=i?"":"none",r.contentBackgroundColor&&(M.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(M.style.color=r.contentTextColor),r.contentPaddingX&&(M.style.paddingLeft=r.contentPaddingX,M.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(M.style.paddingTop=r.contentPaddingY,M.style.paddingBottom=r.contentPaddingY),e.name){let re=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=e.name,M.appendChild(re)}if(e.args!==void 0){let re=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let oe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(oe.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(oe.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(oe.style.color=r.codeBlockTextColor),oe.textContent=ps(e.args),re.append(Q,oe),M.appendChild(re)}if(e.chunks&&e.chunks.length){let re=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let oe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(oe.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(oe.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(oe.style.color=r.codeBlockTextColor),oe.textContent=e.chunks.join(""),re.append(Q,oe),M.appendChild(re)}if(e.status==="complete"&&e.result!==void 0){let re=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let oe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(oe.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(oe.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(oe.style.color=r.codeBlockTextColor),oe.textContent=ps(e.result),re.append(Q,oe),M.appendChild(re)}if(e.status==="complete"&&typeof e.duration=="number"){let re=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${e.duration}ms`,M.appendChild(re)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),D){D.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Ae(i?"chevron-up":"chevron-down",16,re,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show"}M.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),o.append(f,N,M),o};var Ci=new Map,Ly=n=>{let e=(n.startsWith(Ho)?n.slice(Ho.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(e.length===0)return n;let r=e.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},fm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,hm=(n,t)=>{var r,o,s;let e=(o=(r=fm(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ci.get(n))!=null?s:e==="expanded"},bm=(n,t,e)=>{var a,i;let r=fm(e);n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(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=Ae(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},ym=(n,t,e)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=hm(n,e);bm(r,s,e),o.style.display=s?"":"none"};var Ai=(n,t)=>{var k,D,N,M,U,z,ne,Le,je,ye,De,$e,Se,xe,re;let e=n.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(e==null?void 0:e.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-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(k=r==null?void 0:r.backgroundColor)!=null?k:"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))",!e)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=e.status==="denied"?"shield-x":e.status==="timeout"?"shield-alert":"shield-check",c=e.status==="approved"?"var(--persona-feedback-success, #16a34a)":e.status==="denied"?"var(--persona-feedback-error, #dc2626)":e.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(N=r==null?void 0:r.titleColor)!=null?N:"currentColor",g=Ae(d,20,c,2);g&&i.appendChild(g);let f=y("div","persona-flex-1 persona-min-w-0"),u=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=(M=r==null?void 0:r.title)!=null?M:"Approval Required",u.appendChild(m),!o){let Q=y("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",e.status),e.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"):e.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"):e.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"),u.appendChild(Q)}f.appendChild(u);let x=e.toolType==="webmcp"||e.toolName.startsWith(Ho)?Hi(e.toolName):void 0,T=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:e.toolName,toolType:e.toolType,description:e.description,parameters:e.parameters,...x?{displayTitle:x}:{},...e.reason?{reason:e.reason}:{}}),E=!e.toolName,A=T||(E?e.description:`The assistant wants to use \u201C${x!=null?x:Ly(e.toolName)}\u201D.`),R=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(R.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(R.style.color=r.descriptionColor),R.textContent=A,f.appendChild(R),e.reason){let Q=y("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 oe=y("span","persona-font-medium");oe.textContent=`${(z=r==null?void 0:r.reasonLabel)!=null?z:"Agent's stated reason:"} `,Q.appendChild(oe),Q.appendChild(document.createTextNode(e.reason)),f.appendChild(Q)}let L=(ne=r==null?void 0:r.detailsDisplay)!=null?ne:"collapsed",W=!!e.description&&!E,C=W||!!e.parameters;if(L!=="hidden"&&C){let Q=hm(n.id,t),oe=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");oe.type="button",oe.setAttribute("data-expand-header","true"),oe.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(oe.style.color=r.descriptionColor);let ge=y("span");ge.setAttribute("data-approval-details-label","true");let de=y("span","persona-inline-flex persona-items-center");de.setAttribute("data-approval-details-chevron","true"),oe.append(ge,de),bm(oe,Q,t),f.appendChild(oe);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=Q?"":"none",W){let se=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor),se.textContent=e.description,V.appendChild(se)}if(e.parameters){let se=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&&(se.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(se.style.color=r.parameterTextColor),se.style.fontSize="0.75rem",se.style.lineHeight="1rem",se.textContent=ps(e.parameters),V.appendChild(se)}f.appendChild(V)}if(o){let Q=y("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let oe=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");oe.type="button",oe.style.backgroundColor=(Le=r==null?void 0:r.approveButtonColor)!=null?Le:"var(--persona-approval-approve-bg, #22c55e)",oe.style.color=(je=r==null?void 0:r.approveButtonTextColor)!=null?je:"#ffffff",oe.setAttribute("data-approval-action","approve");let ge=Ae("shield-check",14,(ye=r==null?void 0:r.approveButtonTextColor)!=null?ye:"#ffffff",2);ge&&(ge.style.marginRight="4px",oe.appendChild(ge));let de=document.createTextNode((De=r==null?void 0:r.approveLabel)!=null?De:"Approve");oe.appendChild(de);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=($e=r==null?void 0:r.denyButtonColor)!=null?$e:"transparent",V.style.color=(Se=r==null?void 0:r.denyButtonTextColor)!=null?Se:"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 se=Ae("shield-x",14,(xe=r==null?void 0:r.denyButtonTextColor)!=null?xe:"var(--persona-feedback-error, #dc2626)",2);se&&(se.style.marginRight="4px",V.appendChild(se));let Re=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");V.appendChild(Re),Q.append(oe,V),f.appendChild(Q)}return a.append(i,f),s.appendChild(a),s};var vm=n=>{let t=[],e=null;return{buttons:t,render:(o,s,a,i,d,c)=>{n.innerHTML="",t.length=0;let g=(c==null?void 0:c.agentPushed)===!0;if(g||(e=null),!o||!o.length||!g&&(i!=null?i:s?s.getMessages():[]).some(T=>T.role==="user"))return;let f=document.createDocumentFragment(),u=s?s.isStreaming():!1,m=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=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");x.type="button",x.textContent=v,x.disabled=u,d!=null&&d.fontFamily&&(x.style.fontFamily=m(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="",g&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),t.push(x)}),n.appendChild(f),g){let v=JSON.stringify(o);v!==e&&(e=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ua=class{constructor(t=2e3,e=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=e}push(t){var e;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(e=this.store)==null||e.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let e=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of e)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=t.length,e.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let e=this.getAll();return t>=e.length?e:e.slice(e.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ma=class{constructor(t="persona-event-stream",e="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=e}open(){return new Promise((t,e)=>{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,t()},r.onerror=()=>{e(r.error)}}catch(r){e(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,e)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{e(a.error)}}catch(r){e(r)}})}getCount(){return new Promise((t,e)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{e(s.error)}}catch(r){e(r)}})}clear(){return new Promise((t,e)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{e(s.error)}}catch(r){e(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,e)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{e(r.error)}}catch(r){e(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var Iy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Py=new Set(["step_start","execution_start"]),Wy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ry=new Set(["step_complete","agent_turn_complete"]),By=new Set(["flow_complete","agent_complete"]),xm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Cm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),tr=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Uo=(n,t)=>{let e=n[t];return Cm(e)?e:void 0};function ml(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function Si(n,t){if(!(n<=0||t===void 0||t<250))return n/(t/1e3)}function Hy(n,t){return typeof t.type=="string"?t.type:n}function Dy(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 Ny(n,t){return n==="step_delta"||n==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function wm(n){var r,o,s,a,i;let t=Uo(n,"result"),e=[Uo(n,"tokens"),Uo(n,"totalTokens"),t?Uo(t,"tokens"):void 0,Uo(n,"usage"),t?Uo(t,"usage"):void 0];for(let d of e){if(!d)continue;let c=(o=(r=tr(d.output))!=null?r:tr(d.outputTokens))!=null?o:tr(d.completionTokens);if(c!==void 0)return c}return(i=(s=tr(n.outputTokens))!=null?s:tr(n.completionTokens))!=null?i:t?(a=tr(t.outputTokens))!=null?a:tr(t.completionTokens):void 0}function Fy(n){var e,r,o,s,a;let t=Uo(n,"result");return(a=(o=(r=(e=tr(n.executionTime))!=null?e:tr(n.executionTimeMs))!=null?r:tr(n.execution_time))!=null?o:tr(n.duration))!=null?a:t?(s=tr(t.executionTime))!=null?s:tr(t.executionTimeMs):void 0}function _y(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ga=class{constructor(t=_y){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let e=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:e,tokensPerSecond:Si(this.metric.outputTokens,e)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,e){var s;if(!Cm(e)){xm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Hy(t,e),o=this.now();if(Iy.has(r)){this.startRun(o);return}if(Py.has(r)){this.run||this.startRun(o);return}if(Wy.has(r)){if(!Ny(r,e))return;let a=Dy(e);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+ml(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Si(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ry.has(r)){if(!this.run)return;let a=this.run,i=wm(e);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+ml(a.visibleCharCount),g=this.resolveDuration(a,e,o);this.metric={status:"running",tokensPerSecond:Si(c,g),outputTokens:c,durationMs:g,source:d?"usage":"estimate"};return}if(By.has(r)){if(!this.run)return;let a=this.run,i=wm(e),d=i!=null?i:a.exactOutputTokens+ml(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",g=this.resolveDuration(a,e,o);this.metric={status:"complete",tokensPerSecond:Si(d,g),outputTokens:d,durationMs:g,source:c},this.run=null;return}if(xm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,e,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Fy(e);return s!=null?s:r-t.startedAt}};function xs(n,t){t&&t.split(/\s+/).forEach(e=>e&&n.classList.add(e))}var Oy={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)"}},$y={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},qy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Uy=100;function zy(n,t){let e={...Oy,...t};if(e[n])return e[n];for(let r of Object.keys(e))if(r.endsWith("_")&&n.startsWith(r))return e[r];return $y}function jy(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function Vy(n){let t=new Date(n),e=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${e}:${r}:${o}.${s}`}function Ky(n,t){try{let e=JSON.parse(n);if(typeof e!="object"||e===null)return null;for(let r of t){let o=r.split("."),s=e;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 Gy(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(e=>{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),e()})}function Qy(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function Xy(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Jy(n){let t=[];return n.outputTokens!==void 0&&t.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&t.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&t.push(n.source),t.join(" \xB7 ")}function Yy(n,t,e){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&e){let i=s.renderEventStreamPayload({event:n,config:e,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 gl(n,t,e,r,o,s,a,i){var u;let d=o.has(n.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");xs(c,(u=r.classNames)==null?void 0:u.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:n,index:t,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var z,ne;let m=y("div",""),v=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");v.setAttribute("data-event-id",n.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=Ae(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&x.appendChild(T);let E=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(z=r.timestampFormat)!=null?z:"relative";E.textContent=A==="relative"?jy(n.timestamp,e):Vy(n.timestamp);let R=null;r.showSequenceNumbers!==!1&&(R=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(t+1));let L=zy(n.type,r.badgeColors),W=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");W.style.backgroundColor=L.bg,W.style.color=L.text,W.style.borderColor=L.text+"50",W.textContent=n.type;let C=(ne=r.descriptionFields)!=null?ne:qy,k=Ky(n.payload,C),D=null;k&&(D=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),D.textContent=k);let N=y("div","persona-flex-1 persona-min-w-0"),M=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"),U=Ae("clipboard","12px","currentColor",1.5);return U&&M.appendChild(U),M.addEventListener("click",async Le=>{Le.stopPropagation(),await Gy(Qy(n)),M.innerHTML="";let je=Ae("check","12px","currentColor",1.5);je&&M.appendChild(je),setTimeout(()=>{M.innerHTML="";let ye=Ae("clipboard","12px","currentColor",1.5);ye&&M.appendChild(ye)},1500)}),v.appendChild(x),v.appendChild(E),R&&v.appendChild(R),v.appendChild(W),D&&v.appendChild(D),v.appendChild(N),v.appendChild(M),m.appendChild(v),d&&m.appendChild(Yy(n,a,i)),m}}function Am(n){var v,x,T,E,A;let{buffer:t,getFullHistory:e,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",g=(T=i==null?void 0:i.label)!=null?T:"",f=(A=(E=o==null?void 0:o.features)==null?void 0:E.eventStream)!=null?A:{},u=s.find(R=>R.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let R=u.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(R)return{element:R,update:()=>{},destroy:()=>{}}}return m();function m(){let R=f.classNames,L=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");xs(L,R==null?void 0:R.panel);let W=[],C="",k="",D=null,N=[],M={},U=0,z=ai(),ne=0,Le=0,je=!1,ye=null,De=!1,$e=0,Se=new Set,xe=new Map,re="",Q="",oe=null,ge,de,V,se,Re,Z=null,Y=null,te=null;function ot(){let ce=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ue=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");xs(ue,R==null?void 0:R.headerBar);let Te=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Te.textContent="Events",ge=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"),ge.textContent="0",a){Y=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Y.style.cursor="help";let nr=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");nr.textContent="Throughput",Z=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"),Z.textContent="-- tok/s",te=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"),te.style.display="none",te.style.pointerEvents="none";let Pn=Y,an=te,_n=()=>{if(!an.textContent)return;let wt=Pn.getBoundingClientRect(),zn=ce.getBoundingClientRect();an.style.left=`${wt.left-zn.left}px`,an.style.top=`${wt.bottom-zn.top+4}px`,an.style.display="block"},wr=()=>{an.style.display="none"};Y.addEventListener("mouseenter",_n),Y.addEventListener("mouseleave",wr),Y.appendChild(nr),Y.appendChild(Z)}let pt=y("div","persona-flex-1");de=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 Zt=y("option","");Zt.value="",Zt.textContent="All events",de.appendChild(Zt),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 xn=Ae("clipboard-copy","12px","currentColor",1.5);xn&&V.appendChild(xn);let _t=y("span","persona-text-xs");_t.textContent="Copy All",V.appendChild(_t),ue.appendChild(Te),ue.appendChild(ge),Y&&ue.appendChild(Y),ue.appendChild(pt),ue.appendChild(de),ue.appendChild(V);let Ze=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");xs(Ze,R==null?void 0:R.searchBar);let Ft=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),ut=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");Ft&&ut.appendChild(Ft),se=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"),xs(se,R==null?void 0:R.searchInput),se.type="text",se.placeholder="Search event payloads...",Re=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"),Re.type="button",Re.style.display="none";let en=Ae("x","12px","currentColor",2);return en&&Re.appendChild(en),Ze.appendChild(ut),Ze.appendChild(se),Ze.appendChild(Re),ce.appendChild(ue),ce.appendChild(Ze),te&&ce.appendChild(te),ce}let st,tt=s.find(ce=>ce.renderEventStreamToolbar);if(tt!=null&&tt.renderEventStreamToolbar&&o){let ce=tt.renderEventStreamToolbar({config:o,defaultRenderer:()=>ot(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ue=>{C=ue,Dt(),An()},onSearchChange:ue=>{k=ue,Dt(),An()}});st=ce!=null?ce:ot()}else st=ot();let Ee=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");Ee.style.display="none";function fe(){if(!a||!Z||!Y)return;let ce=a();Z.textContent=Xy(ce);let ue=Jy(ce);te&&(te.textContent=ue,ue||(te.style.display="none")),ue?Y.setAttribute("aria-label",ue):Y.removeAttribute("aria-label")}let Ke=y("div","persona-flex-1 persona-min-h-0 persona-relative"),X=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let pe=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");xs(pe,R==null?void 0:R.scrollIndicator),pe.style.display="none",pe.setAttribute("data-persona-scroll-to-bottom-has-label",g?"true":"false");let ke=Ae(c,"14px","currentColor",2);ke&&pe.appendChild(ke);let Qe=y("span","");Qe.textContent=g,pe.appendChild(Qe);let Kt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Kt.style.display="none",Ke.appendChild(X),Ke.appendChild(Kt),Ke.appendChild(pe),L.setAttribute("tabindex","0"),L.appendChild(st),L.appendChild(Ee),L.appendChild(Ke);function Ie(){let ce=t.getAll(),ue={};for(let _t of ce)ue[_t.type]=(ue[_t.type]||0)+1;let Te=Object.keys(ue).sort(),pt=Te.length!==N.length||!Te.every((_t,Ze)=>_t===N[Ze]),Zt=!pt&&Te.some(_t=>ue[_t]!==M[_t]),sn=ce.length!==Object.values(M).reduce((_t,Ze)=>_t+Ze,0);if(!pt&&!Zt&&!sn||(N=Te,M=ue,!de))return;let xn=de.value;if(de.options[0].textContent="All events",pt){for(;de.options.length>1;)de.remove(1);for(let _t of Te){let Ze=y("option","");Ze.value=_t,Ze.textContent=`${_t} (${ue[_t]||0})`,de.appendChild(Ze)}xn&&Te.includes(xn)?de.value=xn:xn&&(de.value="",C="")}else for(let _t=1;_t<de.options.length;_t++){let Ze=de.options[_t];Ze.textContent=`${Ze.value} (${ue[Ze.value]||0})`}}function qe(){let ce=t.getAll();if(C&&(ce=ce.filter(ue=>ue.type===C)),k){let ue=k.toLowerCase();ce=ce.filter(Te=>Te.type.toLowerCase().includes(ue)||Te.payload.toLowerCase().includes(ue))}return ce}function nt(){return C!==""||k!==""}function Dt(){U=0,ne=0,z.resume(),pe.style.display="none"}function bn(ce){Se.has(ce)?Se.delete(ce):Se.add(ce),oe=ce;let ue=X.scrollTop,Te=z.isFollowing();De=!0,z.pause(),An(),X.scrollTop=ue,Te&&z.resume(),De=!1}function xr(){return $o(X,50)}function An(){Le=Date.now(),je=!1,fe(),Ie();let ce=t.getEvictedCount();ce>0?(Ee.textContent=`${ce.toLocaleString()} older events truncated`,Ee.style.display=""):Ee.style.display="none",W=qe();let ue=W.length,Te=t.getSize()>0;ge&&(ge.textContent=String(t.getSize())),ue===0&&Te&&nt()?(Kt.textContent=k?`No events matching '${k}'`:"No events matching filter",Kt.style.display="",X.style.display="none"):(Kt.style.display="none",X.style.display=""),V&&(V.title=nt()?`Copy Filtered (${ue})`:"Copy All"),d&&!z.isFollowing()&&ue>U&&(ne+=ue-U,Qe.textContent=g?`${g}${ne>0?` (${ne})`:""}`:"",pe.style.display=""),U=ue;let pt=t.getAll(),Zt=pt.length>0?pt[0].timestamp:0,sn=new Set(W.map(Ze=>Ze.id));for(let Ze of Se)sn.has(Ze)||Se.delete(Ze);let xn=C!==re||k!==Q,_t=xe.size===0&&W.length>0;if(xn||_t||W.length===0){X.innerHTML="",xe.clear();let Ze=document.createDocumentFragment();for(let Ft=0;Ft<W.length;Ft++){let ut=gl(W[Ft],Ft,Zt,f,Se,bn,s,o);xe.set(W[Ft].id,ut),Ze.appendChild(ut)}X.appendChild(Ze),re=C,Q=k,oe=null}else{if(oe!==null){let Ft=xe.get(oe);if(Ft&&Ft.parentNode===X){let ut=W.findIndex(en=>en.id===oe);if(ut>=0){let en=gl(W[ut],ut,Zt,f,Se,bn,s,o);X.insertBefore(en,Ft),Ft.remove(),xe.set(oe,en)}}oe=null}let Ze=new Set(W.map(Ft=>Ft.id));for(let[Ft,ut]of xe)Ze.has(Ft)||(ut.remove(),xe.delete(Ft));for(let Ft=0;Ft<W.length;Ft++){let ut=W[Ft];if(!xe.has(ut.id)){let en=gl(ut,Ft,Zt,f,Se,bn,s,o);xe.set(ut.id,en),X.appendChild(en)}}}z.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Ve(){if(Date.now()-Le>=Uy){ye!==null&&(cancelAnimationFrame(ye),ye=null),An();return}je||(je=!0,ye=requestAnimationFrame(()=>{ye=null,An()}))}let Nt=(ce,ue)=>{if(!V)return;V.innerHTML="";let Te=Ae(ce,"12px","currentColor",1.5);Te&&V.appendChild(Te);let pt=y("span","persona-text-xs");pt.textContent="Copy All",V.appendChild(pt),setTimeout(()=>{V.innerHTML="";let Zt=Ae("clipboard-copy","12px","currentColor",1.5);Zt&&V.appendChild(Zt);let sn=y("span","persona-text-xs");sn.textContent="Copy All",V.appendChild(sn),V.disabled=!1},ue)},$=async()=>{if(V){V.disabled=!0;try{let ce;nt()?ce=W:e?(ce=await e(),ce.length===0&&(ce=t.getAll())):ce=t.getAll();let ue=ce.map(Te=>{try{return JSON.parse(Te.payload)}catch{return Te.payload}});await navigator.clipboard.writeText(JSON.stringify(ue,null,2)),Nt("check",1500)}catch{Nt("x",1500)}}},Me=()=>{de&&(C=de.value,Dt(),An())},we=()=>{!se||!Re||(Re.style.display=se.value?"":"none",D&&clearTimeout(D),D=setTimeout(()=>{k=se.value,Dt(),An()},150))},Fe=()=>{!se||!Re||(se.value="",k="",Re.style.display="none",D&&clearTimeout(D),Dt(),An())},at=()=>{if(De)return;let ce=X.scrollTop,{action:ue,nextLastScrollTop:Te}=ii({following:z.isFollowing(),currentScrollTop:ce,lastScrollTop:$e,nearBottom:xr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});$e=Te,ue==="resume"?(z.resume(),ne=0,pe.style.display="none"):ue==="pause"&&(z.pause(),d&&(Qe.textContent=g,pe.style.display=""))},dt=ce=>{let ue=li({following:z.isFollowing(),deltaY:ce.deltaY,nearBottom:xr(),resumeWhenNearBottom:!0});ue==="pause"?(z.pause(),d&&(Qe.textContent=g,pe.style.display="")):ue==="resume"&&(z.resume(),ne=0,pe.style.display="none")},rt=()=>{d&&(X.scrollTop=X.scrollHeight,z.resume(),ne=0,pe.style.display="none")},Et=ce=>{let ue=ce.target;if(!ue||ue.closest("button"))return;let Te=ue.closest("[data-event-id]");if(!Te)return;let pt=Te.getAttribute("data-event-id");pt&&bn(pt)},j=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),se==null||se.focus(),se==null||se.select();return}ce.key==="Escape"&&(se&&document.activeElement===se?(Fe(),se.blur(),L.focus()):r&&r())};V&&V.addEventListener("click",$),de&&de.addEventListener("change",Me),se&&se.addEventListener("input",we),Re&&Re.addEventListener("click",Fe),X.addEventListener("scroll",at),X.addEventListener("wheel",dt,{passive:!0}),X.addEventListener("click",Et),pe.addEventListener("click",rt),L.addEventListener("keydown",j);function At(){D&&clearTimeout(D),ye!==null&&(cancelAnimationFrame(ye),ye=null),je=!1,xe.clear(),V&&V.removeEventListener("click",$),de&&de.removeEventListener("change",Me),se&&se.removeEventListener("input",we),Re&&Re.removeEventListener("click",Fe),X.removeEventListener("scroll",at),X.removeEventListener("wheel",dt),X.removeEventListener("click",Et),pe.removeEventListener("click",rt),L.removeEventListener("keydown",j)}return{element:L,update:Ve,destroy:At}}}function Sm(n,t){let e=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 ${e} 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 g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=e;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 u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(g,f),i.append(d,c),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${e}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",r),i.append(u)}return i}var Tm=(n,t)=>{var r,o,s;let e=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(e){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",g=e({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Sm(n,t)});if(g)return g}return Sm(n,t)};var fl=class{constructor(){this.components=new Map}register(t,e){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,e)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([e,r])=>{this.register(e,r)})}},zo=new fl;zo.register("PersonaArtifactCard",Tm);function Zy(n){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),e=y("div","persona-font-semibold persona-text-sm persona-mb-2");e.textContent=n.component?`Component: ${n.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=n.props)!=null?o:{},null,2),t.appendChild(e),t.appendChild(r),t}function Em(n,t){var de,V,se,Re;let e=(V=(de=n.features)==null?void 0:de.artifacts)==null?void 0:V.layout,o=((se=e==null?void 0:e.toolbarPreset)!=null?se:"default")==="document",s=(Re=e==null?void 0:e.panePadding)==null?void 0:Re.trim(),a=n.markdown?Da(n.markdown):null,i=Na(n.sanitize),d=Z=>{let Y=a?a(Z):fo(Z);return i?i(Y):Y},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,g=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};c&&c.addEventListener("click",()=>{var Z;g(),(Z=t.onDismiss)==null||Z.call(t)});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 u=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");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let m=y("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=y("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 Z;g(),(Z=t.onDismiss)==null||Z.call(t)});let x="rendered",T=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=o?In({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):In({icon:"eye",label:"Rendered view"}),A=o?In({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):In({icon:"code-2",label:"Source"}),R=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),L=(e==null?void 0:e.documentToolbarShowCopyLabel)===!0,W=(e==null?void 0:e.documentToolbarShowCopyChevron)===!0,C=e==null?void 0:e.documentToolbarCopyMenuItems,k=!!(W&&C&&C.length>0),D=null,N,M=null,U=null;if(o&&(L||W)&&!k){if(N=L?sl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):In({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let Z=Ae("chevron-down",14,"currentColor",2);Z&&N.appendChild(Z)}}else o&&k?(D=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),N=L?sl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):In({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),M=In({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(N,M)):o?N=In({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):N=In({icon:"copy",label:"Copy"});let z=o?In({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):In({icon:"refresh-cw",label:"Refresh"}),ne=o?In({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):In({icon:"x",label:"Close"}),Le=()=>{var st,tt,Ee;let Z=(st=xe.find(fe=>fe.id===re))!=null?st:xe[xe.length-1],Y=(tt=Z==null?void 0:Z.id)!=null?tt:null,te=(Z==null?void 0:Z.artifactType)==="markdown"&&(Ee=Z.markdown)!=null?Ee:"",ot=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"";return{markdown:te,jsonPayload:ot,id:Y}},je=async()=>{var st;let{markdown:Z,jsonPayload:Y}=Le(),te=(st=xe.find(tt=>tt.id===re))!=null?st:xe[xe.length-1],ot=(te==null?void 0:te.artifactType)==="markdown"?Z:te?Y:"";try{await navigator.clipboard.writeText(ot)}catch{}};if(N.addEventListener("click",async()=>{let Z=e==null?void 0:e.onDocumentToolbarCopyMenuSelect;if(Z&&k){let{markdown:Y,jsonPayload:te,id:ot}=Le();try{await Z({actionId:"primary",artifactId:ot,markdown:Y,jsonPayload:te})}catch{}return}await je()}),M&&(C!=null&&C.length)){let Z=()=>{var te;return(te=f.closest("[data-persona-root]"))!=null?te:document.body},Y=()=>{U=bs({items:C.map(te=>({id:te.id,label:te.label})),onSelect:async te=>{let{markdown:ot,jsonPayload:st,id:tt}=Le(),Ee=e==null?void 0:e.onDocumentToolbarCopyMenuSelect;try{Ee?await Ee({actionId:te,artifactId:tt,markdown:ot,jsonPayload:st}):te==="markdown"||te==="md"?await navigator.clipboard.writeText(ot):te==="json"||te==="source"?await navigator.clipboard.writeText(st):await navigator.clipboard.writeText(ot||st)}catch{}},anchor:D!=null?D:M,position:"bottom-right",portal:Z()})};f.isConnected?Y():requestAnimationFrame(Y),M.addEventListener("click",te=>{te.stopPropagation(),U==null||U.toggle()})}z.addEventListener("click",async()=>{var Z;try{await((Z=e==null?void 0:e.onDocumentToolbarRefresh)==null?void 0:Z.call(e))}catch{}oe()}),ne.addEventListener("click",()=>{var Z;g(),(Z=t.onDismiss)==null||Z.call(t)});let ye=()=>{o&&(E.setAttribute("aria-pressed",x==="rendered"?"true":"false"),A.setAttribute("aria-pressed",x==="source"?"true":"false"))};E.addEventListener("click",()=>{x="rendered",ye(),oe()}),A.addEventListener("click",()=>{x="source",ye(),oe()});let De=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?(u.replaceChildren(),T.append(E,A),D?R.append(D,z,ne):R.append(N,z,ne),u.append(T,De,R),ye()):(u.appendChild(m),u.appendChild(v)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let $e=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"),Se=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&($e.style.paddingLeft=s,$e.style.paddingRight=s,Se.style.padding=s),f.appendChild(u),f.appendChild($e),f.appendChild(Se);let xe=[],re=null,Q=!1,oe=()=>{var ot,st,tt,Ee;let Z=o&&xe.length<=1;$e.classList.toggle("persona-hidden",Z),$e.replaceChildren();for(let fe of xe){let Ke=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");Ke.type="button",Ke.textContent=fe.title||fe.id.slice(0,8),fe.id===re&&Ke.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ke.addEventListener("click",()=>t.onSelect(fe.id)),$e.appendChild(Ke)}Se.replaceChildren();let Y=re&&xe.find(fe=>fe.id===re)||xe[xe.length-1];if(!Y)return;if(o){let fe=Y.artifactType==="markdown"?"MD":(ot=Y.component)!=null?ot:"Component",X=(Y.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";De.textContent=`${X} \xB7 ${fe}`}else m.textContent="Artifacts";if(Y.artifactType==="markdown"){if(o&&x==="source"){let Ke=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ke.textContent=(st=Y.markdown)!=null?st:"",Se.appendChild(Ke);return}let fe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");fe.innerHTML=d((tt=Y.markdown)!=null?tt:""),Se.appendChild(fe);return}let te=Y.component?zo.get(Y.component):void 0;if(te){let Ke={message:{id:Y.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let X=te((Ee=Y.props)!=null?Ee:{},Ke);if(X){Se.appendChild(X);return}}catch{}}Se.appendChild(Zy(Y))},ge=()=>{var Y;let Z=xe.length>0;if(f.classList.toggle("persona-hidden",!Z),c){let te=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,st=((Y=te==null?void 0:te.classList.contains("persona-artifact-narrow-host"))!=null?Y:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Z&&st&&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(Z){var Y,te,ot;xe=Z.artifacts,re=(ot=(te=Z.selectedId)!=null?te:(Y=Z.artifacts[Z.artifacts.length-1])==null?void 0:Y.id)!=null?ot:null,xe.length>0&&(Q=!0),oe(),ge()},setMobileOpen(Z){Q=Z,!Z&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):ge()}}}function dr(n){var t,e;return((e=(t=n==null?void 0:n.features)==null?void 0:t.artifacts)==null?void 0:e.enabled)===!0}function Mm(n,t){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"),!dr(t))return;let e=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=e==null?void 0:e.paneBorder)==null?void 0:i.trim(),o=(d=e==null?void 0:e.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 ev(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 Ti(n,t){var d,c,g,f,u,m,v,x,T,E;if(!dr(t)){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"),ev(n),Mm(n,t);return}let e=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(g=e==null?void 0:e.splitGap)!=null?g:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=e==null?void 0:e.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(u=e==null?void 0:e.paneMaxWidth)!=null?u:"28rem"),e!=null&&e.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",e.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=e==null?void 0:e.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=e==null?void 0:e.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=e==null?void 0:e.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=(T=e==null?void 0:e.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=e==null?void 0:e.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Mm(n,t)}var km=["panel","seamless"];function Ei(n,t){var i,d,c,g,f,u;for(let m of km)n.classList.remove(`persona-artifact-appearance-${m}`);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"),!dr(t))return;let e=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=e==null?void 0:e.paneAppearance)!=null?c:"panel",o=km.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(g=e==null?void 0:e.paneBorderRadius)==null?void 0:g.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=e==null?void 0:e.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(e==null?void 0:e.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((u=e.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Lm(n,t){var e,r,o;return!t||!dr(n)?!1:((o=(r=(e=n.features)==null?void 0:e.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function tv(n,t){if(!(n!=null&&n.trim()))return t;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):t}function nv(n){if(!(n!=null&&n.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):null}function rv(n,t,e){return e<t?t:Math.min(e,Math.max(t,n))}function ov(n,t,e,r){let o=n-r-2*t-e;return Math.max(0,o)}function Im(n,t){var a;let r=(a=(t.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 Pm(n,t,e,r,o,s){let a=tv(o,200),i=ov(t,e,r,200);i=Math.max(a,i);let d=nv(s);return d!==null&&(i=Math.min(i,d)),rv(n,a,i)}var Wm={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"}},hl=(n,t,e,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,T;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Wm[a])!=null?x:Wm.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 E=y("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,d.appendChild(E)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var C,k;let A=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${a}-${E.name}`;let R=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=E.label,A.appendChild(R);let L=(C=E.type)!=null?C:"text",W;L==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=L),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=`${t.id}-${a}-${E.name}`,W.name=E.name,W.placeholder=(k=E.placeholder)!=null?k:"",E.required&&(W.required=!0),A.appendChild(W),g.appendChild(A)});let f=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=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=(T=i.submitLabel)!=null?T:"Submit",f.appendChild(u),f.appendChild(m),g.appendChild(f),s.replaceChildren(d,g),g.addEventListener("submit",async E=>{var W,C;E.preventDefault();let A=(W=e.formEndpoint)!=null?W:"/form",R=new FormData(g),L={};R.forEach((k,D)=>{L[D]=k}),L.type=a,m.disabled=!0,u.textContent="Submitting\u2026";try{let k=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let D=await k.json();u.textContent=(C=D.message)!=null?C:"Thanks! We'll be in touch soon.",D.success&&D.nextPrompt&&await r.sendMessage(String(D.nextPrompt))}catch(k){u.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var bl=class{constructor(){this.plugins=new Map}register(t){var e;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(e=t.onRegister)==null||e.call(t)}unregister(t){var r;let e=this.plugins.get(t);e&&((r=e.onUnregister)==null||r.call(e),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,e)=>{var r,o;return((r=e.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let e=this.getAll();if(!t||t.length===0)return e;let r=new Set(t.map(s=>s.id));return[...e.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var e;return(e=t.onUnregister)==null?void 0:e.call(t)}),this.plugins.clear()}},yl=new bl;var Rm=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>e(o,s)),e=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:t,off:e,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 sv=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},av=n=>{let t=n.trim(),e=t.indexOf("{");if(e===-1)return null;let r=0;for(let o=e;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(e,o+1)}return null},xl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=sv(n),e=av(t);if(!e)return null;let r=JSON.parse(e);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}},vl=n=>typeof n=="string"?n:n==null?"":String(n),fa={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:vl(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let e=n.payload,r=vl(e.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:vl(e.text)}}},Bm=n=>Array.isArray(n)?n.map(t=>String(t)):[],wl=n=>{let t=new Set(Bm(n.getSessionMetadata().processedActionMessageIds)),e=()=>{t=new Set(Bm(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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,g)=>c||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!i)return null;t.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 g=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:e}};var iv=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},lv=n=>n.map(t=>({...t,streaming:!1})),cv=n=>n.map(t=>({...t,status:"complete"})),Hm=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let e=t();return e?iv(e.getItem(n)):null},save:e=>{let r=t();if(r)try{let o={...e,messages:e.messages?lv(e.messages):void 0,artifacts:e.artifacts?cv(e.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let e=t();if(e)try{e.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as xA,STR as wA,OBJ as CA}from"partial-json";function Dm(n,t){let{config:e,message:r,onPropsUpdate:o}=t,s=zo.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:e,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 Nm(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let t=n.content.trim();if(t.startsWith("{")||t.startsWith("["))return n.content}return null}function Fm(n){let t=Nm(n);if(!t)return!1;try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function _m(n){let t=Nm(n);if(!t)return null;try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"){let r=e;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var dv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Om(n){let{onSubmit:t,onDismiss:e,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=dv}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),u.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),k.title=c[C-1],k.dataset.rating=String(C),k.innerHTML=`
29
29
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
30
30
  <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>
31
31
  </svg>
32
- `,I.addEventListener("click",()=>{f=C,E.forEach((B,D)=>{let T=D<C;B.classList.toggle("selected",T),B.setAttribute("aria-checked",D===C-1?"true":"false")})}),E.push(I),M.appendChild(I)}u.appendChild(M);let k=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),C.appendChild(k),u.appendChild(C)}let N=document.createElement("div");N.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{t==null||t(),g.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){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let C=(k==null?void 0:k.value.trim())||void 0;await e(f,C),g.remove()}catch(C){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),N.appendChild(P),N.appendChild(W),u.appendChild(N),g.appendChild(u),g}function Dm(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:g="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 u=null,m=document.createElement("div");m.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 M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=o,v.appendChild(M),m.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let N=document.createElement("span");N.className="persona-feedback-label-low",N.textContent=c;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=g,k.appendChild(N),k.appendChild(P);let W=document.createElement("div");W.className="persona-feedback-numbers";let C=[];for(let q=0;q<=10;q++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${q} out of 10`),z.textContent=String(q),z.dataset.rating=String(q),q<=6?z.classList.add("persona-feedback-detractor"):q<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{u=q,C.forEach((re,ke)=>{re.classList.toggle("selected",ke===q),re.setAttribute("aria-checked",ke===q?"true":"false")})}),C.push(z),W.appendChild(z)}E.appendChild(k),E.appendChild(W),m.appendChild(E);let I=null;if(d){let q=document.createElement("div");q.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"),q.appendChild(I),m.appendChild(q)}let B=document.createElement("div");B.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{t==null||t(),f.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=a,T.addEventListener("click",async()=>{if(u===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let q=(I==null?void 0:I.value.trim())||void 0;await e(u,q),f.remove()}catch(q){T.disabled=!1,T.textContent=a,console.error("[NPS Feedback] Failed to submit:",q)}}),B.appendChild(D),B.appendChild(T),m.appendChild(B),f.appendChild(m),f}var Cs="persona-chat-history",sv=30*1e3,av={"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 iv(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=av[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 Si(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 lv(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 cv(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var vl=n=>!n||typeof n!="object"?{}:{...n},Nm=n=>n.map(e=>({...e,streaming:!1})),Fm=(n,e,t)=>{let r=n!=null&&n.markdown?Ha(n.markdown):null,o=Ba(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 c,g,f;let a=(c=s.text)!=null?c:"",i=(g=s.message.rawContent)!=null?g: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;return n!=null&&n.postprocessMessage?d=n.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""}):r?d=r(a):d=fo(a),o?o(d):d}};function Om(n){var i,d,c,g;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=(g=n==null?void 0:n.iconStrokeWidth)!=null?g:.5,a=Ae(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 _m=(n,e,t)=>{var zl,Vl,jl,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,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc;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=Bu(e),o=fl.getForInstance(r.plugins);r.components&&zo.registerAll(r.components);let s=km(),i=r.persistState===!1?null:(zl=r.storageAdapter)!=null?zl:Pm(),d={},c=null,g=!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&&(g=!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=vl(h.metadata)),(Vl=h.messages)!=null&&Vl.length&&(r={...r,initialMessages:h.messages}),(jl=h.artifacts)!=null&&jl.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Kl=h.selectedArtifactId)!=null?Kl: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:{}});(Gl=l.messages)!=null&&Gl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>d,m=l=>{var h;d=(h=l({...d}))!=null?h:{},Yo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[yl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[fa.message,fa.messageAndClick],M=bl({parsers:v,handlers:x,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let E=(Xl=(Ql=r.launcher)==null?void 0:Ql.enabled)!=null?Xl:!0,k=(Yl=(Jl=r.launcher)==null?void 0:Jl.autoExpand)!=null?Yl:!1,N=(Zl=r.autoFocusInput)!=null?Zl:!1,P=k,W=E,C=(tc=(ec=r.layout)==null?void 0:ec.header)==null?void 0:tc.layout,I=!1,B=()=>ca(r),D=()=>E||B(),T=B()?!1:E?k:!0,q=!1,z=null,re=()=>{q=!0,z&&clearTimeout(z),z=setTimeout(()=>{q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),q=!1)},1e4)},ke=Fm(r,M,re),Ve=(rc=(nc=r.features)==null?void 0:nc.showReasoning)!=null?rc:!0,be=(sc=(oc=r.features)==null?void 0:oc.showToolCalls)!=null?sc:!0,He=(ic=(ac=r.features)==null?void 0:ac.showEventStreamToggle)!=null?ic:!1,Fe=(cc=(lc=r.features)==null?void 0:lc.scrollToBottom)!=null?cc:{},Se=(pc=(dc=r.features)==null?void 0:dc.scrollBehavior)!=null?pc:{},oe=`${(mc=typeof r.persistState=="object"?(uc=r.persistState)==null?void 0:uc.keyPrefix:void 0)!=null?mc:"persona-"}event-stream`,G=He?new ma(oe):null,se=(hc=(fc=(gc=r.features)==null?void 0:gc.eventStream)==null?void 0:fc.maxEvents)!=null?hc:2e3,ge=He?new ua(se,G):null,pe=He?new ga:null,j=null,ae=!1,Ie=null,ee=0;G==null||G.open().then(()=>ge==null?void 0:ge.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Z={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)}},ne=(yc=r.statusIndicator)!=null?yc:{},at=l=>{var p,h,y,A;return l==="idle"?(p=ne.idleText)!=null?p:Tn.idle:l==="connecting"?(h=ne.connectingText)!=null?h:Tn.connecting:l==="connected"?(y=ne.connectedText)!=null?y:Tn.connected:l==="error"?(A=ne.errorText)!=null?A:Tn.error:Tn[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 ot=sm({config:r,showClose:D()}),{wrapper:Me,panel:fe,pillRoot:Xe}=ot.shell,J=ot.panelElements,{container:ue,body:Ee,messagesWrapper:Je,suggestions:Ke,textarea:Pe,sendButton:je,sendButtonWrapper:bn,composerForm:Wt,statusText:dn,introTitle:wr,introSubtitle:$,closeButton:K,iconHolder:he,headerTitle:Ge,headerSubtitle:Ze,header:$e,footer:Oe,actionsRow:Lt,leftActions:jt,rightActions:Xt}=J,kn=J.setSendButtonMode,V=J.micButton,Rt=J.micButtonWrapper,le=J.attachmentButton,we=J.attachmentButtonWrapper,Ne=J.attachmentInput,St=J.attachmentPreviewsContainer;ue.classList.add("persona-relative"),Ee.classList.add("persona-relative");let rn=12,on=()=>{var l;return(l=Fe.label)!=null?l:""},vn=()=>{var l;return(l=Fe.iconName)!=null?l:"arrow-down"},Dt=()=>Fe.enabled!==!1,nt=()=>{var l;return(l=Se.mode)!=null?l:"follow"},Bt=()=>{var l;return(l=Se.anchorTopOffset)!=null?l:16},dt=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");dt.type="button",dt.style.display="none",dt.setAttribute("data-persona-scroll-to-bottom","true");let Jt=b("span","persona-flex persona-items-center"),tr=b("span",""),Ln=b("span","");Ln.setAttribute("data-persona-scroll-to-bottom-count",""),Ln.style.display="none",dt.append(Jt,tr,Ln),ue.appendChild(dt);let sn=b("div","persona-stream-anchor-spacer");sn.setAttribute("aria-hidden","true"),sn.setAttribute("data-persona-anchor-spacer",""),sn.style.flexShrink="0",sn.style.pointerEvents="none",sn.style.height="0px",Ee.appendChild(sn);let Fn=()=>{let p=Oe.style.display==="none"?0:Oe.offsetHeight;dt.style.bottom=`${p+rn}px`};Fn();let Cr=()=>{let l=!!on();dt.setAttribute("aria-label",on()||"Jump to latest"),dt.title=on(),dt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Jt.innerHTML="";let p=Ae(vn(),"14px","currentColor",2);p?(Jt.appendChild(p),Jt.style.display=""):Jt.style.display="none",tr.textContent=on(),tr.style.display=l?"":"none"};Cr();let vt=null,qn=null,Ar=o.find(l=>l.renderHeader);if(Ar!=null&&Ar.renderHeader){let l=Ar.renderHeader({config:r,defaultRenderer:()=>{let p=Uo({config:r,showClose:D()});return da(ue,p,r),p.header},onClose:()=>S(!1,"user")});if(l){let p=ue.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),$e=l,ot.header.element=l)}}let Nr=()=>{var p,h,y,A;if(!ge)return;if(ae=!0,!j&&ge&&(j=bm({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>ur(),config:r,plugins:o,getThroughput:()=>{var H;return(H=pe==null?void 0:pe.getMetric())!=null?H:{status:"idle"}}})),j&&(Ee.style.display="none",(p=Oe.parentNode)==null||p.insertBefore(j.element,Oe),j.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Nn.actionIconColor}`;let H=(A=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:A.toggleButtonActive;H&&H.split(/\s+/).forEach(U=>U&&yt.classList.add(U))}let l=()=>{if(!ae)return;let H=Date.now();H-ee>=200&&(j==null||j.update(),ee=H),Ie=requestAnimationFrame(l)};ee=0,Ie=requestAnimationFrame(l),$n(),s.emit("eventStream:opened",{timestamp:Date.now()})},ur=()=>{var l,p,h;if(ae){if(ae=!1,j&&j.element.remove(),Ee.style.display="",yt){yt.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&&yt.classList.remove(A))}Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),$n(),s.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(He){let l=(vc=(bc=r.features)==null?void 0:bc.eventStream)==null?void 0:vc.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:"");yt=b("button",p),yt.style.width="28px",yt.style.height="28px",yt.style.color=Nn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=Ae("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let y=J.clearChatButtonWrapper,A=J.closeButtonWrapper,H=y||A;H&&H.parentNode===$e?$e.insertBefore(yt,H):$e.appendChild(yt),yt.addEventListener("click",()=>{ae?ur():Nr()})}let xo=l=>{var A,H,U,F,R;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 ce=l.querySelector("[data-persona-composer-form]");ce!=null&&ce.parentNode?ce.parentNode.insertBefore(h,ce):l.insertBefore(h,l.firstChild)}if(!((H=l.querySelector("[data-persona-composer-attachment-input]"))!=null?H:l.querySelector('input[type="file"]'))){let ce=b("input");ce.type="file",ce.setAttribute("data-persona-composer-attachment-input",""),ce.accept=((U=p.allowedTypes)!=null?U:Gr).join(","),ce.multiple=((F=p.maxFiles)!=null?F:4)>1,ce.style.display="none",ce.setAttribute("aria-label",(R=p.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(ce)}},Sr=o.find(l=>l.renderComposer);if(Sr!=null&&Sr.renderComposer){let l=r.composer,p=Sr.renderComposer({config:r,defaultRenderer:()=>bi({config:r}).footer,onSubmit:h=>{var U;if(!O||O.isStreaming())return;let y=h.trim(),A=(U=vt==null?void 0:vt.hasAttachments())!=null?U:!1;if(!y&&!A)return;et();let H;A&&(H=[],H.push(...vt.getContentParts()),y&&H.push(Vi(y))),O.sendMessage(y,{contentParts:H}),A&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ne==null||Ne.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:((xc=r.voiceRecognition)==null?void 0:xc.enabled)===!0?()=>{qn==null||qn()}:void 0});p&&(ot.replaceComposer(p),Oe=ot.composer.footer)}let wo=l=>{let p=(...de)=>{for(let Y of de){let ve=l.querySelector(Y);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),H=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");h&&(Wt=h),y&&(Pe=y),A&&(je=A),H&&(V=H,Rt=H.parentElement),U&&(dn=U);let F=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Ke=F);let R=p("[data-persona-composer-attachment-button]",".persona-attachment-button");R&&(le=R,we=R.parentElement),Ne=p("[data-persona-composer-attachment-input]",'input[type="file"]'),St=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ce=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ce&&(Lt=ce)};xo(Oe),wo(Oe);let On=(Tc=(wc=r.layout)==null?void 0:wc.contentMaxWidth)!=null?Tc:B()?(Sc=(Ac=(Cc=r.launcher)==null?void 0:Cc.composerBar)==null?void 0:Ac.contentMaxWidth)!=null?Sc:"720px":void 0;if(On&&(Je.style.maxWidth=On,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%"),On&&Wt&&!B()&&(Wt.style.maxWidth=On,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),On&&Ke&&!B()&&(Ke.style.maxWidth=On,Ke.style.marginLeft="auto",Ke.style.marginRight="auto"),On&&St&&!B()&&(St.style.maxWidth=On,St.style.marginLeft="auto",St.style.marginRight="auto"),(Mc=r.attachments)!=null&&Mc.enabled&&Ne&&St){vt=ta.fromConfig(r.attachments),vt.setPreviewsContainer(St),Ne.addEventListener("change",h=>{let y=h.target;vt==null||vt.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=Om(l);ue.appendChild(p)}(()=>{var y,A;let l=(A=(y=r.layout)==null?void 0:y.slots)!=null?A:{},p=H=>{switch(H){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Je;case"footer-top":return Ke;case"composer":return Wt;case"footer-bottom":return dn;default:return null}},h=(H,U)=>{var F;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")$e.insertBefore(U,$e.firstChild);else if(H==="header-right")$e.appendChild(U);else{let R=$e.querySelector(".persona-flex-col");R?(F=R.parentNode)==null||F.insertBefore(U,R.nextSibling):$e.appendChild(U)}break;case"body-top":{let R=Ee.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(U):Ee.insertBefore(U,Ee.firstChild);break}case"body-bottom":Ee.appendChild(U);break;case"footer-top":Ke.replaceWith(U);break;case"footer-bottom":dn.replaceWith(U);break;default:break}};for(let[H,U]of Object.entries(l))if(U)try{let F=U({config:r,defaultContent:()=>p(H)});F&&h(H,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,F)}})();let Jr=l=>{var U,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 H=h.getAttribute("data-bubble-type");if(H==="reasoning")vs.has(A)?vs.delete(A):vs.add(A),lm(A,y);else if(H==="tool")xs.has(A)?xs.delete(A):xs.add(A),cm(A,y,r);else if(H==="approval"){let R=r.approval!==!1?r.approval:void 0,ce=((U=R==null?void 0:R.detailsDisplay)!=null?U:"collapsed")==="expanded",de=(F=vi.get(A))!=null?F:ce;vi.set(A,!de),mm(A,y,r)}Lr.delete(A)};Je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Jr(l))}),Je.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Jr(l))});let Fr=new Map,Yr=null,Zr="idle",Co={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ao=(l,p)=>{let{icon:h,label:y}=Co[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=Ae(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},eo=()=>{Je.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var H;let h=p.closest("[data-actions-for]"),y=(H=h==null?void 0:h.getAttribute("data-actions-for"))!=null?H:null;Ao(p,y&&y===Yr?Zr:"idle")})};Je.addEventListener("click",l=>{var U;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 H=h.getAttribute("data-action");if(H==="copy"){let R=O.getMessages().find(ce=>ce.id===A);if(R&&Z.onCopy){let ce=R.content||"";navigator.clipboard.writeText(ce).then(()=>{h.classList.add("persona-message-action-success");let de=Ae("check",14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=Ae("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(de=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",de)}),Z.onCopy(R)}}else if(H==="read-aloud")O.toggleReadAloud(A);else if(H==="upvote"||H==="downvote"){let R=((U=Fr.get(A))!=null?U:null)===H,ce=H==="upvote"?"thumbs-up":"thumbs-down";if(R){Fr.delete(A),h.classList.remove("persona-message-action-active");let de=Ae(ce,14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de))}else{let de=H==="upvote"?"downvote":"upvote",Y=y.querySelector(`[data-action="${de}"]`);if(Y){Y.classList.remove("persona-message-action-active");let qe=Ae(de==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(Y.innerHTML="",Y.appendChild(qe))}Fr.set(A,H),h.classList.add("persona-message-action-active");let ve=Ae(ce,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=O.getMessages().find(rt=>rt.id===A);Ce&&Z.onFeedback&&Z.onFeedback({type:H,messageId:Ce.id,message:Ce})}}}),Je.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 H=h.getAttribute("data-approval-action");if(!H)return;let U=H==="approve"?"approved":"denied",R=O.getMessages().find(de=>de.id===A);if(!(R!=null&&R.approval))return;let ce=y.querySelector("[data-approval-buttons]");ce&&ce.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),R.approval.toolType==="webmcp"?O.resolveWebMcpApproval(A,U):O.resolveApproval(R.approval,U)});let wt=null,zn=null,Vn={artifacts:[],selectedId:null},Pn=!1,Tt={current:null};Je.addEventListener("click",l=>{var Y,ve,De,Ce,rt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((De=(ve=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:De.call(ve,{type:"download",artifactId:y}))===!0)return;let H=O.getArtifactById(y),U=H==null?void 0:H.markdown,F=(H==null?void 0:H.title)||"artifact";if(!U){let qe=h.closest("[data-open-artifact]"),gt=qe==null?void 0:qe.closest("[data-message-id]"),lt=gt==null?void 0:gt.getAttribute("data-message-id");if(lt){let Le=O.getMessages().find(ze=>ze.id===lt);if(Le!=null&&Le.rawContent)try{let ze=JSON.parse(Le.rawContent);U=(Ce=ze==null?void 0:ze.props)==null?void 0:Ce.markdown,F=((rt=ze==null?void 0:ze.props)==null?void 0:rt.title)||F}catch{}}}if(!U)return;let R=new Blob([U],{type:"text/markdown"}),ce=URL.createObjectURL(R),de=document.createElement("a");de.href=ce,de.download=`${F}.md`,de.click(),URL.revokeObjectURL(ce)}),Je.addEventListener("click",l=>{var H,U,F;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((F=(U=(H=r.features)==null?void 0:H.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:F.call(U,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),Pn=!1,O.selectArtifact(y),Gn())}),Je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let nr=J.composerOverlay,rr=(l,p,h)=>{var F,R,ce,de;let y=p.trim();if(!y||!Tt.current)return;let A=(F=l.getAttribute("data-tool-call-id"))!=null?F:"",H=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:y,answers:h.structured,values:(R=h.values)!=null?R:h.source==="multi"?y.split(", "):[y],isFreeText:H,source:h.source},bubbles:!0,composed:!0})),ps(nr,A);let U=Tt.current.getMessages().find(Y=>{var ve;return((ve=Y.toolCall)==null?void 0:ve.id)===A});(ce=U==null?void 0:U.agentMetadata)!=null&&ce.awaitingLocalTool?Tt.current.resolveAskUserQuestion(U,(de=h.structured)!=null?de:y):Tt.current.sendMessage(y)},jn=l=>{var A;let p=Tt.current;if(!p)return;let h=(A=l.getAttribute("data-tool-call-id"))!=null?A:"",y=p.getMessages().find(H=>{var U;return((U=H.toolCall)==null?void 0:U.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:Fa(l,y),currentIndex:dr(l)})},to=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Or=l=>{var A,H,U;if(((H=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:H.groupedAutoAdvance)===!1)return;let p=dr(l),h=ds(l);if(p>=h-1)return;let y=(U=Tt.current)==null?void 0:U.getMessages().find(F=>{var R;return((R=F.toolCall)==null?void 0:R.id)===l.getAttribute("data-tool-call-id")});y&&(_a(l,y,r,p+1),jn(l))};nr.addEventListener("click",l=>{var H,U,F,R,ce,de,Y,ve,De,Ce,rt,qe,gt,lt;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 We=(H=y.getAttribute("data-tool-call-id"))!=null?H:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),ps(nr,We);let Le=(U=Tt.current)==null?void 0:U.getMessages().find(ze=>{var Qe;return((Qe=ze.toolCall)==null?void 0:Qe.id)===We});(F=Le==null?void 0:Le.agentMetadata)!=null&&F.awaitingLocalTool&&((R=Tt.current)==null||R.markAskUserQuestionResolved(Le),(ce=Tt.current)==null||ce.resolveAskUserQuestion(Le,"(dismissed)"));return}if(A==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Le=y.getAttribute("data-multi-select")==="true",ze=ho(y);if(ze&&Le){let Qe=No(y)[dr(y)],bt=new Set(Array.isArray(Qe)?Qe:[]);bt.has(We)?bt.delete(We):bt.add(We),yo(y,Array.from(bt)),jn(y);return}if(ze){yo(y,We),jn(y),Or(y);return}if(Le){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let bt=y.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=Oi(y).length===0);return}rr(y,We,{source:"pick",values:[We]});return}if(A==="submit-multi"){let We=Oi(y);if(We.length===0)return;rr(y,We.join(", "),{source:"multi",values:We});return}if(A==="open-free-text"){let We=y.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Le=We.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(A==="focus-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(A==="submit-free-text"){let We=y.querySelector('[data-ask-free-text-input="true"]'),Le=(de=We==null?void 0:We.value)!=null?de:"";if(!Le.trim())return;if(ho(y)){yo(y,Le.trim()),jn(y),Or(y);return}rr(y,Le,{source:"free-text"});return}if(A==="next"||A==="back"){if(!Tt.current)return;let We=(Y=y.getAttribute("data-tool-call-id"))!=null?Y:"",Le=Tt.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===We});if(!Le)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(De=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?De:"";if(Qe){let Be=No(y)[dr(y)];(typeof Be!="string"||Be!==Qe)&&yo(y,Qe)}let bt=A==="next"?1:-1,L=dr(y)+bt;_a(y,Le,r,L),jn(y);return}if(A==="submit-all"){if(!Tt.current)return;let We=(Ce=y.getAttribute("data-tool-call-id"))!=null?Ce:"",Le=Tt.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===We});if(!Le)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Qe=(qe=(rt=ze==null?void 0:ze.value)==null?void 0:rt.trim())!=null?qe:"";Qe&&yo(y,Qe);let bt=Fa(y,Le);Tt.current.persistAskUserQuestionProgress(Le,{answers:bt,currentIndex:dr(y)});let L=to(bt);rr(y,L||"(submitted)",{source:"submit-all",structured:bt});return}if(A==="skip"){if(!Tt.current)return;let We=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",Le=Tt.current.getMessages().find(Re=>{var me;return((me=Re.toolCall)==null?void 0:me.id)===We});if(!Le)return;let ze=ho(y),Qe=dr(y),bt=ds(y),L=Qe>=bt-1;if(!ze){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),ps(nr,We),(lt=Le.agentMetadata)!=null&&lt.awaitingLocalTool&&(Tt.current.markAskUserQuestionResolved(Le),Tt.current.resolveAskUserQuestion(Le,"(dismissed)"));return}yo(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),L){let Re=Fa(y,Le),me=to(Re);rr(y,me||"(skipped)",{source:"submit-all",structured:Re});return}_a(y,Le,r,Qe+1),jn(y);return}}),nr.addEventListener("keydown",l=>{var H;if(l.key!=="Enter")return;let h=l.target;if(!((H=h.matches)!=null&&H.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(ho(y)){yo(y,A.trim()),jn(y),Or(y);return}rr(y,A,{source:"free-text"})}});let no=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=nr.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),H=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];H&&(l.preventDefault(),H.click())};document.addEventListener("keydown",no);let Kn=null,Nt=null,In=null,or=null,ro=()=>{};function _r(){or==null||or(),or=null}let oo=()=>{var U;if(!Kn||!Nt)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((U=n.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){Nt.style.removeProperty("position"),Nt.style.removeProperty("left"),Nt.style.removeProperty("top"),Nt.style.removeProperty("bottom"),Nt.style.removeProperty("width"),Nt.style.removeProperty("z-index");return}let y=Kn.firstElementChild;if(!y||y===Nt)return;let A=10;Nt.style.position="absolute",Nt.style.top="0",Nt.style.bottom="0",Nt.style.width=`${A}px`,Nt.style.zIndex="5";let H=y.offsetWidth-A/2;Nt.style.left=`${Math.max(0,H)}px`},Tr=()=>{},Gn=()=>{var h,y,A,H,U;if(!wt||!pr(r))return;Ci(n,r),Ai(n,r),Tr();let l=(H=(A=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:A.narrowHostMaxWidth)!=null?H:520,p=fe.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),wt.update(Vn),Pn?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(U=wt.backdrop)==null||U.classList.add("persona-hidden")):Vn.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),ro()};if(pr(r)){fe.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(ue),wt=wm(r,{onSelect:h=>{var y;return(y=Tt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Pn=!0,Gn()}}),wt.element.classList.add("persona-hidden"),Kn=p,p.appendChild(l),p.appendChild(wt.element),wt.backdrop&&fe.appendChild(wt.backdrop),fe.appendChild(p),ro=()=>{var y,A,H,U;if(!Kn||!wt)return;if(!(((H=(A=(y=r.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:H.resizable)===!0)){In==null||In(),In=null,_r(),Nt&&(Nt.remove(),Nt=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!Nt){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 R=n.ownerDocument,ce=(U=R.defaultView)!=null?U:window,de=Y=>{var gt,lt;if(!wt||Y.button!==0||n.classList.contains("persona-artifact-narrow-host")||ce.innerWidth<=640)return;Y.preventDefault(),_r();let ve=Y.clientX,De=wt.element.getBoundingClientRect().width,Ce=(lt=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:lt.layout,rt=We=>{let Le=Kn.getBoundingClientRect().width,ze=n.classList.contains("persona-artifact-appearance-seamless"),Qe=ze?0:Tm(Kn,ce),bt=ze?0:F.getBoundingClientRect().width||6,L=De-(We.clientX-ve),Be=Mm(L,Le,Qe,bt,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);wt.element.style.width=`${Be}px`,wt.element.style.maxWidth="none",oo()},qe=()=>{R.removeEventListener("pointermove",rt),R.removeEventListener("pointerup",qe),R.removeEventListener("pointercancel",qe),or=null;try{F.releasePointerCapture(Y.pointerId)}catch{}};or=qe,R.addEventListener("pointermove",rt),R.addEventListener("pointerup",qe),R.addEventListener("pointercancel",qe);try{F.setPointerCapture(Y.pointerId)}catch{}};F.addEventListener("pointerdown",de),Nt=F,Kn.insertBefore(F,wt.element),In=()=>{F.removeEventListener("pointerdown",de)}}if(Nt){let F=Vn.artifacts.length>0&&!Pn;Nt.classList.toggle("persona-hidden",!F),oo()}},Tr=()=>{var ce,de,Y,ve,De,Ce,rt,qe,gt,lt,We,Le,ze,Qe;if(!E||!wt||((de=(ce=r.launcher)==null?void 0:ce.sidebarMode)!=null?de:!1)||wn(r)&&vr(r).reveal==="emerge")return;let y=(Y=n.ownerDocument.defaultView)!=null?Y:window,A=(De=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?De:!0,H=(rt=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?rt:640;if(A&&y.innerWidth<=H||!Sm(r,E))return;let U=(lt=(gt=(qe=r.launcher)==null?void 0:qe.width)!=null?gt:r.launcherWidth)!=null?lt:Qr,F=(Qe=(ze=(Le=(We=r.features)==null?void 0:We.artifacts)==null?void 0:Le.layout)==null?void 0:ze.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!Pn?(fe.style.width=F,fe.style.maxWidth=F):(fe.style.width=U,fe.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(zn=new ResizeObserver(()=>{Gn()}),zn.observe(fe))}else fe.appendChild(ue),B()&&Xe&&(J.peekBanner&&Xe.appendChild(J.peekBanner),Xe.appendChild(Oe));n.appendChild(Me),Xe&&n.appendChild(Xe);let ye=()=>{var Be,Re,me,_t,Ft,Kt,xt,zt,Jn,nn,Ye,Pt,cn,cr,Yn,ko,Lo,os,ss,Gt,Po,mo,go,jr,Io,hr,tt,mn;if(B()){fe.style.width="100%",fe.style.maxWidth="100%";let Ut=(Re=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?Re:{},$t=Me.dataset.state==="expanded",ft=(me=Ut.expandedSize)!=null?me:"anchored";if(!($t&&ft!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let At=(Ft=(_t=r.theme)==null?void 0:_t.components)==null?void 0:Ft.panel,An=ei(r),Rn=(Bn,Wo)=>{var Os;return Bn==null||Bn===""?Wo:(Os=hs(An,Bn))!=null?Os:Bn},Br="1px solid var(--persona-border)",yn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Hn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Rn(At==null?void 0:At.border,Br),ue.style.borderRadius=Rn(At==null?void 0:At.borderRadius,Hn),ue.style.boxShadow=Rn(At==null?void 0:At.shadow,yn),ue.style.overflow="hidden";return}let l=wn(r),p=(xt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?xt:!1,h=l||p||((Jn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?Jn:!1),y=((nn=r.launcher)==null?void 0:nn.enabled)===!1,A=(Pt=(Ye=r.theme)==null?void 0:Ye.components)==null?void 0:Pt.panel,H=ei(r),U=(Ut,$t)=>{var ft;return Ut==null||Ut===""?$t:(ft=hs(H,Ut))!=null?ft:Ut},F=(cn=n.ownerDocument.defaultView)!=null?cn:window,R=(Yn=(cr=r.launcher)==null?void 0:cr.mobileFullscreen)!=null?Yn:!0,ce=(Lo=(ko=r.launcher)==null?void 0:ko.mobileBreakpoint)!=null?Lo:640,de=F.innerWidth<=ce,Y=R&&de&&E,ve=(ss=(os=r.launcher)==null?void 0:os.position)!=null?ss:"bottom-left",De=ve==="bottom-left"||ve==="top-left",Ce=(Po=(Gt=r.launcher)==null?void 0:Gt.zIndex)!=null?Po:Mn,rt=p||Y?"none":"1px solid var(--persona-border)",qe=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&&(qe="none",rt="none");let gt=p||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=U(A==null?void 0:A.border,rt),We=U(A==null?void 0:A.shadow,qe),Le=U(A==null?void 0:A.borderRadius,gt),ze=Ee.scrollTop;n.style.cssText="",Me.style.cssText="",fe.style.cssText="",ue.style.cssText="",Ee.style.cssText="",Oe.style.cssText="";let Qe=()=>{var $t;if(ze<=0)return;(($t=Ee.ownerDocument.defaultView)!=null?$t:window).requestAnimationFrame(()=>{if(Ee.scrollTop===ze)return;let ft=Ee.scrollHeight-Ee.clientHeight;ft<=0||(Ee.scrollTop=Math.min(ze,ft))})};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=`
32
+ `,k.addEventListener("click",()=>{f=C,E.forEach((D,N)=>{let M=N<C;D.classList.toggle("selected",M),D.setAttribute("aria-checked",N===C-1?"true":"false")})}),E.push(k),T.appendChild(k)}u.appendChild(T);let A=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),C.appendChild(A),u.appendChild(C)}let R=document.createElement("div");R.className="persona-feedback-actions";let L=document.createElement("button");L.type="button",L.className="persona-feedback-btn persona-feedback-btn-skip",L.textContent=i,L.addEventListener("click",()=>{e==null||e(),g.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){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let C=(A==null?void 0:A.value.trim())||void 0;await t(f,C),g.remove()}catch(C){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),R.appendChild(L),R.appendChild(W),u.appendChild(R),g.appendChild(u),g}function $m(n){let{onSubmit:t,onDismiss:e,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:g="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 u=null,m=document.createElement("div");m.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 T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=o,v.appendChild(T),m.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=c;let L=document.createElement("span");L.className="persona-feedback-label-high",L.textContent=g,A.appendChild(R),A.appendChild(L);let W=document.createElement("div");W.className="persona-feedback-numbers";let C=[];for(let U=0;U<=10;U++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${U} out of 10`),z.textContent=String(U),z.dataset.rating=String(U),U<=6?z.classList.add("persona-feedback-detractor"):U<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{u=U,C.forEach((ne,Le)=>{ne.classList.toggle("selected",Le===U),ne.setAttribute("aria-checked",Le===U?"true":"false")})}),C.push(z),W.appendChild(z)}E.appendChild(A),E.appendChild(W),m.appendChild(E);let k=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),U.appendChild(k),m.appendChild(U)}let D=document.createElement("div");D.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{e==null||e(),f.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=a,M.addEventListener("click",async()=>{if(u===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let U=(k==null?void 0:k.value.trim())||void 0;await t(u,U),f.remove()}catch(U){M.disabled=!1,M.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),D.appendChild(N),D.appendChild(M),m.appendChild(D),f.appendChild(m),f}var ws="persona-chat-history",pv=30*1e3,uv={"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 mv(n){var r,o,s;if(!n)return[];let t=[],e=Array.from((r=n.items)!=null?r:[]);for(let a of e){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=uv[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Mi(n){if(!n)return!1;let t=n.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function gv(n){var t,e,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:(t=n.storage)!=null?t:"session",keyPrefix:(e=n.keyPrefix)!=null?e:"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 fv(n){try{let t=n==="local"?localStorage:sessionStorage,e="__persist_test__";return t.setItem(e,"1"),t.removeItem(e),t}catch{return null}}var Cl=n=>!n||typeof n!="object"?{}:{...n},qm=n=>n.map(t=>({...t,streaming:!1})),Um=(n,t,e)=>{let r=n!=null&&n.markdown?Da(n.markdown):null,o=Na(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 c,g,f;let a=(c=s.text)!=null?c:"",i=(g=s.message.rawContent)!=null?g:null;if(t){let u=t.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&&e&&e())}let d;return n!=null&&n.postprocessMessage?d=n.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""}):r?d=r(a):d=fo(a),o?o(d):d}};function zm(n){var i,d,c,g;let t=y("div","persona-attachment-drop-overlay");n!=null&&n.background&&t.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&t.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&t.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let e=(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=(g=n==null?void 0:n.iconStrokeWidth)!=null?g:.5,a=Ae(e,r,o,s);if(a&&t.appendChild(a),n!=null&&n.label){let f=y("span","persona-drop-overlay-label");f.textContent=n.label,t.appendChild(f)}return t}var jm=(n,t,e)=>{var 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,bc,yc,vc,xc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Ic,Pc,Wc,Rc,Bc,Hc,Dc,Nc,Fc,_c,Oc,$c;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=Ou(t),o=yl.getForInstance(r.plugins);r.components&&zo.registerAll(r.components);let s=Rm(),i=r.persistState===!1?null:(Vl=r.storageAdapter)!=null?Vl:Hm(),d={},c=null,g=!1,f=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(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=Cl(h.metadata)),(Kl=h.messages)!=null&&Kl.length&&(r={...r,initialMessages:h.messages}),(Gl=h.artifacts)!=null&&Gl.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Ql=h.selectedArtifactId)!=null?Ql: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:{}});(Xl=l.messages)!=null&&Xl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>d,m=l=>{var h;d=(h=l({...d}))!=null?h:{},Yo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[xl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[fa.message,fa.messageAndClick],T=wl({parsers:v,handlers:x,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let E=(Yl=(Jl=r.launcher)==null?void 0:Jl.enabled)!=null?Yl:!0,A=(ec=(Zl=r.launcher)==null?void 0:Zl.autoExpand)!=null?ec:!1,R=(tc=r.autoFocusInput)!=null?tc:!1,L=A,W=E,C=(rc=(nc=r.layout)==null?void 0:nc.header)==null?void 0:rc.layout,k=!1,D=()=>ca(r),N=()=>E||D(),M=D()?!1:E?A:!0,U=!1,z=null,ne=()=>{U=!0,z&&clearTimeout(z),z=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},Le=Um(r,T,ne),je=(sc=(oc=r.features)==null?void 0:oc.showReasoning)!=null?sc:!0,ye=(ic=(ac=r.features)==null?void 0:ac.showToolCalls)!=null?ic:!0,De=(cc=(lc=r.features)==null?void 0:lc.showEventStreamToggle)!=null?cc:!1,$e=(pc=(dc=r.features)==null?void 0:dc.scrollToBottom)!=null?pc:{},Se=(mc=(uc=r.features)==null?void 0:uc.scrollBehavior)!=null?mc:{},re=`${(fc=typeof r.persistState=="object"?(gc=r.persistState)==null?void 0:gc.keyPrefix:void 0)!=null?fc:"persona-"}event-stream`,Q=De?new ma(re):null,oe=(yc=(bc=(hc=r.features)==null?void 0:hc.eventStream)==null?void 0:bc.maxEvents)!=null?yc:2e3,ge=De?new ua(oe,Q):null,de=De?new ga:null,V=null,se=!1,Re=null,Z=0;Q==null||Q.open().then(()=>ge==null?void 0:ge.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Y={onCopy:l=>{var p,h;s.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.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;s.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.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)}},te=(vc=r.statusIndicator)!=null?vc:{},ot=l=>{var p,h,b,S;return l==="idle"?(p=te.idleText)!=null?p:kn.idle:l==="connecting"?(h=te.connectingText)!=null?h:kn.connecting:l==="connected"?(b=te.connectedText)!=null?b:kn.connected:l==="error"?(S=te.errorText)!=null?S:kn.error:kn[l]};function st(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 tt=dm({config:r,showClose:N()}),{wrapper:Ee,panel:fe,pillRoot:Ke}=tt.shell,X=tt.panelElements,{container:pe,body:ke,messagesWrapper:Qe,suggestions:Kt,textarea:Ie,sendButton:qe,sendButtonWrapper:nt,composerForm:Dt,statusText:bn,introTitle:xr,introSubtitle:An,closeButton:Ve,iconHolder:Nt,headerTitle:$,headerSubtitle:Me,header:we,footer:Fe,actionsRow:at,leftActions:dt,rightActions:rt}=X,Et=X.setSendButtonMode,j=X.micButton,At=X.micButtonWrapper,ce=X.attachmentButton,ue=X.attachmentButtonWrapper,Te=X.attachmentInput,pt=X.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ke.classList.add("persona-relative");let Zt=12,sn=()=>{var l;return(l=$e.label)!=null?l:""},xn=()=>{var l;return(l=$e.iconName)!=null?l:"arrow-down"},_t=()=>$e.enabled!==!1,Ze=()=>{var l;return(l=Se.mode)!=null?l:"follow"},Ft=()=>{var l;return(l=Se.anchorTopOffset)!=null?l:16},ut=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");ut.type="button",ut.style.display="none",ut.setAttribute("data-persona-scroll-to-bottom","true");let en=y("span","persona-flex persona-items-center"),nr=y("span",""),Pn=y("span","");Pn.setAttribute("data-persona-scroll-to-bottom-count",""),Pn.style.display="none",ut.append(en,nr,Pn),pe.appendChild(ut);let an=y("div","persona-stream-anchor-spacer");an.setAttribute("aria-hidden","true"),an.setAttribute("data-persona-anchor-spacer",""),an.style.flexShrink="0",an.style.pointerEvents="none",an.style.height="0px",ke.appendChild(an);let _n=()=>{let p=Fe.style.display==="none"?0:Fe.offsetHeight;ut.style.bottom=`${p+Zt}px`};_n();let wr=()=>{let l=!!sn();ut.setAttribute("aria-label",sn()||"Jump to latest"),ut.title=sn(),ut.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),en.innerHTML="";let p=Ae(xn(),"14px","currentColor",2);p?(en.appendChild(p),en.style.display=""):en.style.display="none",nr.textContent=sn(),nr.style.display=l?"":"none"};wr();let wt=null,zn=null,Cr=o.find(l=>l.renderHeader);if(Cr!=null&&Cr.renderHeader){let l=Cr.renderHeader({config:r,defaultRenderer:()=>{let p=qo({config:r,showClose:N()});return da(pe,p,r),p.header},onClose:()=>he(!1,"user")});if(l){let p=pe.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),we=l,tt.header.element=l)}}let Dr=()=>{var p,h,b,S;if(!ge)return;if(se=!0,!V&&ge&&(V=Am({buffer:ge,getFullHistory:()=>ge.getAllFromStore(),onClose:()=>pr(),config:r,plugins:o,getThroughput:()=>{var H;return(H=de==null?void 0:de.getMetric())!=null?H:{status:"idle"}}})),V&&(ke.style.display="none",(p=Fe.parentNode)==null||p.insertBefore(V.element,Fe),V.update()),vt){vt.style.boxShadow=`inset 0 0 0 1.5px ${Fn.actionIconColor}`;let H=(S=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;H&&H.split(/\s+/).forEach(q=>q&&vt.classList.add(q))}let l=()=>{if(!se)return;let H=Date.now();H-Z>=200&&(V==null||V.update(),Z=H),Re=requestAnimationFrame(l)};Z=0,Re=requestAnimationFrame(l),qn(),s.emit("eventStream:opened",{timestamp:Date.now()})},pr=()=>{var l,p,h;if(se){if(se=!1,V&&V.element.remove(),ke.style.display="",vt){vt.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&&vt.classList.remove(S))}Re!==null&&(cancelAnimationFrame(Re),Re=null),qn(),s.emit("eventStream:closed",{timestamp:Date.now()})}},vt=null;if(De){let l=(wc=(xc=r.features)==null?void 0:xc.eventStream)==null?void 0:wc.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:"");vt=y("button",p),vt.style.width="28px",vt.style.height="28px",vt.style.color=Fn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let h=Ae("activity","18px","currentColor",1.5);h&&vt.appendChild(h);let b=X.clearChatButtonWrapper,S=X.closeButtonWrapper,H=b||S;H&&H.parentNode===we?we.insertBefore(vt,H):we.appendChild(vt),vt.addEventListener("click",()=>{se?pr():Dr()})}let xo=l=>{var S,H,q,F,B;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 ie=l.querySelector("[data-persona-composer-form]");ie!=null&&ie.parentNode?ie.parentNode.insertBefore(h,ie):l.insertBefore(h,l.firstChild)}if(!((H=l.querySelector("[data-persona-composer-attachment-input]"))!=null?H:l.querySelector('input[type="file"]'))){let ie=y("input");ie.type="file",ie.setAttribute("data-persona-composer-attachment-input",""),ie.accept=((q=p.allowedTypes)!=null?q:Gr).join(","),ie.multiple=((F=p.maxFiles)!=null?F:4)>1,ie.style.display="none",ie.setAttribute("aria-label",(B=p.buttonTooltipText)!=null?B:"Attach files"),l.appendChild(ie)}},Ar=o.find(l=>l.renderComposer);if(Ar!=null&&Ar.renderComposer){let l=r.composer,p=Ar.renderComposer({config:r,defaultRenderer:()=>wi({config:r}).footer,onSubmit:h=>{var q;if(!_||_.isStreaming())return;let b=h.trim(),S=(q=wt==null?void 0:wt.hasAttachments())!=null?q:!1;if(!b&&!S)return;We();let H;S&&(H=[],H.push(...wt.getContentParts()),b&&H.push(Gi(b))),_.sendMessage(b,{contentParts:H}),S&&wt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Te==null||Te.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:((Cc=r.voiceRecognition)==null?void 0:Cc.enabled)===!0?()=>{zn==null||zn()}:void 0});p&&(tt.replaceComposer(p),Fe=tt.composer.footer)}let wo=l=>{let p=(...le)=>{for(let J of le){let ve=l.querySelector(J);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),H=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(Dt=h),b&&(Ie=b),S&&(qe=S),H&&(j=H,At=H.parentElement),q&&(bn=q);let F=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Kt=F);let B=p("[data-persona-composer-attachment-button]",".persona-attachment-button");B&&(ce=B,ue=B.parentElement),Te=p("[data-persona-composer-attachment-input]",'input[type="file"]'),pt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(at=ie)};xo(Fe),wo(Fe);let On=(Mc=(Ac=r.layout)==null?void 0:Ac.contentMaxWidth)!=null?Mc:D()?(Ec=(Tc=(Sc=r.launcher)==null?void 0:Sc.composerBar)==null?void 0:Tc.contentMaxWidth)!=null?Ec:"720px":void 0;if(On&&(Qe.style.maxWidth=On,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%"),On&&Dt&&!D()&&(Dt.style.maxWidth=On,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),On&&Kt&&!D()&&(Kt.style.maxWidth=On,Kt.style.marginLeft="auto",Kt.style.marginRight="auto"),On&&pt&&!D()&&(pt.style.maxWidth=On,pt.style.marginLeft="auto",pt.style.marginRight="auto"),(kc=r.attachments)!=null&&kc.enabled&&Te&&pt){wt=ta.fromConfig(r.attachments),wt.setPreviewsContainer(pt),Te.addEventListener("change",h=>{let b=h.target;wt==null||wt.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,p=zm(l);pe.appendChild(p)}(()=>{var b,S;let l=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},p=H=>{switch(H){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Qe;case"footer-top":return Kt;case"composer":return Dt;case"footer-bottom":return bn;default:return null}},h=(H,q)=>{var F;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")we.insertBefore(q,we.firstChild);else if(H==="header-right")we.appendChild(q);else{let B=we.querySelector(".persona-flex-col");B?(F=B.parentNode)==null||F.insertBefore(q,B.nextSibling):we.appendChild(q)}break;case"body-top":{let B=ke.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(q):ke.insertBefore(q,ke.firstChild);break}case"body-bottom":ke.appendChild(q);break;case"footer-top":Kt.replaceWith(q);break;case"footer-bottom":bn.replaceWith(q);break;default:break}};for(let[H,q]of Object.entries(l))if(q)try{let F=q({config:r,defaultContent:()=>p(H)});F&&h(H,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,F)}})();let Jr=l=>{var q,F;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 H=h.getAttribute("data-bubble-type");if(H==="reasoning")ys.has(S)?ys.delete(S):ys.add(S),mm(S,b);else if(H==="tool")vs.has(S)?vs.delete(S):vs.add(S),gm(S,b,r);else if(H==="approval"){let B=r.approval!==!1?r.approval:void 0,ie=((q=B==null?void 0:B.detailsDisplay)!=null?q:"collapsed")==="expanded",le=(F=Ci.get(S))!=null?F:ie;Ci.set(S,!le),ym(S,b,r)}kr.delete(S)};Qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Jr(l))}),Qe.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Jr(l))});let Nr=new Map,Yr=null,Zr="idle",Co={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ao=(l,p)=>{let{icon:h,label:b}=Co[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=Ae(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},eo=()=>{Qe.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var H;let h=p.closest("[data-actions-for]"),b=(H=h==null?void 0:h.getAttribute("data-actions-for"))!=null?H:null;Ao(p,b&&b===Yr?Zr:"idle")})};Qe.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 H=h.getAttribute("data-action");if(H==="copy"){let B=_.getMessages().find(ie=>ie.id===S);if(B&&Y.onCopy){let ie=B.content||"";navigator.clipboard.writeText(ie).then(()=>{h.classList.add("persona-message-action-success");let le=Ae("check",14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let J=Ae("copy",14,"currentColor",2);J&&(h.innerHTML="",h.appendChild(J))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),Y.onCopy(B)}}else if(H==="read-aloud")_.toggleReadAloud(S);else if(H==="upvote"||H==="downvote"){let B=((q=Nr.get(S))!=null?q:null)===H,ie=H==="upvote"?"thumbs-up":"thumbs-down";if(B){Nr.delete(S),h.classList.remove("persona-message-action-active");let le=Ae(ie,14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le))}else{let le=H==="upvote"?"downvote":"upvote",J=b.querySelector(`[data-action="${le}"]`);if(J){J.classList.remove("persona-message-action-active");let Ue=Ae(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(J.innerHTML="",J.appendChild(Ue))}Nr.set(S,H),h.classList.add("persona-message-action-active");let ve=Ae(ie,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=_.getMessages().find(et=>et.id===S);Ce&&Y.onFeedback&&Y.onFeedback({type:H,messageId:Ce.id,message:Ce})}}}),Qe.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 H=h.getAttribute("data-approval-action");if(!H)return;let q=H==="approve"?"approved":"denied",B=_.getMessages().find(le=>le.id===S);if(!(B!=null&&B.approval))return;let ie=b.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(J=>{J.disabled=!0,J.style.opacity="0.5",J.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,q):_.resolveApproval(B.approval,q)});let St=null,jn=null,Vn={artifacts:[],selectedId:null},Wn=!1,Mt={current:null};Qe.addEventListener("click",l=>{var J,ve,_e,Ce,et;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((_e=(ve=(J=r.features)==null?void 0:J.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:_e.call(ve,{type:"download",artifactId:b}))===!0)return;let H=_.getArtifactById(b),q=H==null?void 0:H.markdown,F=(H==null?void 0:H.title)||"artifact";if(!q){let Ue=h.closest("[data-open-artifact]"),ht=Ue==null?void 0:Ue.closest("[data-message-id]"),lt=ht==null?void 0:ht.getAttribute("data-message-id");if(lt){let Pe=_.getMessages().find(ze=>ze.id===lt);if(Pe!=null&&Pe.rawContent)try{let ze=JSON.parse(Pe.rawContent);q=(Ce=ze==null?void 0:ze.props)==null?void 0:Ce.markdown,F=((et=ze==null?void 0:ze.props)==null?void 0:et.title)||F}catch{}}}if(!q)return;let B=new Blob([q],{type:"text/markdown"}),ie=URL.createObjectURL(B),le=document.createElement("a");le.href=ie,le.download=`${F}.md`,le.click(),URL.revokeObjectURL(ie)}),Qe.addEventListener("click",l=>{var H,q,F;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((F=(q=(H=r.features)==null?void 0:H.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:F.call(q,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Wn=!1,_.selectArtifact(b),Qn())}),Qe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let rr=X.composerOverlay,or=(l,p,h)=>{var F,B,ie,le;let b=p.trim();if(!b||!Mt.current)return;let S=(F=l.getAttribute("data-tool-call-id"))!=null?F:"",H=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:(B=h.values)!=null?B:h.source==="multi"?b.split(", "):[b],isFreeText:H,source:h.source},bubbles:!0,composed:!0})),ds(rr,S);let q=Mt.current.getMessages().find(J=>{var ve;return((ve=J.toolCall)==null?void 0:ve.id)===S});(ie=q==null?void 0:q.agentMetadata)!=null&&ie.awaitingLocalTool?Mt.current.resolveAskUserQuestion(q,(le=h.structured)!=null?le:b):Mt.current.sendMessage(b)},Kn=l=>{var S;let p=Mt.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",b=p.getMessages().find(H=>{var q;return((q=H.toolCall)==null?void 0:q.id)===h});b&&p.persistAskUserQuestionProgress(b,{answers:Oa(l,b),currentIndex:cr(l)})},to=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Fr=l=>{var S,H,q;if(((H=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:H.groupedAutoAdvance)===!1)return;let p=cr(l),h=cs(l);if(p>=h-1)return;let b=(q=Mt.current)==null?void 0:q.getMessages().find(F=>{var B;return((B=F.toolCall)==null?void 0:B.id)===l.getAttribute("data-tool-call-id")});b&&(qa(l,b,r,p+1),Kn(l))};rr.addEventListener("click",l=>{var H,q,F,B,ie,le,J,ve,_e,Ce,et,Ue,ht,lt;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 Be=(H=b.getAttribute("data-tool-call-id"))!=null?H:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ds(rr,Be);let Pe=(q=Mt.current)==null?void 0:q.getMessages().find(ze=>{var Ge;return((Ge=ze.toolCall)==null?void 0:Ge.id)===Be});(F=Pe==null?void 0:Pe.agentMetadata)!=null&&F.awaitingLocalTool&&((B=Mt.current)==null||B.markAskUserQuestionResolved(Pe),(ie=Mt.current)==null||ie.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(S==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let Pe=b.getAttribute("data-multi-select")==="true",ze=ho(b);if(ze&&Pe){let Ge=No(b)[cr(b)],xt=new Set(Array.isArray(Ge)?Ge:[]);xt.has(Be)?xt.delete(Be):xt.add(Be),bo(b,Array.from(xt)),Kn(b);return}if(ze){bo(b,Be),Kn(b),Fr(b);return}if(Pe){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let xt=b.querySelector('[data-ask-user-action="submit-multi"]');xt&&(xt.disabled=qi(b).length===0);return}or(b,Be,{source:"pick",values:[Be]});return}if(S==="submit-multi"){let Be=qi(b);if(Be.length===0)return;or(b,Be.join(", "),{source:"multi",values:Be});return}if(S==="open-free-text"){let Be=b.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let Pe=Be.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(S==="focus-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(S==="submit-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]'),Pe=(le=Be==null?void 0:Be.value)!=null?le:"";if(!Pe.trim())return;if(ho(b)){bo(b,Pe.trim()),Kn(b),Fr(b);return}or(b,Pe,{source:"free-text"});return}if(S==="next"||S==="back"){if(!Mt.current)return;let Be=(J=b.getAttribute("data-tool-call-id"))!=null?J:"",Pe=Mt.current.getMessages().find(Ne=>{var He;return((He=Ne.toolCall)==null?void 0:He.id)===Be});if(!Pe)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ge=(_e=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?_e:"";if(Ge){let Ne=No(b)[cr(b)];(typeof Ne!="string"||Ne!==Ge)&&bo(b,Ge)}let xt=S==="next"?1:-1,P=cr(b)+xt;qa(b,Pe,r,P),Kn(b);return}if(S==="submit-all"){if(!Mt.current)return;let Be=(Ce=b.getAttribute("data-tool-call-id"))!=null?Ce:"",Pe=Mt.current.getMessages().find(Ne=>{var He;return((He=Ne.toolCall)==null?void 0:He.id)===Be});if(!Pe)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ge=(Ue=(et=ze==null?void 0:ze.value)==null?void 0:et.trim())!=null?Ue:"";Ge&&bo(b,Ge);let xt=Oa(b,Pe);Mt.current.persistAskUserQuestionProgress(Pe,{answers:xt,currentIndex:cr(b)});let P=to(xt);or(b,P||"(submitted)",{source:"submit-all",structured:xt});return}if(S==="skip"){if(!Mt.current)return;let Be=(ht=b.getAttribute("data-tool-call-id"))!=null?ht:"",Pe=Mt.current.getMessages().find(He=>{var me;return((me=He.toolCall)==null?void 0:me.id)===Be});if(!Pe)return;let ze=ho(b),Ge=cr(b),xt=cs(b),P=Ge>=xt-1;if(!ze){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ds(rr,Be),(lt=Pe.agentMetadata)!=null&&lt.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Pe),Mt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}bo(b,"");let Ne=b.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),P){let He=Oa(b,Pe),me=to(He);or(b,me||"(skipped)",{source:"submit-all",structured:He});return}qa(b,Pe,r,Ge+1),Kn(b);return}}),rr.addEventListener("keydown",l=>{var H;if(l.key!=="Enter")return;let h=l.target;if(!((H=h.matches)!=null&&H.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(ho(b)){bo(b,S.trim()),Kn(b),Fr(b);return}or(b,S,{source:"free-text"})}});let no=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=rr.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),H=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];H&&(l.preventDefault(),H.click())};document.addEventListener("keydown",no);let Gn=null,Ot=null,Rn=null,sr=null,ro=()=>{};function _r(){sr==null||sr(),sr=null}let oo=()=>{var q;if(!Gn||!Ot)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){Ot.style.removeProperty("position"),Ot.style.removeProperty("left"),Ot.style.removeProperty("top"),Ot.style.removeProperty("bottom"),Ot.style.removeProperty("width"),Ot.style.removeProperty("z-index");return}let b=Gn.firstElementChild;if(!b||b===Ot)return;let S=10;Ot.style.position="absolute",Ot.style.top="0",Ot.style.bottom="0",Ot.style.width=`${S}px`,Ot.style.zIndex="5";let H=b.offsetWidth-S/2;Ot.style.left=`${Math.max(0,H)}px`},Sr=()=>{},Qn=()=>{var h,b,S,H,q;if(!St||!dr(r))return;Ti(n,r),Ei(n,r),Sr();let l=(H=(S=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?H:520,p=fe.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),St.update(Vn),Wn?(St.setMobileOpen(!1),St.element.classList.add("persona-hidden"),(q=St.backdrop)==null||q.classList.add("persona-hidden")):Vn.artifacts.length>0&&(St.element.classList.remove("persona-hidden"),St.setMobileOpen(!0)),ro()};if(dr(r)){fe.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(pe),St=Em(r,{onSelect:h=>{var b;return(b=Mt.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Wn=!0,Qn()}}),St.element.classList.add("persona-hidden"),Gn=p,p.appendChild(l),p.appendChild(St.element),St.backdrop&&fe.appendChild(St.backdrop),fe.appendChild(p),ro=()=>{var b,S,H,q;if(!Gn||!St)return;if(!(((H=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:H.resizable)===!0)){Rn==null||Rn(),Rn=null,_r(),Ot&&(Ot.remove(),Ot=null),St.element.style.removeProperty("width"),St.element.style.removeProperty("maxWidth");return}if(!Ot){let F=y("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 B=n.ownerDocument,ie=(q=B.defaultView)!=null?q:window,le=J=>{var ht,lt;if(!St||J.button!==0||n.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;J.preventDefault(),_r();let ve=J.clientX,_e=St.element.getBoundingClientRect().width,Ce=(lt=(ht=r.features)==null?void 0:ht.artifacts)==null?void 0:lt.layout,et=Be=>{let Pe=Gn.getBoundingClientRect().width,ze=n.classList.contains("persona-artifact-appearance-seamless"),Ge=ze?0:Im(Gn,ie),xt=ze?0:F.getBoundingClientRect().width||6,P=_e-(Be.clientX-ve),Ne=Pm(P,Pe,Ge,xt,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);St.element.style.width=`${Ne}px`,St.element.style.maxWidth="none",oo()},Ue=()=>{B.removeEventListener("pointermove",et),B.removeEventListener("pointerup",Ue),B.removeEventListener("pointercancel",Ue),sr=null;try{F.releasePointerCapture(J.pointerId)}catch{}};sr=Ue,B.addEventListener("pointermove",et),B.addEventListener("pointerup",Ue),B.addEventListener("pointercancel",Ue);try{F.setPointerCapture(J.pointerId)}catch{}};F.addEventListener("pointerdown",le),Ot=F,Gn.insertBefore(F,St.element),Rn=()=>{F.removeEventListener("pointerdown",le)}}if(Ot){let F=Vn.artifacts.length>0&&!Wn;Ot.classList.toggle("persona-hidden",!F),oo()}},Sr=()=>{var ie,le,J,ve,_e,Ce,et,Ue,ht,lt,Be,Pe,ze,Ge;if(!E||!St||((le=(ie=r.launcher)==null?void 0:ie.sidebarMode)!=null?le:!1)||Cn(r)&&yr(r).reveal==="emerge")return;let b=(J=n.ownerDocument.defaultView)!=null?J:window,S=(_e=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?_e:!0,H=(et=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?et:640;if(S&&b.innerWidth<=H||!Lm(r,E))return;let q=(lt=(ht=(Ue=r.launcher)==null?void 0:Ue.width)!=null?ht:r.launcherWidth)!=null?lt:Qr,F=(Ge=(ze=(Pe=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:Pe.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!Wn?(fe.style.width=F,fe.style.maxWidth=F):(fe.style.width=q,fe.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(jn=new ResizeObserver(()=>{Qn()}),jn.observe(fe))}else fe.appendChild(pe),D()&&Ke&&(X.peekBanner&&Ke.appendChild(X.peekBanner),Ke.appendChild(Fe));n.appendChild(Ee),Ke&&n.appendChild(Ke);let be=()=>{var Ne,He,me,zt,qt,Xt,Ct,Gt,Yn,on,Xe,Wt,dn,lr,Zn,ko,Lo,rs,os,Jt,Io,mo,go,Vr,Po,fr,Ye,gn;if(D()){fe.style.width="100%",fe.style.maxWidth="100%";let Vt=(He=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?He:{},jt=Ee.dataset.state==="expanded",bt=(me=Vt.expandedSize)!=null?me:"anchored";if(!(jt&&bt!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let Tt=(qt=(zt=r.theme)==null?void 0:zt.components)==null?void 0:qt.panel,En=ri(r),Bn=(Dn,Wo)=>{var Fs;return Dn==null||Dn===""?Wo:(Fs=fs(En,Dn))!=null?Fs:Dn},Br="1px solid var(--persona-border)",vn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Hn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Bn(Tt==null?void 0:Tt.border,Br),pe.style.borderRadius=Bn(Tt==null?void 0:Tt.borderRadius,Hn),pe.style.boxShadow=Bn(Tt==null?void 0:Tt.shadow,vn),pe.style.overflow="hidden";return}let l=Cn(r),p=(Ct=(Xt=r.launcher)==null?void 0:Xt.sidebarMode)!=null?Ct:!1,h=l||p||((Yn=(Gt=r.launcher)==null?void 0:Gt.fullHeight)!=null?Yn:!1),b=((on=r.launcher)==null?void 0:on.enabled)===!1,S=(Wt=(Xe=r.theme)==null?void 0:Xe.components)==null?void 0:Wt.panel,H=ri(r),q=(Vt,jt)=>{var bt;return Vt==null||Vt===""?jt:(bt=fs(H,Vt))!=null?bt:Vt},F=(dn=n.ownerDocument.defaultView)!=null?dn:window,B=(Zn=(lr=r.launcher)==null?void 0:lr.mobileFullscreen)!=null?Zn:!0,ie=(Lo=(ko=r.launcher)==null?void 0:ko.mobileBreakpoint)!=null?Lo:640,le=F.innerWidth<=ie,J=B&&le&&E,ve=(os=(rs=r.launcher)==null?void 0:rs.position)!=null?os:"bottom-left",_e=ve==="bottom-left"||ve==="top-left",Ce=(Io=(Jt=r.launcher)==null?void 0:Jt.zIndex)!=null?Io:Ln,et=p||J?"none":"1px solid var(--persona-border)",Ue=J?"none":p?_e?"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&&!J&&(Ue="none",et="none");let ht=p||J?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=q(S==null?void 0:S.border,et),Be=q(S==null?void 0:S.shadow,Ue),Pe=q(S==null?void 0:S.borderRadius,ht),ze=ke.scrollTop;n.style.cssText="",Ee.style.cssText="",fe.style.cssText="",pe.style.cssText="",ke.style.cssText="",Fe.style.cssText="";let Ge=()=>{var jt;if(ze<=0)return;((jt=ke.ownerDocument.defaultView)!=null?jt:window).requestAnimationFrame(()=>{if(ke.scrollTop===ze)return;let bt=ke.scrollHeight-ke.clientHeight;bt<=0||(ke.scrollTop=Math.min(ze,bt))})};if(J){Ee.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"),Ee.style.cssText=`
33
33
  position: fixed !important;
34
34
  inset: 0 !important;
35
35
  width: 100% !important;
@@ -54,7 +54,7 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
54
54
  padding: 0 !important;
55
55
  box-shadow: none !important;
56
56
  border-radius: 0 !important;
57
- `,ue.style.cssText=`
57
+ `,pe.style.cssText=`
58
58
  display: flex !important;
59
59
  flex-direction: column !important;
60
60
  flex: 1 1 0% !important;
@@ -65,11 +65,11 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
65
65
  overflow: hidden !important;
66
66
  border-radius: 0 !important;
67
67
  border: none !important;
68
- `,Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.overflowY="auto",Oe.style.flexShrink="0",I=!0,Qe();return}let bt=(go=(mo=r==null?void 0:r.launcher)==null?void 0:mo.width)!=null?go:r==null?void 0:r.launcherWidth,L=bt!=null?bt:Qr;if(!p&&!l)y&&h?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=L,fe.style.maxWidth=L);else if(l)if(vr(r).reveal==="emerge"){let $t=vr(r).width;fe.style.width=$t,fe.style.maxWidth=$t}else fe.style.width="100%",fe.style.maxWidth="100%";if(Tr(),fe.style.boxShadow=We,fe.style.borderRadius=Le,ue.style.border=lt,ue.style.borderRadius=Le,l&&!Y&&(A==null?void 0:A.border)===void 0&&(ue.style.border="none",vr(r).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.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"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",fe.style.overflow="hidden",ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.overflowY="auto",Oe.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&&((jr=xr[ve])!=null?jr:xr["bottom-right"]).split(" ").forEach($t=>Me.classList.add($t)),p){let Ut=(hr=(Io=r.launcher)==null?void 0:Io.sidebarWidth)!=null?hr:"420px";Me.style.cssText=`
68
+ `,ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",Fe.style.flexShrink="0",k=!0,Ge();return}let xt=(go=(mo=r==null?void 0:r.launcher)==null?void 0:mo.width)!=null?go:r==null?void 0:r.launcherWidth,P=xt!=null?xt:Qr;if(!p&&!l)b&&h?(fe.style.width="100%",fe.style.maxWidth="100%"):(fe.style.width=P,fe.style.maxWidth=P);else if(l)if(yr(r).reveal==="emerge"){let jt=yr(r).width;fe.style.width=jt,fe.style.maxWidth=jt}else fe.style.width="100%",fe.style.maxWidth="100%";if(Sr(),fe.style.boxShadow=Be,fe.style.borderRadius=Pe,pe.style.border=lt,pe.style.borderRadius=Pe,l&&!J&&(S==null?void 0:S.border)===void 0&&(pe.style.border="none",yr(r).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),h&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",b&&(n.style.width="100%"),Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.height="100%",b&&(Ee.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",fe.style.overflow="hidden",pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",Fe.style.flexShrink="0"),Ee.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&&((Vr=vr[ve])!=null?Vr:vr["bottom-right"]).split(" ").forEach(jt=>Ee.classList.add(jt)),p){let Vt=(fr=(Po=r.launcher)==null?void 0:Po.sidebarWidth)!=null?fr:"420px";Ee.style.cssText=`
69
69
  position: fixed !important;
70
70
  top: 0 !important;
71
71
  bottom: 0 !important;
72
- width: ${Ut} !important;
72
+ width: ${Vt} !important;
73
73
  height: 100vh !important;
74
74
  max-height: 100vh !important;
75
75
  margin: 0 !important;
@@ -77,7 +77,7 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
77
77
  display: flex !important;
78
78
  flex-direction: column !important;
79
79
  z-index: ${Ce} !important;
80
- ${De?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
80
+ ${_e?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
81
81
  `,fe.style.cssText=`
82
82
  position: relative !important;
83
83
  display: flex !important;
@@ -89,9 +89,9 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
89
89
  min-height: 0 !important;
90
90
  margin: 0 !important;
91
91
  padding: 0 !important;
92
- box-shadow: ${We} !important;
93
- border-radius: ${Le} !important;
94
- `,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),ue.style.cssText=`
92
+ box-shadow: ${Be} !important;
93
+ border-radius: ${Pe} !important;
94
+ `,fe.style.setProperty("width","100%","important"),fe.style.setProperty("max-width","100%","important"),pe.style.cssText=`
95
95
  display: flex !important;
96
96
  flex-direction: column !important;
97
97
  flex: 1 1 0% !important;
@@ -100,37 +100,37 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
100
100
  min-height: 0 !important;
101
101
  max-height: 100% !important;
102
102
  overflow: hidden !important;
103
- border-radius: ${Le} !important;
103
+ border-radius: ${Pe} !important;
104
104
  border: ${lt} !important;
105
- `,Oe.style.cssText=`
105
+ `,Fe.style.cssText=`
106
106
  flex-shrink: 0 !important;
107
107
  border-top: none !important;
108
108
  padding: 8px 16px 12px 16px !important;
109
- `}if(!y&&!l){let Ut="max-height: -moz-available !important; max-height: stretch !important;",$t=p?"":"padding-top: 1.25em !important;",ft=p?"":`z-index: ${(mn=(tt=r.launcher)==null?void 0:tt.zIndex)!=null?mn:Mn} !important;`;Me.style.cssText+=Ut+$t+ft}Qe()};ye(),ys(n,r),Ci(n,r),Ai(n,r);let pt=[];pt.push(()=>{document.removeEventListener("keydown",no)});let en=null,pn=null;pt.push(()=>{en==null||en(),en=null,pn==null||pn(),pn=null}),zn&&pt.push(()=>{zn==null||zn.disconnect(),zn=null}),pt.push(()=>{In==null||In(),In=null,_r(),Nt&&(Nt.remove(),Nt=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),He&&pt.push(()=>{Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),j==null||j.destroy(),j=null,ge==null||ge.destroy(),ge=null,G=null});let Mr=null,Ss=()=>{Mr&&(Mr(),Mr=null),r.colorScheme==="auto"&&(Mr=_u(()=>{ys(n,r)}))};Ss(),pt.push(()=>{Mr&&(Mr(),Mr=null)});let $r=(Ec=r.features)==null?void 0:Ec.streamAnimation;if($r!=null&&$r.type&&$r.type!=="none"){let l=oa($r.type,$r.plugins);l&&(Zi(l,n),pt.push(()=>Yu(n)))}let So=gm(Ke),Er=null,O,jo=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?iu(p):null;h?So.render(h,O,Pe,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(H=>H.role==="user")?So.render([],O,Pe,p):So.render(r.suggestionChips,O,Pe,p,r.suggestionChipsConfig)},kr=!1,Lr=qu(),Ur=new Map,Pr=new Map,mr=new Map,Ko=0,ya=is()!==null,Qn=ri(),Xn=0,gr=null,fr=!1,To=!1,qr=0,Cn=null,Ir=null,Go=!1,Mo=!1,Qo=null,ba=4,Xo=24,va=80,Jo=new Map,ht={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ts=(Lc=(kc=r.voiceRecognition)==null?void 0:kc.autoResume)!=null?Lc:!1,sr=l=>{s.emit("voice:state",{active:ht.active,source:l,timestamp:Date.now()})},_n=()=>{m(l=>({...l,voiceState:{active:ht.active,timestamp:Date.now(),manuallyDeactivated:ht.manuallyDeactivated}}))},xa=()=>{var y,A;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=vl(d.voiceState),p=!!l.active,h=Number((A=l.timestamp)!=null?A:0);ht.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<sv&&setTimeout(()=>{var H,U;ht.active||(ht.manuallyDeactivated=!1,((U=(H=r.voiceRecognition)==null?void 0:H.provider)==null?void 0:U.type)==="runtype"?O.toggleVoice().then(()=>{ht.active=O.isVoiceActive(),sr("restore"),O.isVoiceActive()&&ns()}):Pa("restore"))},1e3)},wa=()=>O?Nm(O.getMessages()).filter(l=>!l.__skipPersist):[];function Yo(l){if(!(i!=null&&i.save))return;let h={messages:l?Nm(l):O?wa():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.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 zr=null,Ms=()=>Me.querySelector("#persona-scroll-container")||Ee,so=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),fr=!1},Es=()=>{gr!==null&&(cancelAnimationFrame(gr),gr=null),To=!1,so()},ks=()=>{qr>0?(Ln.textContent=String(qr),Ln.style.display="",dt.setAttribute("aria-label",`${on()||"Jump to latest"} (${qr} new)`)):(Ln.textContent="",Ln.style.display="none",dt.setAttribute("aria-label",on()||"Jump to latest"))},Ls=()=>{qr!==0&&(qr=0,ks())},Ps=()=>nt()==="follow"?!Qn.isFollowing():!$o(Ee,Xo),$n=()=>{if(!Dt()||ae){dt.parentNode&&dt.remove(),dt.style.display="none";return}dt.parentNode!==ue&&ue.appendChild(dt),Fn();let p=Xr(Ee)>0&&Ps();p||Ls(),dt.style.display=p?"":"none"},Zo=()=>{Qn.pause()&&(Es(),$n())},Wr=()=>{Qn.resume(),Ls(),$n()},Rr=(l=!1)=>{nt()==="follow"&&Qn.isFollowing()&&(!l&&!kr||(gr!==null&&(cancelAnimationFrame(gr),gr=null),To=!0,gr=requestAnimationFrame(()=>{gr=null,To=!1,Qn.isFollowing()&&Ca(Ms(),l?220:140)})))},Is=(l,p,h,y=()=>!0)=>{let A=l.scrollTop,H=p(),U=H-A;so();let F=performance.now();fr=!0;let R=de=>1-Math.pow(1-de,3),ce=de=>{if(!y()){so();return}let Y=p();Y!==H&&(H=Y,U=H-A);let ve=de-F,De=Math.min(ve/h,1),Ce=R(De),rt=A+U*Ce;l.scrollTop=rt,Xn=l.scrollTop,De<1?zr=requestAnimationFrame(ce):(l.scrollTop=H,Xn=l.scrollTop,zr=null,fr=!1)};zr=requestAnimationFrame(ce)},Ca=(l,p=500)=>{let h=Xr(l)-l.scrollTop;if(Math.abs(h)<1){Xn=l.scrollTop;return}if(Math.abs(h)>=va){so(),fr=!0,l.scrollTop=Xr(l),Xn=l.scrollTop,fr=!1;return}Is(l,()=>Xr(l),p,()=>Qn.isFollowing())},Ws=()=>{let l=Ms();fr=!0,l.scrollTop=Xr(l),Xn=l.scrollTop,fr=!1,$n()},Rs=l=>{sn.style.height=`${Math.max(0,Math.round(l))}px`,Cn&&(Cn.spacerHeight=Math.max(0,l))},Eo=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),so(),Cn=null,sn.style.height="0px"},Aa=l=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var ce;Ir=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Ee.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,A=h;for(;A&&A!==Ee;)y+=A.offsetTop,A=A.offsetParent;let H=(ce=Cn==null?void 0:Cn.spacerHeight)!=null?ce:0,U=Ee.scrollHeight-H,{targetScrollTop:F,spacerHeight:R}=Gu({anchorOffsetTop:y,topOffset:Bt(),viewportHeight:Ee.clientHeight,contentHeight:U});Cn={initialSpacerHeight:R,contentHeightAtAnchor:U,spacerHeight:R},Rs(R),Is(Ee,()=>F,220)})},Sa=()=>{if(nt()==="follow"){if(!Qn.isFollowing()||$o(Ee,1))return;Rr(!kr);return}if(Cn&&Cn.initialSpacerHeight>0){let l=Ee.scrollHeight-Cn.spacerHeight,p=Qu({initialSpacerHeight:Cn.initialSpacerHeight,contentHeightAtAnchor:Cn.contentHeightAtAnchor,currentContentHeight:l});p!==Cn.spacerHeight&&Rs(p)}$n()},Ta=l=>{let p=nt();p==="follow"?(Wr(),Rr(!0)):p==="anchor-top"&&Aa(l)},Ma=l=>{let p=new Map;l.forEach(h=>{let y=Jo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!Mo&&nt()!=="anchor-top"&&Ps()&&(qr+=1,ks(),$n())),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}))}),Jo.clear(),p.forEach((h,y)=>{Jo.set(y,h)})},Ea=(l,p,h)=>{var lt,We,Le,ze,Qe,bt;let y=document.createElement("div"),H=(()=>{var Be;let L=o.find(Re=>Re.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),U=(L,Be)=>Be==null?!1:typeof Be=="string"?(L.textContent=Be,!0):(L.appendChild(Be),!0),F=new Set,R=new Set,ce=o.some(L=>L.renderAskUserQuestion),de=[],Y=[],ve=r.enableComponentStreaming!==!1,De=o.some(L=>L.renderApproval)&&r.approval!==!1,Ce=[];if(p.forEach(L=>{var Ye,Pt,cn,cr,Yn,ko,Lo,os,ss,Gt,Po,mo,go,jr,Io,hr;F.add(L.id);let Be=ce&&Do(L),Re=De&&L.variant==="approval"&&!!L.approval,me=!Be&&L.role==="assistant"&&!L.variant&&ve&&Rm(L);if(!Re&&mr.has(L.id)){let tt=l.querySelector(`#wrapper-${L.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),mr.delete(L.id)}if(!me&&Pr.has(L.id)){let tt=l.querySelector(`#wrapper-${L.id}`);tt==null||tt.removeAttribute("data-preserve-runtime"),Pr.delete(L.id)}let _t=Do(L)?`:${(Ye=L.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(Pt=L.agentMetadata)!=null&&Pt.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ft=Uu(L,Ko)+_t,Kt=Be||Re||me?null:zu(Lr,L.id,Ft);if(Kt){y.appendChild(Kt.cloneNode(!0)),Do(L)&&((cn=L.toolCall)!=null&&cn.id)&&((cr=L.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Yn=L.agentMetadata)!=null&&Yn.askUserQuestionAnswered)&&(R.add(L.toolCall.id),Oa(L,r,J.composerOverlay));return}let xt=null,zt=o.find(tt=>!!(L.variant==="reasoning"&&tt.renderReasoning||L.variant==="tool"&&tt.renderToolCall||!L.variant&&tt.renderMessage)),Jn=(ko=r.layout)==null?void 0:ko.messages;if(Do(L)&&((Lo=L.agentMetadata)==null?void 0:Lo.askUserQuestionAnswered)===!0){Ur.delete(L.id);let tt=l.querySelector(`#wrapper-${L.id}`);tt==null||tt.removeAttribute("data-preserve-runtime");return}if($i(L)&&((ss=(os=r.features)==null?void 0:os.suggestReplies)==null?void 0:ss.enabled)!==!1)return;if(Do(L)&&((Po=(Gt=r.features)==null?void 0:Gt.askUserQuestion)==null?void 0:Po.enabled)!==!1){let tt=o.find(mn=>typeof mn.renderAskUserQuestion=="function");if(tt&&Tt.current){let mn=Ur.get(L.id),Ut=mn!==Ft,$t=null;if(Ut){let{payload:At,complete:An}=cs(L),Rn=L.id,Br=()=>{var yn;return(yn=Tt.current)==null?void 0:yn.getMessages().find(Hn=>Hn.id===Rn)};$t=tt.renderAskUserQuestion({message:L,payload:At,complete:An,resolve:yn=>{var Bn;let Hn=Br();Hn&&((Bn=Tt.current)==null||Bn.resolveAskUserQuestion(Hn,yn))},dismiss:()=>{var Hn,Bn,Wo;let yn=Br();(Hn=yn==null?void 0:yn.agentMetadata)!=null&&Hn.awaitingLocalTool&&((Bn=Tt.current)==null||Bn.markAskUserQuestionResolved(yn),(Wo=Tt.current)==null||Wo.resolveAskUserQuestion(yn,"(dismissed)"))},config:r})}let ft=mn!=null;if(Ut&&$t===null&&!ft){((mo=L.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((go=L.agentMetadata)!=null&&go.askUserQuestionAnswered)&&(R.add(L.toolCall.id),Oa(L,r,J.composerOverlay));return}let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${L.id}`,Qt.setAttribute("data-wrapper-id",L.id),Qt.setAttribute("data-ask-plugin-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),y.appendChild(Qt),de.push({messageId:L.id,fingerprint:Ft,bubble:$t});return}else{((jr=L.agentMetadata)==null?void 0:jr.awaitingLocalTool)===!0&&!((Io=L.agentMetadata)!=null&&Io.askUserQuestionAnswered)&&(R.add(L.toolCall.id),Oa(L,r,J.composerOverlay));return}}else if(Re){let tt=o.find(ft=>typeof ft.renderApproval=="function"),Ut=mr.get(L.id)!==Ft,$t=null;if(Ut&&(tt!=null&&tt.renderApproval)){let ft=L.id,Qt=(At,An)=>{var Br,yn,Hn;let Rn=(Br=Tt.current)==null?void 0:Br.getMessages().find(Bn=>Bn.id===ft);Rn!=null&&Rn.approval&&(Rn.approval.toolType==="webmcp"?(yn=Tt.current)==null||yn.resolveWebMcpApproval(Rn.id,At):(Hn=Tt.current)==null||Hn.resolveApproval(Rn.approval,At,An))};$t=tt.renderApproval({message:L,defaultRenderer:()=>xi(L,r),config:r,approve:At=>Qt("approved",At),deny:At=>Qt("denied",At)})}if(Ut&&$t===null){let ft=l.querySelector(`#wrapper-${L.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),mr.delete(L.id),xt=xi(L,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${L.id}`,ft.setAttribute("data-wrapper-id",L.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),Ce.push({messageId:L.id,fingerprint:Ft,bubble:$t});return}}else if(zt)if(L.variant==="reasoning"&&L.reasoning&&zt.renderReasoning){if(!Ve)return;xt=zt.renderReasoning({message:L,defaultRenderer:()=>ll(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&zt.renderToolCall){if(!be)return;xt=zt.renderToolCall({message:L,defaultRenderer:()=>cl(L,r),config:r})}else zt.renderMessage&&(xt=zt.renderMessage({message:L,defaultRenderer:()=>{let tt=il(L,h,Jn,r.messageActions,Z,{loadingIndicatorRenderer:H,widgetConfig:r});return L.role!=="user"&&ml(tt,L,r,O),tt},config:r}));if(!xt&&me){let tt=Hm(L);if(tt){let mn=Pr.get(L.id),Ut=mn!==Ft,$t=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(Ut){let Qt=Im(tt,{config:r,message:L,transform:h});if(Qt)if($t){let At=document.createElement("div");if(At.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(" "),At.id=`bubble-${L.id}`,At.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let An=document.createElement("div");An.className="persona-mb-3 persona-text-sm persona-leading-relaxed",An.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),At.appendChild(An)}At.appendChild(Qt),ft=At}else{let At=document.createElement("div");if(At.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",At.id=`bubble-${L.id}`,At.setAttribute("data-message-id",L.id),At.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let An=document.createElement("div");An.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",An.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),At.appendChild(An)}At.appendChild(Qt),ft=At}}if(ft||mn!=null){let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id=`wrapper-${L.id}`,Qt.setAttribute("data-wrapper-id",L.id),Qt.setAttribute("data-component-directive-stub","true"),Qt.setAttribute("data-preserve-runtime","true"),$t||Qt.classList.add("persona-w-full"),y.appendChild(Qt),Y.push({messageId:L.id,fingerprint:Ft,bubble:ft});return}}}if(!xt)if(L.variant==="reasoning"&&L.reasoning){if(!Ve)return;xt=ll(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!be)return;xt=cl(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;xt=xi(L,r)}else{let tt=(hr=r.layout)==null?void 0:hr.messages;tt!=null&&tt.renderUserMessage&&L.role==="user"?xt=tt.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):tt!=null&&tt.renderAssistantMessage&&L.role==="assistant"?xt=tt.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):xt=il(L,h,tt,r.messageActions,Z,{loadingIndicatorRenderer:H,widgetConfig:r}),L.role!=="user"&&xt&&ml(xt,L,r,O)}let nn=document.createElement("div");nn.className="persona-flex",nn.id=`wrapper-${L.id}`,nn.setAttribute("data-wrapper-id",L.id),L.role==="user"&&nn.classList.add("persona-justify-end"),(xt==null?void 0:xt.getAttribute("data-persona-component-directive"))==="true"&&nn.classList.add("persona-w-full"),nn.appendChild(xt),Vu(Lr,L.id,Ft,nn),y.appendChild(nn)}),J.composerOverlay&&J.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Re=Be.getAttribute("data-persona-ask-sheet-for");Re&&!R.has(Re)&&ps(J.composerOverlay,Re)}),(We=(lt=r.features)==null?void 0:lt.toolCallDisplay)!=null&&We.grouped){let L=[],Be=[];p.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&be){Be.push(Re);return}Be.length>1&&L.push(Be),Be=[]}),Be.length>1&&L.push(Be),L.forEach((Re,me)=>{var Ye,Pt;let _t=Re.map(cn=>Array.from(y.children).find(cr=>cr instanceof HTMLElement&&cr.getAttribute("data-wrapper-id")===cn.id)).filter(cn=>!!cn);if(_t.length<2)return;let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id=`wrapper-tool-group-${me}-${Re[0].id}`,Ft.setAttribute("data-wrapper-id",`tool-group-${me}-${Re[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 xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Re.length} tools`,Jn=(Pt=(Ye=r.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:Pt.call(Ye,{messages:Re,toolCalls:Re.map(cn=>cn.toolCall).filter(cn=>!!cn),defaultSummary:zt,config:r});U(xt,Jn)||(xt.textContent=zt);let nn=document.createElement("div");nn.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(xt,nn),Ft.appendChild(Kt),_t[0].before(Ft),_t.forEach((cn,cr)=>{let Yn=document.createElement("div");Yn.className="persona-tool-group-item persona-relative",Yn.setAttribute("data-persona-tool-group-item","true"),cr<_t.length-1&&Yn.setAttribute("data-persona-tool-group-connector","true"),Yn.appendChild(cn),nn.appendChild(Yn)})})}ju(Lr,F);let rt=p.some(L=>L.role==="assistant"&&L.streaming),qe=p[p.length-1],gt=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(kr&&p.some(L=>L.role==="user")&&!rt&&!gt){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:pa},Be=o.find(me=>me.renderLoadingIndicator),Re=null;if(Be!=null&&Be.renderLoadingIndicator&&(Re=Be.renderLoadingIndicator(L)),Re===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Re=r.loadingIndicator.render(L)),Re===null&&(Re=pa()),Re){let me=document.createElement("div"),_t=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;me.className=_t?["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(Re);let Ft=document.createElement("div");Ft.className="persona-flex",Ft.id="wrapper-typing-indicator",Ft.setAttribute("data-wrapper-id","typing-indicator"),Ft.appendChild(me),y.appendChild(Ft)}}if(!kr&&p.length>0){let L=p[p.length-1],Be={config:r,lastMessage:L,messageCount:p.length},Re=o.find(_t=>_t.renderIdleIndicator),me=null;if(Re!=null&&Re.renderIdleIndicator&&(me=Re.renderIdleIndicator(Be)),me===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(me=r.loadingIndicator.renderIdle(Be)),me){let _t=document.createElement("div"),Ft=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;_t.className=Ft?["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(" "),_t.setAttribute("data-idle-indicator","true"),_t.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(_t),y.appendChild(Kt)}}if(ti(l,y),de.length>0)for(let{messageId:L,fingerprint:Be,bubble:Re}of de){let me=l.querySelector(`#wrapper-${L}`);me&&Re!==null&&(me.replaceChildren(Re),me.setAttribute("data-bubble-fp",Be),Ur.set(L,Be))}if(Ur.size>0)for(let L of Ur.keys())F.has(L)||Ur.delete(L);if(Y.length>0)for(let{messageId:L,fingerprint:Be,bubble:Re}of Y){let me=l.querySelector(`#wrapper-${L}`);me&&Re!==null&&(me.replaceChildren(Re),me.setAttribute("data-bubble-fp",Be),Pr.set(L,Be))}if(Pr.size>0)for(let L of Pr.keys())F.has(L)||Pr.delete(L);if(Ce.length>0)for(let{messageId:L,fingerprint:Be,bubble:Re}of Ce){let me=l.querySelector(`#wrapper-${L}`);me&&Re!==null&&(me.replaceChildren(Re),me.setAttribute("data-bubble-fp",Be),mr.set(L,Be))}if(mr.size>0)for(let L of mr.keys())F.has(L)||mr.delete(L)},ao=(l,p,h)=>{Ea(l,p,h),eo()},io=null,ka=()=>{var h;if(io)return;let l=y=>{let A=y.composedPath();A.includes(Me)||Xe&&A.includes(Xe)||S(!1,"user")};io=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Hs=()=>{var p;if(!io)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",io,!0),io=null};pt.push(()=>Hs());let lo=null,La=()=>{var h;if(lo)return;let l=y=>{y.key==="Escape"&&(y.isComposing||S(!1,"user"))};lo=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Bs=()=>{var p;if(!lo)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",lo,!0),lo=null};pt.push(()=>Bs());let co=!1,Ds=new Set,es=()=>{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)},Ue=()=>{var gt,lt,We,Le;if(!B())return;let l=J.peekBanner,p=J.peekTextNode;if(!l||!p)return;if(T){l.classList.remove("persona-pill-peek--visible");return}let h=(gt=O==null?void 0:O.getMessages())!=null?gt:[],y;for(let ze=h.length-1;ze>=0;ze--){let Qe=h[ze];if(Qe.role==="assistant"&&Qe.content){y=Qe;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let A=y.content,H=!!y.streaming,U=es(),F=ai(U),R=F.type!=="none"?oa(F.type,U==null?void 0:U.plugins):null,ce=((lt=R==null?void 0:R.isAnimating)==null?void 0:lt.call(R,y))===!0,de=R!==null&&(H||ce);de&&R&&!Ds.has(R.name)&&(Zi(R,n),Ds.add(R.name));let Y=de&&(R!=null&&R.containerClass)?R.containerClass:null,ve=(We=p.dataset.personaPeekStreamClass)!=null?We:null;ve&&ve!==Y&&(p.classList.remove(ve),delete p.dataset.personaPeekStreamClass),Y&&ve!==Y&&(p.classList.add(Y),p.dataset.personaPeekStreamClass=Y),de?(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 De=de?ii(A,F.buffer,R,y,H):A;if(de&&F.placeholder==="skeleton"&&H&&(!De||!De.trim())){let ze=document.createElement("div"),Qe=aa();Qe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Qe),ti(p,ze)}else{let ze=Math.max(0,De.length-100),Qe=De.length>100?De.slice(-100):De,bt=fo(Qe);if(!de||!R){let L=De.length>100?`\u2026${Qe}`:Qe;p.textContent!==L&&(p.textContent=L)}else{let L=bt;(R.wrap==="char"||R.wrap==="word")&&(L=sa(bt,R.wrap,`peek-${y.id}`,{skipTags:R.skipTags,startIndex:ze}));let Be=document.createElement("div");if(Be.innerHTML=L,R.useCaret&&Qe.length>0){let Re=li(),me=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),_t=me[me.length-1];_t!=null&&_t.parentNode?_t.parentNode.insertBefore(Re,_t.nextSibling):Be.appendChild(Re)}ti(p,Be),(Le=R.onAfterRender)==null||Le.call(R,{container:p,bubble:l,messageId:y.id,message:y,speed:F.speed,duration:F.duration})}}let qe=kr||co;l.classList.toggle("persona-pill-peek--visible",qe)};if(B()){let l=J.peekBanner;if(l){let y=A=>{A.preventDefault(),A.stopPropagation(),S(!0,"user")};l.addEventListener("pointerdown",y),pt.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{co||(co=!0,Ue())},h=()=>{co&&(co=!1,Ue())};fe.addEventListener("pointerenter",p),fe.addEventListener("pointerleave",h),pt.push(()=>{fe.removeEventListener("pointerenter",p),fe.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),pt.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let w=l=>{var ve,De,Ce,rt,qe,gt,lt,We;let p=(De=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?De:{},h=(Ce=p.expandedSize)!=null?Ce:"anchored",y=(rt=p.bottomOffset)!=null?rt:"16px",A=p.collapsedMaxWidth,H=(qe=p.expandedMaxWidth)!=null?qe:"880px",U=(gt=p.expandedTopOffset)!=null?gt:"5vh",F=(lt=p.modalMaxWidth)!=null?lt:"880px",R=(We=p.modalMaxHeight)!=null?We:"min(90vh, 800px)",ce="calc(100vw - 32px)",de="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="",Xe){let Le=Xe.style;Le.bottom=y,Le.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=ce,Y.maxHeight=R,Y.height=R;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${y} + ${de})`,Y.top=U,Y.width=H,Y.maxWidth=ce}},_=()=>{var R,ce,de,Y,ve,De,Ce,rt;if(!D())return;if(B()){let gt=(de=((ce=(R=r.launcher)==null?void 0:R.composerBar)!=null?ce:{}).expandedSize)!=null?de:"anchored",lt=T?"expanded":"collapsed";Me.dataset.state=lt,Me.dataset.expandedSize=gt,Xe&&(Xe.dataset.state=lt,Xe.dataset.expandedSize=gt),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),w(T),ue.style.display=T?"flex":"none",ye(),T?(ka(),La()):(Hs(),Bs()),Ue();return}let l=wn(r),p=(Y=n.ownerDocument.defaultView)!=null?Y:window,h=(De=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?De:640,y=(rt=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?rt:!0,A=p.innerWidth<=h,H=y&&A&&E,U=vr(r).reveal;T?(Me.style.removeProperty("display"),Me.style.display=l?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),tn?tn.element.style.display="none":un&&(un.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!H?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.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"),fe.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"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),tn?tn.element.style.display=l?"none":"":un&&(un.style.display=l?"none":""))},S=(l,p="user")=>{var H,U;if(!D()||T===l)return;let h=T;T=l,_();let y=(()=>{var Ce,rt,qe,gt,lt,We,Le,ze,Qe,bt;let F=(rt=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?rt:!1,R=(qe=n.ownerDocument.defaultView)!=null?qe:window,ce=(lt=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?lt:!0,de=(Le=(We=r.launcher)==null?void 0:We.mobileBreakpoint)!=null?Le:640,Y=R.innerWidth<=de,ve=wn(r)&&ce&&Y,De=B()&&((bt=(Qe=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Qe.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return F||ce&&Y&&E||ve||De})();if(T&&y){if(!en){let F=n.getRootNode(),R=F instanceof ShadowRoot?F.host:n.closest(".persona-host");R&&(en=el(R,(U=(H=r.launcher)==null?void 0:H.zIndex)!=null?U:Mn))}pn||(pn=tl(n.ownerDocument))}else T||(en==null||en(),en=null,pn==null||pn(),pn=null);T&&(Ns(),nt()==="follow"?Rr(!0):Ws());let A={open:T,source:p,timestamp:Date.now()};T&&!h?s.emit("widget:opened",A):!T&&h&&s.emit("widget:closed",A),s.emit("widget:state",{open:T,launcherEnabled:E,voiceActive:ht.active,streaming:O.isStreaming()})},X=l=>{kn(l?"stop":"send"),V&&(V.disabled=l),So.buttons.forEach(p=>{p.disabled=l}),Oe.dataset.personaComposerStreaming=l?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},ie=()=>{ht.active||Pe&&Pe.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ie(),200)});let Q=()=>{var h,y,A,H,U,F,R,ce,de,Y,ve;wr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",$.textContent=(H=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",Pe.placeholder=(F=(U=r.copy)==null?void 0:U.inputPlaceholder)!=null?F:"How can I help...";let l=Ee.querySelector("[data-persona-intro-card]");if(l){let De=((R=r.copy)==null?void 0:R.showWelcomeCard)!==!1;l.style.display=De?"":"none",De?(Ee.classList.remove("persona-gap-3"),Ee.classList.add("persona-gap-6")):(Ee.classList.remove("persona-gap-6"),Ee.classList.add("persona-gap-3"))}!((de=(ce=r.sendButton)==null?void 0:ce.useIcon)!=null&&de)&&!(O!=null&&O.isStreaming())&&(je.textContent=(ve=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ve:"Send"),Pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Pe.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=>{m(p=>({...p,sessionId:l}))}});let Te=null,_e=()=>{Te==null&&(Te=setInterval(()=>{let l=Je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Te),Te=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=$a(p-y))})},100))};O=new Ya(r,{onMessagesChanged(l){var y;ao(Je,l,ke),_e(),jo(l),Rr(!kr),Ma(l);let p=[...l].reverse().find(A=>A.role==="user");l.length===0&&Eo(),!Go||Mo?(Go=!0,Qo=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Qo&&(Qo=p.id,Ta(p.id));let h=ht.lastUserMessageId;p&&p.id!==h&&(ht.lastUserMessageId=p.id,s.emit("user:message",p)),ht.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Yo(l),Ue()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};it(dn,(A=>{var H,U,F,R;return A==="idle"?(H=p.idleText)!=null?H:Tn.idle:A==="connecting"?(U=p.connectingText)!=null?U:Tn.connecting:A==="connected"?(F=p.connectedText)!=null?F:Tn.connected:A==="error"?(R=p.errorText)!=null?R:Tn.error:Tn[A]})(l),p,l)},onStreamingChanged(l){kr=l,X(l),O&&ao(Je,O.getMessages(),ke),l||Rr(!0),Ue()},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":Vr(),ns();break;case"processing":Vr(),Ym();break;case"speaking":Vr(),Zm();break;default:l==="idle"&&O.isBargeInActive()?(Vr(),ns(),V==null||V.setAttribute("aria-label","End voice session")):(ht.active=!1,Vr(),sr("system"),_n());break}},onArtifactsState(l){Vn=l,Gn(),Yo()}}),Tt.current=O;let st=null;if(O.onReadAloudChange((l,p)=>{var A;Yr=l,Zr=p,eo();let h=l!=null?l:st;l&&(st=l);let y=h&&(A=O.getMessages().find(H=>H.id===h))!=null?A:null;s.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(st=null)}),Go=!0,((Ic=(Pc=r.voiceRecognition)==null?void 0:Pc.provider)==null?void 0:Ic.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)}),(ge||r.onSSEEvent)&&O.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),pe==null||pe.processEvent(l,p),ge==null||ge.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=vl(l.metadata),M.syncFromMetadata()),(p=l.messages)!=null&&p.length){Mo=!0;try{O.hydrateMessages(l.messages)}finally{Mo=!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 et=()=>{var p,h,y;!B()||T||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||S(!0,"auto")},Ht=l=>{var A;if(l.preventDefault(),O.isStreaming()){O.cancel(),pe==null||pe.reset(),j==null||j.update();return}let p=Pe.value.trim(),h=(A=vt==null?void 0:vt.hasAttachments())!=null?A:!1;if(!p&&!h)return;et();let y;h&&(y=[],y.push(...vt.getContentParts()),p&&y.push(Vi(p))),Pe.value="",Pe.style.height="auto",Mt(),O.sendMessage(p,{contentParts:y}),h&&vt.clearAttachments()},qt=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},an={...ni},Ct=!1,Mt=()=>{an={...ni}},hn=()=>O.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Wn=l=>{if(!Pe)return;Ct=!0,Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),Ct=!1;let p=Pe.value.length;Pe.setSelectionRange(p,p)},xn=()=>{Ct||Mt()},Yt=l=>{if(Pe){if(qt()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Pe.selectionStart===0&&Pe.selectionEnd===0,h=$u({direction:l.key==="ArrowUp"?"up":"down",history:hn(),currentValue:Pe.value,atStart:p,state:an});if(an=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Wn(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(O.isStreaming()){l.preventDefault();return}Mt(),l.preventDefault(),je.click()}}},ar=l=>{l.key!=="Escape"||l.isComposing||O.isStreaming()&&l.composedPath().includes(ue)&&(O.cancel(),pe==null||pe.reset(),j==null||j.update(),Mt(),l.preventDefault(),l.stopImmediatePropagation())},Ml=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let p=iv(l.clipboardData);p.length!==0&&(l.preventDefault(),await vt.handleFiles(p))},ir=null,Hr=!1,ts=null,mt=null,El=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Pa=(l="user")=>{var H,U,F,R,ce,de,Y;if(Hr||O.isStreaming())return;let p=El();if(!p)return;ir=new p;let y=(U=((H=r.voiceRecognition)!=null?H:{}).pauseDuration)!=null?U:2e3;ir.continuous=!0,ir.interimResults=!0,ir.lang="en-US";let A=Pe.value;ir.onresult=ve=>{let De="",Ce="";for(let qe=0;qe<ve.results.length;qe++){let gt=ve.results[qe],lt=gt[0].transcript;gt.isFinal?De+=lt+" ":Ce=lt}let rt=A+De+Ce;Pe.value=rt,ts&&clearTimeout(ts),(De||Ce)&&(ts=window.setTimeout(()=>{let qe=Pe.value.trim();qe&&ir&&Hr&&(po(),Pe.value="",Pe.style.height="auto",O.sendMessage(qe,{viaVoice:!0}))},y))},ir.onerror=ve=>{ve.error!=="no-speech"&&po()},ir.onend=()=>{if(Hr){let ve=Pe.value.trim();ve&&ve!==A.trim()&&(Pe.value="",Pe.style.height="auto",O.sendMessage(ve,{viaVoice:!0})),po()}};try{if(ir.start(),Hr=!0,ht.active=!0,l!=="system"&&(ht.manuallyDeactivated=!1),sr(l),_n(),V){let ve=(F=r.voiceRecognition)!=null?F:{};mt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(R=ve.iconName)!=null?R:"mic",iconSize:parseFloat((Y=(de=ve.iconSize)!=null?de:(ce=r.sendButton)==null?void 0:ce.size)!=null?Y:"40")||24};let De=ve.recordingBackgroundColor,Ce=ve.recordingIconColor,rt=ve.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=De!=null?De:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let qe=V.querySelector("svg");qe&&qe.setAttribute("stroke",Ce)}rt&&(V.style.borderColor=rt),V.setAttribute("aria-label","Stop voice recognition")}}catch{po("system")}},po=(l="user")=>{if(Hr){if(Hr=!1,ts&&(clearTimeout(ts),ts=null),ir){try{ir.stop()}catch{}ir=null}if(ht.active=!1,sr(l),_n(),V){if(V.classList.remove("persona-voice-recording"),mt){V.style.backgroundColor=mt.backgroundColor,V.style.color=mt.color,V.style.borderColor=mt.borderColor;let p=V.querySelector("svg");p&&p.setAttribute("stroke",mt.color||"currentColor"),mt=null}V.setAttribute("aria-label","Start voice recognition")}}},Jm=(l,p)=>{var lt,We,Le,ze,Qe,bt,L,Be,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((lt=l==null?void 0:l.provider)==null?void 0:lt.type)==="runtype",A=((We=l==null?void 0:l.provider)==null?void 0:We.type)==="custom";if(!(h||y||A))return null;let U=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 R=(Le=l==null?void 0:l.iconName)!=null?Le:"mic",ce=(ze=p==null?void 0:p.size)!=null?ze:"40px",de=(Qe=l==null?void 0:l.iconSize)!=null?Qe:ce,Y=parseFloat(de)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:p==null?void 0:p.backgroundColor,De=(L=l==null?void 0:l.iconColor)!=null?L:p==null?void 0:p.textColor;F.style.width=de,F.style.height=de,F.style.minWidth=de,F.style.minHeight=de,F.style.fontSize="18px",F.style.lineHeight="1",De?F.style.color=De:F.style.color="var(--persona-text, #111827)";let rt=Ae(R,Y,De||"currentColor",1.5);rt?F.appendChild(rt):F.textContent="\u{1F3A4}",ve?F.style.backgroundColor=ve: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),U.appendChild(F);let qe=(Be=l==null?void 0:l.tooltipText)!=null?Be:"Start voice recognition";if(((Re=l==null?void 0:l.showTooltip)!=null?Re:!1)&&qe){let me=b("div","persona-send-button-tooltip");me.textContent=qe,U.appendChild(me)}return{micButton:F,micButtonWrapper:U}},Mi=()=>{var p,h,y,A,H;if(!V||mt)return;let l=(p=r.voiceRecognition)!=null?p:{};mt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((H=(A=l.iconSize)!=null?A:(y=r.sendButton)==null?void 0:y.size)!=null?H:"40")||24}},Ei=(l,p)=>{var H,U,F,R,ce;if(!V)return;let h=V.querySelector("svg");h&&h.remove();let y=(ce=mt==null?void 0:mt.iconSize)!=null?ce:parseFloat((R=(F=(H=r.voiceRecognition)==null?void 0:H.iconSize)!=null?F:(U=r.sendButton)==null?void 0:U.size)!=null?R:"40")||24,A=Ae(l,y,p,1.5);A&&V.appendChild(A)},Ia=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ns=()=>{var A;if(!V)return;Mi();let l=(A=r.voiceRecognition)!=null?A:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(Ia(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let H=V.querySelector("svg");H&&H.setAttribute("stroke",h)}y&&(V.style.borderColor=y),V.setAttribute("aria-label","Stop voice recognition")},Ym=()=>{var F,R,ce,de,Y,ve,De,Ce;if(!V)return;Mi();let l=(F=r.voiceRecognition)!=null?F:{},p=O.getVoiceInterruptionMode(),h=(R=l.processingIconName)!=null?R:"loader",y=(de=(ce=l.processingIconColor)!=null?ce:mt==null?void 0:mt.color)!=null?de:"",A=(ve=(Y=l.processingBackgroundColor)!=null?Y:mt==null?void 0:mt.backgroundColor)!=null?ve:"",H=(Ce=(De=l.processingBorderColor)!=null?De:mt==null?void 0:mt.borderColor)!=null?Ce:"";Ia(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=A,V.style.borderColor=H;let U=y||"currentColor";V.style.color=U,Ei(h,U),V.setAttribute("aria-label","Processing voice input"),p==="none"&&(V.style.cursor="default")},Zm=()=>{var ce,de,Y,ve,De,Ce,rt,qe,gt,lt,We,Le;if(!V)return;Mi();let l=(ce=r.voiceRecognition)!=null?ce:{},p=O.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(de=l.speakingIconName)!=null?de:h,A=(Ce=l.speakingIconColor)!=null?Ce:p==="barge-in"?(ve=(Y=l.recordingIconColor)!=null?Y:mt==null?void 0:mt.color)!=null?ve:"":(De=mt==null?void 0:mt.color)!=null?De:"",H=(gt=l.speakingBackgroundColor)!=null?gt:p==="barge-in"?(rt=l.recordingBackgroundColor)!=null?rt:"var(--persona-voice-recording-bg, #ef4444)":(qe=mt==null?void 0:mt.backgroundColor)!=null?qe:"",U=(Le=l.speakingBorderColor)!=null?Le:p==="barge-in"?(lt=l.recordingBorderColor)!=null?lt:"":(We=mt==null?void 0:mt.borderColor)!=null?We:"";Ia(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=H,V.style.borderColor=U;let F=A||"currentColor";V.style.color=F,Ei(y,F);let R=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",R),p==="none"&&(V.style.cursor="default"),p==="barge-in"&&V.classList.add("persona-voice-recording")},Vr=()=>{var l,p,h;V&&(Ia(),mt&&(V.style.backgroundColor=(l=mt.backgroundColor)!=null?l:"",V.style.color=(p=mt.color)!=null?p:"",V.style.borderColor=(h=mt.borderColor)!=null?h:"",Ei(mt.iconName,mt.color||"currentColor"),mt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},Wa=()=>{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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,_n(),sr("user"),Vr()});return}O.toggleVoice().then(()=>{ht.active=O.isVoiceActive(),ht.manuallyDeactivated=!O.isVoiceActive(),_n(),sr("user"),O.isVoiceActive()?ns():Vr()});return}if(Hr){let h=Pe.value.trim();ht.manuallyDeactivated=!0,_n(),po("user"),h&&(Pe.value="",Pe.style.height="auto",O.sendMessage(h))}else ht.manuallyDeactivated=!1,_n(),Pa("user")};qn=Wa,V&&(V.addEventListener("click",Wa),pt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Vr()):po("system"),V&&V.removeEventListener("click",Wa)}));let eg=s.on("assistant:complete",()=>{Ts&&(ht.active||ht.manuallyDeactivated||Ts==="assistant"&&!ht.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!ht.active&&!ht.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?O.toggleVoice().then(()=>{ht.active=O.isVoiceActive(),sr("auto"),O.isVoiceActive()&&ns()}):Pa("auto"))},600))});pt.push(eg);let tg=s.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});pt.push(tg);let kl=()=>{S(!T,"user")},tn=null,un=null;if(E&&!B()){let{instance:l,element:p}=ol({config:r,plugins:o,onToggle:kl});tn=l,l||(un=p)}tn?n.appendChild(tn.element):un&&n.appendChild(un),_(),jo(),Q(),X(O.isStreaming()),nt()==="follow"?Rr(!0):Ws(),xa(),N&&(!E||B()?setTimeout(()=>ie(),0):T&&setTimeout(()=>ie(),200));let Ns=()=>{var R,ce,de,Y,ve,De,Ce,rt,qe,gt,lt,We,Le,ze,Qe,bt,L,Be,Re,me,_t,Ft;if(B()){Fn(),_();return}let l=wn(r),p=(ce=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?ce:!1,h=l||p||((Y=(de=r.launcher)==null?void 0:de.fullHeight)!=null?Y:!1),y=(ve=n.ownerDocument.defaultView)!=null?ve:window,A=(Ce=(De=r.launcher)==null?void 0:De.mobileFullscreen)!=null?Ce:!0,H=(qe=(rt=r.launcher)==null?void 0:rt.mobileBreakpoint)!=null?qe:640,U=y.innerWidth<=H,F=A&&U&&E;try{if(F){ye(),ys(n,r);return}if(I&&(I=!1,ye(),ys(n,r)),!E&&!l){fe.style.height="",fe.style.width="";return}if(!p&&!l){let Kt=(lt=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?lt:r==null?void 0:r.launcherWidth,xt=Kt!=null?Kt:Qr;fe.style.width=xt,fe.style.maxWidth=xt}if(Tr(),!h){let Kt=y.innerHeight,xt=64,zt=(Le=(We=r.launcher)==null?void 0:We.heightOffset)!=null?Le:0,Jn=Math.max(200,Kt-xt),nn=Math.min(640,Jn),Ye=Math.max(200,nn-zt);fe.style.height=`${Ye}px`}}finally{if(Fn(),_(),T&&E){let xt=((ze=n.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?bt:640),zt=(Be=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?Be:!1,Jn=(me=(Re=r.launcher)==null?void 0:Re.mobileFullscreen)!=null?me:!0,nn=wn(r)&&Jn&&xt,Ye=zt||Jn&&xt&&E||nn;if(Ye&&!pn){let Pt=n.getRootNode(),cn=Pt instanceof ShadowRoot?Pt.host:n.closest(".persona-host");cn&&!en&&(en=el(cn,(Ft=(_t=r.launcher)==null?void 0:_t.zIndex)!=null?Ft:Mn)),pn=tl(n.ownerDocument)}else Ye||(en==null||en(),en=null,pn==null||pn(),pn=null)}}};Ns();let Ll=(Wc=n.ownerDocument.defaultView)!=null?Wc:window;if(Ll.addEventListener("resize",Ns),pt.push(()=>Ll.removeEventListener("resize",Ns)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Fn()});l.observe(Oe),pt.push(()=>l.disconnect())}Xn=Ee.scrollTop;let Pl=Xr(Ee),ng=()=>{let l=Ee.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:Ee.ownerDocument.getSelection()},ki=()=>Ku(ng(),Ee),Il=()=>{let l=Ee.scrollTop,p=Xr(Ee),h=p<Pl;if(Pl=p,nt()!=="follow"){Xn=l,$n();return}let{action:y,nextLastScrollTop:A}=oi({following:Qn.isFollowing(),currentScrollTop:l,lastScrollTop:Xn,nearBottom:$o(Ee,Xo),userScrollThreshold:ba,isAutoScrolling:fr||To||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=A,y==="resume"){ki()||Wr();return}y==="pause"&&Zo()};if(Ee.addEventListener("scroll",Il,{passive:!0}),pt.push(()=>Ee.removeEventListener("scroll",Il)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Sa()});l.observe(Je),l.observe(Ee),pt.push(()=>l.disconnect())}let Wl=()=>{nt()==="follow"&&Qn.isFollowing()&&ki()&&Zo()},Rl=Ee.ownerDocument;Rl.addEventListener("selectionchange",Wl),pt.push(()=>{Rl.removeEventListener("selectionchange",Wl)});let Hl=l=>{if(nt()!=="follow")return;let p=si({following:Qn.isFollowing(),deltaY:l.deltaY,nearBottom:$o(Ee,Xo),resumeWhenNearBottom:!0});p==="pause"?Zo():p==="resume"&&!ki()&&Wr()};Ee.addEventListener("wheel",Hl,{passive:!0}),pt.push(()=>Ee.removeEventListener("wheel",Hl)),dt.addEventListener("click",()=>{Eo(),Ee.scrollTop=Ee.scrollHeight,Xn=Ee.scrollTop,Wr(),Rr(!0),$n()}),pt.push(()=>dt.remove()),pt.push(()=>{Es(),Eo()});let Bl=()=>{K&&(Er&&(K.removeEventListener("click",Er),Er=null),D()?(K.style.display="",Er=()=>{S(!1,"user")},K.addEventListener("click",Er)):K.style.display="none")};Bl(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{O.clearMessages(),Lr.clear(),Wr(),ps(J.composerOverlay);try{localStorage.removeItem(Cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Cs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Cs)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={},M.syncFromMetadata(),ge==null||ge.clear(),pe==null||pe.reset(),j==null||j.update()})})(),Wt&&Wt.addEventListener("submit",Ht),Pe==null||Pe.addEventListener("keydown",Yt),Pe==null||Pe.addEventListener("input",xn),Pe==null||Pe.addEventListener("paste",Ml);let Dl=(Rc=n.ownerDocument)!=null?Rc:document;Dl.addEventListener("keydown",ar,!0);let Nl="persona-attachment-drop-active",Fs=0,Li=()=>{Fs=0,ue.classList.remove(Nl)},rs=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&vt!==null},Fl=l=>{!Si(l.dataTransfer)||!rs()||(Fs++,Fs===1&&ue.classList.add(Nl))},Ol=l=>{!Si(l.dataTransfer)||!rs()||(Fs--,Fs<=0&&Li())},_l=l=>{!Si(l.dataTransfer)||!rs()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},$l=l=>{var h;if(!Si(l.dataTransfer)||!rs())return;l.preventDefault(),l.stopPropagation(),Li();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&vt.handleFiles(p)},uo=!0;ue.addEventListener("dragenter",Fl,uo),ue.addEventListener("dragleave",Ol,uo),n.addEventListener("dragover",_l,uo),n.addEventListener("drop",$l,uo);let Ra=n.ownerDocument,Ul=l=>{rs()&&l.preventDefault()},ql=l=>{rs()&&l.preventDefault()};Ra.addEventListener("dragover",Ul),Ra.addEventListener("drop",ql),pt.push(()=>{Wt&&Wt.removeEventListener("submit",Ht),Pe==null||Pe.removeEventListener("keydown",Yt),Pe==null||Pe.removeEventListener("input",xn),Pe==null||Pe.removeEventListener("paste",Ml),Dl.removeEventListener("keydown",ar,!0)}),pt.push(()=>{ue.removeEventListener("dragenter",Fl,uo),ue.removeEventListener("dragleave",Ol,uo),n.removeEventListener("dragover",_l,uo),n.removeEventListener("drop",$l,uo),Ra.removeEventListener("dragover",Ul),Ra.removeEventListener("drop",ql),Li()}),pt.push(()=>{O.cancel()}),tn?pt.push(()=>{tn==null||tn.destroy()}):un&&pt.push(()=>{un==null||un.remove()});let ln={update(l){var An,Rn,Br,yn,Hn,Bn,Wo,Os,_c,$c,Uc,qc,zc,Vc,jc,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,Vd,jd,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,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp;let p=r.toolCall,h=r.messageActions,y=(An=r.layout)==null?void 0:An.messages,A=r.colorScheme,H=r.loadingIndicator,U=r.iterationDisplay,F=(Rn=r.features)==null?void 0:Rn.showReasoning,R=(Br=r.features)==null?void 0:Br.showToolCalls,ce=(yn=r.features)==null?void 0:yn.toolCallDisplay,de=(Hn=r.features)==null?void 0:Hn.reasoningDisplay;r={...r,...l},ye(),ys(n,r),Ci(n,r),Ai(n,r),Gn(),r.colorScheme!==A&&Ss();let Y=fl.getForInstance(r.plugins);o.length=0,o.push(...Y),E=(Wo=(Bn=r.launcher)==null?void 0:Bn.enabled)!=null?Wo:!0,k=(_c=(Os=r.launcher)==null?void 0:Os.autoExpand)!=null?_c:!1,Ve=(Uc=($c=r.features)==null?void 0:$c.showReasoning)!=null?Uc:!0,be=(zc=(qc=r.features)==null?void 0:qc.showToolCalls)!=null?zc:!0,Fe=(jc=(Vc=r.features)==null?void 0:Vc.scrollToBottom)!=null?jc:{};let ve=nt();Se=(Gc=(Kc=r.features)==null?void 0:Kc.scrollBehavior)!=null?Gc:{},ve!==nt()&&(Eo(),Wr()),Cr(),$n();let De=He;if(He=(Xc=(Qc=r.features)==null?void 0:Qc.showEventStreamToggle)!=null?Xc:!1,He&&!De){if(ge||(G=new ma(oe),ge=new ua(se,G),pe=pe!=null?pe:new ga,G.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),O.setSSEEventCallback((te,Et)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,te,Et),pe==null||pe.processEvent(te,Et),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!yt&&$e){let te=(Yc=(Jc=r.features)==null?void 0:Jc.eventStream)==null?void 0:Yc.classNames,Et="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"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");yt=b("button",Et),yt.style.width="28px",yt.style.height="28px",yt.style.color=Nn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Vt=Ae("activity","18px","currentColor",1.5);Vt&&yt.appendChild(Vt);let ct=J.clearChatButtonWrapper,It=J.closeButtonWrapper,gn=ct||It;gn&&gn.parentNode===$e?$e.insertBefore(yt,gn):$e.appendChild(yt),yt.addEventListener("click",()=>{ae?ur():Nr()})}}else!He&&De&&(ur(),yt&&(yt.remove(),yt=null),ge==null||ge.clear(),G==null||G.destroy(),ge=null,G=null,pe==null||pe.reset(),pe=null);if(((Zc=r.launcher)==null?void 0:Zc.enabled)===!1&&tn&&(tn.destroy(),tn=null),((ed=r.launcher)==null?void 0:ed.enabled)===!1&&un&&(un.remove(),un=null),((td=r.launcher)==null?void 0:td.enabled)!==!1&&!tn&&!un){let{instance:te,element:Et}=ol({config:r,plugins:o,onToggle:kl});tn=te,te||(un=Et),n.appendChild(Et)}tn&&tn.update(r),Ge&&((nd=r.launcher)==null?void 0:nd.title)!==void 0&&(Ge.textContent=r.launcher.title),Ze&&((rd=r.launcher)==null?void 0:rd.subtitle)!==void 0&&(Ze.textContent=r.launcher.subtitle);let Ce=(od=r.layout)==null?void 0:od.header;if((Ce==null?void 0:Ce.layout)!==C&&$e){let te=Ce?pi(r,Ce,{showClose:D(),onClose:()=>S(!1,"user")}):Uo({config:r,showClose:D(),onClose:()=>S(!1,"user")});ot.replaceHeader(te),$e=ot.header.element,he=ot.header.iconHolder,Ge=ot.header.headerTitle,Ze=ot.header.headerSubtitle,K=ot.header.closeButton,C=Ce==null?void 0:Ce.layout}else if(Ce&&(he&&(he.style.display=Ce.showIcon===!1?"none":""),Ge&&(Ge.style.display=Ce.showTitle===!1?"none":""),Ze&&(Ze.style.display=Ce.showSubtitle===!1?"none":""),K&&(K.style.display=Ce.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let te=Ce.showClearChat;if(te!==void 0){J.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Et}=J;Et&&!Et.classList.contains("persona-absolute")&&(te?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let qe=((sd=r.layout)==null?void 0:sd.showHeader)!==!1;$e&&($e.style.display=qe?"":"none");let gt=((ad=r.layout)==null?void 0:ad.showFooter)!==!1;Oe&&(Oe.style.display=gt?"":"none"),Fn(),$n(),E!==W?E?S(k,"auto"):(T=!0,_()):k!==P&&S(k,"auto"),P=k,W=E,Ns(),Bl();let Le=JSON.stringify(l.toolCall)!==JSON.stringify(p),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Qe=JSON.stringify((id=r.layout)==null?void 0:id.messages)!==JSON.stringify(y),bt=((ld=r.loadingIndicator)==null?void 0:ld.render)!==(H==null?void 0:H.render)||((cd=r.loadingIndicator)==null?void 0:cd.renderIdle)!==(H==null?void 0:H.renderIdle)||((dd=r.loadingIndicator)==null?void 0:dd.showBubble)!==(H==null?void 0:H.showBubble),L=r.iterationDisplay!==U,Be=((ud=(pd=r.features)==null?void 0:pd.showReasoning)!=null?ud:!0)!==(F!=null?F:!0)||((gd=(md=r.features)==null?void 0:md.showToolCalls)!=null?gd:!0)!==(R!=null?R:!0)||JSON.stringify((fd=r.features)==null?void 0:fd.toolCallDisplay)!==JSON.stringify(ce)||JSON.stringify((hd=r.features)==null?void 0:hd.reasoningDisplay)!==JSON.stringify(de);(Le||ze||Qe||bt||L||Be)&&O&&(Ko++,ao(Je,O.getMessages(),ke));let me=(yd=r.launcher)!=null?yd:{},_t=(bd=me.headerIconHidden)!=null?bd:!1,Ft=(xd=(vd=r.layout)==null?void 0:vd.header)==null?void 0:xd.showIcon,Kt=_t||Ft===!1,xt=me.headerIconName,zt=(wd=me.headerIconSize)!=null?wd:"48px";if(he){let te=ue.querySelector(".persona-border-b-persona-divider"),Et=te==null?void 0:te.querySelector(".persona-flex-col");if(Kt)he.style.display="none",te&&Et&&!te.contains(Et)&&te.insertBefore(Et,te.firstChild);else{if(he.style.display="",he.style.height=zt,he.style.width=zt,te&&Et&&(te.contains(he)?he.nextSibling!==Et&&(he.remove(),te.insertBefore(he,Et)):te.insertBefore(he,Et)),xt){let ct=parseFloat(zt)||24,It=Ae(xt,ct*.6,"currentColor",1);It?he.replaceChildren(It):he.textContent=(Cd=me.agentIconText)!=null?Cd:"\u{1F4AC}"}else if(me.iconUrl){let ct=he.querySelector("img");if(ct)ct.src=me.iconUrl,ct.style.height=zt,ct.style.width=zt;else{let It=document.createElement("img");It.src=me.iconUrl,It.alt="",It.className="persona-rounded-xl persona-object-cover",It.style.height=zt,It.style.width=zt,he.replaceChildren(It)}}else{let ct=he.querySelector("svg"),It=he.querySelector("img");(ct||It)&&he.replaceChildren(),he.textContent=(Ad=me.agentIconText)!=null?Ad:"\u{1F4AC}"}let Vt=he.querySelector("img");Vt&&(Vt.style.height=zt,Vt.style.width=zt)}}let Jn=(Td=(Sd=r.layout)==null?void 0:Sd.header)==null?void 0:Td.showTitle,nn=(Ed=(Md=r.layout)==null?void 0:Md.header)==null?void 0:Ed.showSubtitle;if(Ge&&(Ge.style.display=Jn===!1?"none":""),Ze&&(Ze.style.display=nn===!1?"none":""),K){((Ld=(kd=r.layout)==null?void 0:kd.header)==null?void 0:Ld.showCloseButton)===!1?K.style.display="none":K.style.display="";let Et=(Pd=me.closeButtonSize)!=null?Pd:"32px",Vt=(Id=me.closeButtonPlacement)!=null?Id:"inline";K.style.height=Et,K.style.width=Et;let{closeButtonWrapper:ct}=J,It=Vt==="top-right",gn=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&It!==gn)if(ct.remove(),It)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(ct);else{let ut=(Rd=(Wd=me.clearChat)==null?void 0:Wd.placement)!=null?Rd:"inline",fn=(Bd=(Hd=me.clearChat)==null?void 0:Hd.enabled)!=null?Bd:!0;ct.className=fn&&ut==="inline"?"":"persona-ml-auto";let Un=ue.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(ct)}if(K.style.color=me.closeButtonColor||Nn.actionIconColor,me.closeButtonBackgroundColor?(K.style.backgroundColor=me.closeButtonBackgroundColor,K.classList.remove("hover:persona-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let ut=me.closeButtonBorderWidth||"0px",fn=me.closeButtonBorderColor||"transparent";K.style.border=`${ut} solid ${fn}`,K.classList.remove("persona-border-none")}else K.style.border="",K.classList.add("persona-border-none");me.closeButtonBorderRadius?(K.style.borderRadius=me.closeButtonBorderRadius,K.classList.remove("persona-rounded-full")):(K.style.borderRadius="",K.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(K.style.paddingLeft=me.closeButtonPaddingX,K.style.paddingRight=me.closeButtonPaddingX):(K.style.paddingLeft="",K.style.paddingRight=""),me.closeButtonPaddingY?(K.style.paddingTop=me.closeButtonPaddingY,K.style.paddingBottom=me.closeButtonPaddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Sn=(Dd=me.closeButtonIconName)!=null?Dd:"x",yr=(Nd=me.closeButtonIconText)!=null?Nd:"\xD7";K.innerHTML="";let Dn=Ae(Sn,"28px","currentColor",1);Dn?K.appendChild(Dn):K.textContent=yr;let Zt=(Fd=me.closeButtonTooltipText)!=null?Fd:"Close chat",Zn=(Od=me.closeButtonShowTooltip)!=null?Od:!0;if(K.setAttribute("aria-label",Zt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Zn&&Zt)){let ut=null,fn=()=>{if(ut||!K)return;let Ro=K.ownerDocument,_s=Ro.body;if(!_s)return;ut=Dr(Ro,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let $s=Dr(Ro,"div");$s.className="persona-clear-chat-tooltip-arrow",ut.appendChild($s);let Ho=K.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(bo),ut.style.left=`${Ho.left+Ho.width/2}px`,ut.style.top=`${Ho.top-8}px`,ut.style.transform="translate(-50%, -100%)",_s.appendChild(ut)},Un=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};ct.addEventListener("mouseenter",fn),ct.addEventListener("mouseleave",Un),K.addEventListener("focus",fn),K.addEventListener("blur",Un),ct._cleanupTooltip=()=>{Un(),ct&&(ct.removeEventListener("mouseenter",fn),ct.removeEventListener("mouseleave",Un)),K&&(K.removeEventListener("focus",fn),K.removeEventListener("blur",Un))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Pt}=J;if(Ye){let te=(_d=me.clearChat)!=null?_d:{},Et=($d=te.enabled)!=null?$d:!0,Vt=(qd=(Ud=r.layout)==null?void 0:Ud.header)==null?void 0:qd.showClearChat,ct=Vt!==void 0?Vt:Et,It=(zd=te.placement)!=null?zd:"inline";if(Pt){Pt.style.display=ct?"":"none";let{closeButtonWrapper:gn}=J;!B()&&gn&&!gn.classList.contains("persona-absolute")&&(ct?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let Sn=It==="top-right",yr=Pt.classList.contains("persona-absolute");if(!B()&&Sn!==yr&&ct){if(Pt.remove(),Sn)Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px",ue.style.position="relative",ue.appendChild(Pt);else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let Zt=ue.querySelector(".persona-border-b-persona-divider"),Zn=J.closeButtonWrapper;Zt&&Zn&&Zn.parentElement===Zt?Zt.insertBefore(Pt,Zn):Zt&&Zt.appendChild(Pt)}let Dn=J.closeButtonWrapper;Dn&&!Dn.classList.contains("persona-absolute")&&(Sn?Dn.classList.add("persona-ml-auto"):Dn.classList.remove("persona-ml-auto"))}}if(ct){if(!B()){let ut=(Vd=te.size)!=null?Vd:"32px";Ye.style.height=ut,Ye.style.width=ut}let gn=(jd=te.iconName)!=null?jd:"refresh-cw",Sn=(Kd=te.iconColor)!=null?Kd:"";Ye.style.color=Sn||Nn.actionIconColor,Ye.innerHTML="";let yr=B()?"14px":"20px",Dn=Ae(gn,yr,"currentColor",2);if(Dn&&Ye.appendChild(Dn),te.backgroundColor?(Ye.style.backgroundColor=te.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let ut=te.borderWidth||"0px",fn=te.borderColor||"transparent";Ye.style.border=`${ut} solid ${fn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");te.borderRadius?(Ye.style.borderRadius=te.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),te.paddingX?(Ye.style.paddingLeft=te.paddingX,Ye.style.paddingRight=te.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),te.paddingY?(Ye.style.paddingTop=te.paddingY,Ye.style.paddingBottom=te.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let Zt=(Gd=te.tooltipText)!=null?Gd:"Clear chat",Zn=(Qd=te.showTooltip)!=null?Qd:!0;if(Ye.setAttribute("aria-label",Zt),Pt&&(Pt._cleanupTooltip&&(Pt._cleanupTooltip(),delete Pt._cleanupTooltip),Zn&&Zt)){let ut=null,fn=()=>{if(ut||!Ye)return;let Ro=Ye.ownerDocument,_s=Ro.body;if(!_s)return;ut=Dr(Ro,"div","persona-clear-chat-tooltip"),ut.textContent=Zt;let $s=Dr(Ro,"div");$s.className="persona-clear-chat-tooltip-arrow",ut.appendChild($s);let Ho=Ye.getBoundingClientRect();ut.style.position="fixed",ut.style.zIndex=String(bo),ut.style.left=`${Ho.left+Ho.width/2}px`,ut.style.top=`${Ho.top-8}px`,ut.style.transform="translate(-50%, -100%)",_s.appendChild(ut)},Un=()=>{ut&&ut.parentNode&&(ut.parentNode.removeChild(ut),ut=null)};Pt.addEventListener("mouseenter",fn),Pt.addEventListener("mouseleave",Un),Ye.addEventListener("focus",fn),Ye.addEventListener("blur",Un),Pt._cleanupTooltip=()=>{Un(),Pt&&(Pt.removeEventListener("mouseenter",fn),Pt.removeEventListener("mouseleave",Un)),Ye&&(Ye.removeEventListener("focus",fn),Ye.removeEventListener("blur",Un))}}}}let cn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[yl],cr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[fa.message,fa.messageAndClick];M=bl({parsers:cn,handlers:cr,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ke=Fm(r,M,re),O.updateConfig(r),ao(Je,O.getMessages(),ke),jo(),Q(),X(O.isStreaming());let Yn=((Xd=r.voiceRecognition)==null?void 0:Xd.enabled)===!0,ko=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Lo=((Yd=(Jd=r.voiceRecognition)==null?void 0:Jd.provider)==null?void 0:Yd.type)==="runtype";if(Yn&&(ko||Lo))if(!V||!Rt){let te=Jm(r.voiceRecognition,r.sendButton);te&&(V=te.micButton,Rt=te.micButtonWrapper,Xt.insertBefore(Rt,bn),V.addEventListener("click",Wa),V.disabled=O.isStreaming())}else{let te=(Zd=r.voiceRecognition)!=null?Zd:{},Et=(ep=r.sendButton)!=null?ep:{},Vt=(tp=te.iconName)!=null?tp:"mic",ct=(np=Et.size)!=null?np:"40px",It=(rp=te.iconSize)!=null?rp:ct,gn=parseFloat(It)||24;V.style.width=It,V.style.height=It,V.style.minWidth=It,V.style.minHeight=It;let Sn=(sp=(op=te.iconColor)!=null?op:Et.textColor)!=null?sp:"currentColor";V.innerHTML="";let yr=Ae(Vt,gn,Sn,2);yr?V.appendChild(yr):V.textContent="\u{1F3A4}";let Dn=(ap=te.backgroundColor)!=null?ap:Et.backgroundColor;Dn?V.style.backgroundColor=Dn:V.style.backgroundColor="",Sn?V.style.color=Sn:V.style.color="var(--persona-text, #111827)",te.borderWidth?(V.style.borderWidth=te.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),te.borderColor?V.style.borderColor=te.borderColor:V.style.borderColor="",te.paddingX?(V.style.paddingLeft=te.paddingX,V.style.paddingRight=te.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),te.paddingY?(V.style.paddingTop=te.paddingY,V.style.paddingBottom=te.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Zt=Rt==null?void 0:Rt.querySelector(".persona-send-button-tooltip"),Zn=(ip=te.tooltipText)!=null?ip:"Start voice recognition";if(((lp=te.showTooltip)!=null?lp:!1)&&Zn)if(Zt)Zt.textContent=Zn,Zt.style.display="";else{let fn=document.createElement("div");fn.className="persona-send-button-tooltip",fn.textContent=Zn,Rt==null||Rt.insertBefore(fn,V)}else Zt&&(Zt.style.display="none");Rt.style.display="",V.disabled=O.isStreaming()}else V&&Rt&&(Rt.style.display="none",((dp=(cp=r.voiceRecognition)==null?void 0:cp.provider)==null?void 0:dp.type)==="runtype"?O.isVoiceActive()&&O.toggleVoice():Hr&&po());if(((pp=r.attachments)==null?void 0:pp.enabled)===!0)if(!we||!le){let te=(up=r.attachments)!=null?up:{},Vt=(gp=((mp=r.sendButton)!=null?mp:{}).size)!=null?gp:"40px";St||(St=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),St.style.display="none",Wt.insertBefore(St,Pe)),Ne||(Ne=document.createElement("input"),Ne.type="file",Ne.accept=((fp=te.allowedTypes)!=null?fp:Gr).join(","),Ne.multiple=((hp=te.maxFiles)!=null?hp:4)>1,Ne.style.display="none",Ne.setAttribute("aria-label","Attach files"),Wt.insertBefore(Ne,Pe)),we=b("div","persona-send-button-wrapper"),le=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(yp=te.buttonTooltipText)!=null?yp:"Attach file");let ct=(bp=te.buttonIconName)!=null?bp:"paperclip",It=Vt,gn=parseFloat(It)||40,Sn=Math.round(gn*.6);le.style.width=It,le.style.height=It,le.style.minWidth=It,le.style.minHeight=It,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let yr=Ae(ct,Sn,"currentColor",1.5);yr?le.appendChild(yr):le.textContent="\u{1F4CE}",le.addEventListener("click",Zn=>{Zn.preventDefault(),Ne==null||Ne.click()}),we.appendChild(le);let Dn=(vp=te.buttonTooltipText)!=null?vp:"Attach file",Zt=b("div","persona-send-button-tooltip");Zt.textContent=Dn,we.appendChild(Zt),jt.append(we),!vt&&Ne&&St&&(vt=ta.fromConfig(te),vt.setPreviewsContainer(St),Ne.addEventListener("change",async()=>{vt&&(Ne!=null&&Ne.files)&&(await vt.handleFileSelect(Ne.files),Ne.value="")})),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(Om(te.dropOverlay))}else{we.style.display="";let te=(xp=r.attachments)!=null?xp:{};Ne&&(Ne.accept=((wp=te.allowedTypes)!=null?wp:Gr).join(","),Ne.multiple=((Cp=te.maxFiles)!=null?Cp:4)>1),vt&&vt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else we&&(we.style.display="none"),vt&&vt.clearAttachments(),(Ap=ue.querySelector(".persona-attachment-drop-overlay"))==null||Ap.remove();let Gt=(Sp=r.sendButton)!=null?Sp:{},Po=(Tp=Gt.useIcon)!=null?Tp:!1,mo=(Mp=Gt.iconText)!=null?Mp:"\u2191",go=Gt.iconName,jr=(Ep=Gt.tooltipText)!=null?Ep:"Send message",Io=(kp=Gt.showTooltip)!=null?kp:!1,hr=(Lp=Gt.size)!=null?Lp:"40px",tt=Gt.backgroundColor,mn=Gt.textColor;if(Po){if(je.style.width=hr,je.style.height=hr,je.style.minWidth=hr,je.style.minHeight=hr,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",mn?je.style.color=mn:je.style.color="var(--persona-button-primary-fg, #ffffff)",go){let te=parseFloat(hr)||24,Et=(mn==null?void 0:mn.trim())||"currentColor",Vt=Ae(go,te,Et,2);Vt?je.appendChild(Vt):je.textContent=mo}else je.textContent=mo;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",tt?(je.style.backgroundColor=tt,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(Ip=(Pp=r.copy)==null?void 0:Pp.sendButtonLabel)!=null?Ip:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.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",tt?(je.style.backgroundColor=tt,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),mn?je.style.color=mn:je.classList.add("persona-text-white");Gt.borderWidth?(je.style.borderWidth=Gt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Gt.borderColor?je.style.borderColor=Gt.borderColor:je.style.borderColor="",Gt.paddingX?(je.style.paddingLeft=Gt.paddingX,je.style.paddingRight=Gt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Gt.paddingY?(je.style.paddingTop=Gt.paddingY,je.style.paddingBottom=Gt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Ut=bn==null?void 0:bn.querySelector(".persona-send-button-tooltip");if(Io&&jr)if(Ut)Ut.textContent=jr,Ut.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=jr,bn==null||bn.insertBefore(te,je)}else Ut&&(Ut.style.display="none");let $t=(Dp=(Wp=r.layout)==null?void 0:Wp.contentMaxWidth)!=null?Dp:B()?(Bp=(Hp=(Rp=r.launcher)==null?void 0:Rp.composerBar)==null?void 0:Hp.contentMaxWidth)!=null?Bp:"720px":void 0;$t?(Je.style.maxWidth=$t,Je.style.marginLeft="auto",Je.style.marginRight="auto",Je.style.width="100%",Wt&&(Wt.style.maxWidth=$t,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Ke&&(Ke.style.maxWidth=$t,Ke.style.marginLeft="auto",Ke.style.marginRight="auto")):(Je.style.maxWidth="",Je.style.marginLeft="",Je.style.marginRight="",Je.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Ke&&(Ke.style.maxWidth="",Ke.style.marginLeft="",Ke.style.marginRight=""));let ft=(Np=r.statusIndicator)!=null?Np:{},Qt=(Fp=ft.visible)!=null?Fp:!0;if(dn.style.display=Qt?"":"none",O){let te=O.getStatus();it(dn,(Vt=>{var ct,It,gn,Sn;return Vt==="idle"?(ct=ft.idleText)!=null?ct:Tn.idle:Vt==="connecting"?(It=ft.connectingText)!=null?It:Tn.connecting:Vt==="connected"?(gn=ft.connectedText)!=null?gn:Tn.connected:Vt==="error"?(Sn=ft.errorText)!=null?Sn:Tn.error:Tn[Vt]})(te),ft,te)}dn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let At=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";dn.classList.add(At)},open(){D()&&S(!0,"api")},close(){D()&&S(!1,"api")},toggle(){D()&&S(!T,"api")},clearChat(){Pn=!1,O.clearMessages(),Lr.clear(),Wr();try{localStorage.removeItem(Cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Cs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Cs)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={},M.syncFromMetadata(),ge==null||ge.clear(),pe==null||pe.reset(),j==null||j.update()},setMessage(l){return!Pe||O.isStreaming()?!1:(!T&&D()&&S(!0,"system"),Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Pe.value.trim();return p?(!T&&D()&&S(!0,"system"),Pe.value="",Pe.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()||(!T&&D()&&S(!0,"system"),ht.manuallyDeactivated=!1,_n(),O.toggleVoice().then(()=>{ht.active=O.isVoiceActive(),sr("user"),O.isVoiceActive()&&ns()})),!0):Hr?!0:El()?(!T&&D()&&S(!0,"system"),ht.manuallyDeactivated=!1,_n(),Pa("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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,_n(),sr("user"),Vr()}),!0):!1:Hr?(ht.manuallyDeactivated=!0,_n(),po("user"),!0):!1},injectMessage(l){return!T&&D()&&S(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!T&&D()&&S(!0,"system");let p=O.injectAssistantMessage(l);return q&&(q=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),p},injectUserMessage(l){return!T&&D()&&S(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!T&&D()&&S(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!T&&D()&&S(!0,"system"),O.injectMessageBatch(l)},injectComponentDirective(l){return!T&&D()&&S(!0,"system"),O.injectComponentDirective(l)},injectTestMessage(l){!T&&D()&&S(!0,"system"),O.injectTestEvent(l)},async connectStream(l,p){return O.connectStream(l,p)},__pushEventStreamEvent(l){ge&&(pe==null||pe.processEvent(l.type,l.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!He||!ge||Nr()},hideEventStream(){ae&&ur()},isEventStreamVisible(){return ae},showArtifacts(){pr(r)&&(Pn=!1,Gn(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){pr(r)&&(Pn=!0,Gn())},upsertArtifact(l){return pr(r)?(Pn=!1,O.upsertArtifact(l)):null},selectArtifact(l){pr(r)&&O.selectArtifact(l)},clearArtifacts(){pr(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 E&&!T&&!B()||!Pe?!1:(Pe.focus(),!0)},async resolveApproval(l,p,h){let A=O.getMessages().find(H=>{var U;return H.variant==="approval"&&((U=H.approval)==null?void 0:U.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){m(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return D()&&T},isVoiceActive(){return ht.active},toggleReadAloud(l){O.toggleReadAloud(l)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(l){return O.getReadAloudState(l)},onReadAloudChange(l){return O.onReadAloudChange(l)},getState(){return{open:D()&&T,launcherEnabled:E,voiceActive:ht.active,streaming:O.isStreaming()}},showCSATFeedback(l){!T&&D()&&S(!0,"system");let p=Je.querySelector(".persona-feedback-container");p&&p.remove();let h=Bm({onSubmit:async(y,A)=>{var H;O.isClientTokenMode()&&await O.submitCSATFeedback(y,A),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&D()&&S(!0,"system");let p=Je.querySelector(".persona-feedback-container");p&&p.remove();let h=Dm({onSubmit:async(y,A)=>{var H;O.isClientTokenMode()&&await O.submitNPSFeedback(y,A),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Je.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(){Te!=null&&(clearInterval(Te),Te=null),pt.forEach(l=>l()),Me.remove(),Xe==null||Xe.remove(),tn==null||tn.destroy(),un==null||un.remove(),Er&&K.removeEventListener("click",Er)}};if((((Hc=t==null?void 0:t.debugTools)!=null?Hc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:ln,getMessages:ln.getMessages,getStatus:ln.getStatus,getMetadata:ln.getPersistentMetadata,updateMetadata:ln.updatePersistentMetadata,clearHistory:()=>ln.clearChat(),setVoiceActive:h=>h?ln.startVoiceRecognition():ln.stopVoiceRecognition()};window.AgentWidgetBrowser=p,pt.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 R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&ln.focusInput()};if(window.addEventListener("persona:focusInput",p),pt.push(()=>{window.removeEventListener("persona:focusInput",p)}),He){let F=ce=>{let de=ce.detail;(!(de!=null&&de.instanceId)||de.instanceId===l)&&ln.showEventStream()},R=ce=>{let de=ce.detail;(!(de!=null&&de.instanceId)||de.instanceId===l)&&ln.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",R),pt.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",R)})}let h=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&ln.showArtifacts()},y=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&ln.hideArtifacts()},A=F=>{let R=F.detail;R!=null&&R.instanceId&&R.instanceId!==l||R!=null&&R.artifact&&ln.upsertArtifact(R.artifact)},H=F=>{let R=F.detail;R!=null&&R.instanceId&&R.instanceId!==l||typeof(R==null?void 0:R.id)=="string"&&ln.selectArtifact(R.id)},U=F=>{let R=F.detail;(!(R!=null&&R.instanceId)||R.instanceId===l)&&ln.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",U),pt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",U)})}let lr=lv(r.persistState);if(lr&&D()){let l=cv(lr.storage),p=`${lr.keyPrefix}widget-open`,h=`${lr.keyPrefix}widget-voice`,y=`${lr.keyPrefix}widget-voice-mode`;if(l){let A=((Bc=lr.persist)==null?void 0:Bc.openState)&&l.getItem(p)==="true",H=((Dc=lr.persist)==null?void 0:Dc.voiceState)&&l.getItem(h)==="true",U=((Nc=lr.persist)==null?void 0:Nc.voiceState)&&l.getItem(y)==="true";if(A&&setTimeout(()=>{ln.open(),setTimeout(()=>{var F;if(H||U)ln.startVoiceRecognition();else if((F=lr.persist)!=null&&F.focusInput){let R=n.querySelector("textarea");R&&R.focus()}},100)},0),(Fc=lr.persist)!=null&&Fc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Oc=lr.persist)!=null&&Oc.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")})),lr.clearOnChatClear){let F=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},R=()=>F();window.addEventListener("persona:clear-chat",R),pt.push(()=>{window.removeEventListener("persona:clear-chat",R)})}}}return g&&D()&&setTimeout(()=>{ln.open()},0),Ue(),ya||qp().then(()=>{O&&(Ko++,Lr.clear(),ao(Je,O.getMessages(),ke))}).catch(()=>{}),ln};var dv=(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},pv=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},uv=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},mv=(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.")},$m=(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"},Al=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=""},Um=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",Al(n)},xl=n=>{n.style.transition=""},wl=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=""},Cl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},Ti=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},gv=(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))},fv=(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)},qm=(n,e,t,r,o,s,a)=>{var v,x,M,E,k,N;let i=vr(s),d=i.reveal==="push";gv(n,e,t,r,d),fv(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,g=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(E=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?E:640,u=c!=null?c.innerWidth<=f:!1;if(g&&u&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),wl(e),xl(r),Um(r),Cl(t),Ti(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=(k=s==null?void 0:s.launcher)==null?void 0:k.zIndex)!=null?N:Mn),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"),Um(r),pv(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",wl(e),xl(r),Cl(t),Ti(o,r);let P=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=P,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",xl(r),Al(r),Ti(o,r);let P=dv(i.width,n.clientWidth),W=Math.max(0,n.clientWidth),C=i.animate?"margin-left 180ms ease":"none",I=i.side==="right"?a?-P:0:a?0:-P;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+P}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="",wl(e),Al(r),Cl(t),Ti(o,r);let P=i.reveal==="emerge";P?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",uv(r,i.maxHeight),r.style.overflow=P||I?"hidden":"visible",r.style.transition=C,P&&(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")}},hv=(n,e)=>{let t=n.ownerDocument.createElement("div");return $m(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){$m(t,r)},destroy(){t.remove()}}},yv=(n,e)=>{var N,P,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"),g=t.createElement("div"),f=(P=(N=e==null?void 0:e.launcher)==null?void 0:N.enabled)==null||P?(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",g.dataset.personaDockRole="host",c.appendChild(g),r.insertBefore(a,n),d.appendChild(n);let u=null,m=()=>{u==null||u.disconnect(),u=null},v=()=>{m(),vr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{qm(a,i,d,c,g,e,f)}),u.observe(a))},x=!1,M=()=>{qm(a,i,d,c,g,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,mv(a,vr(e)))},E=a.ownerDocument.defaultView,k=()=>{M()};return E==null||E.addEventListener("resize",k),vr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:g,shell:a,syncWidgetState(I){let B=I.launcherEnabled?I.open:!0;f!==B&&(f=B,M())},updateConfig(I){var B,D;e=I,((D=(B=e==null?void 0:e.launcher)==null?void 0:B.enabled)!=null?D:!0)===!1&&(f=!0),M()},destroy(){E==null||E.removeEventListener("resize",k),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},zm=(n,e)=>wn(e)?yv(n,e):hv(n,e);var ha={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Vm=.15,jm=1.5,Sl="persona-preview-shell-theme",bv={load:()=>null,save:()=>{},clear:()=>{}},vv=["How do I get started?","Pricing & plans","Talk to support"];function Tl(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function xv(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 Km(n){let e=xv(n);return`* { box-sizing: border-box; }
109
+ `}if(!b&&!l){let Vt="max-height: -moz-available !important; max-height: stretch !important;",jt=p?"":"padding-top: 1.25em !important;",bt=p?"":`z-index: ${(gn=(Ye=r.launcher)==null?void 0:Ye.zIndex)!=null?gn:Ln} !important;`;Ee.style.cssText+=Vt+jt+bt}Ge()};be(),hs(n,r),Ti(n,r),Ei(n,r);let mt=[];mt.push(()=>{document.removeEventListener("keydown",no)});let nn=null,pn=null;mt.push(()=>{nn==null||nn(),nn=null,pn==null||pn(),pn=null}),jn&&mt.push(()=>{jn==null||jn.disconnect(),jn=null}),mt.push(()=>{Rn==null||Rn(),Rn=null,_r(),Ot&&(Ot.remove(),Ot=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),De&&mt.push(()=>{Re!==null&&(cancelAnimationFrame(Re),Re=null),V==null||V.destroy(),V=null,ge==null||ge.destroy(),ge=null,Q=null});let Tr=null,As=()=>{Tr&&(Tr(),Tr=null),r.colorScheme==="auto"&&(Tr=ju(()=>{hs(n,r)}))};As(),mt.push(()=>{Tr&&(Tr(),Tr=null)});let Or=(Lc=r.features)==null?void 0:Lc.streamAnimation;if(Or!=null&&Or.type&&Or.type!=="none"){let l=oa(Or.type,Or.plugins);l&&(nl(l,n),mt.push(()=>rm(n)))}let So=vm(Kt),Er=null,_,Vo=l=>{var b,S;if(!_)return;let p=l!=null?l:_.getMessages(),h=((S=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:S.enabled)!==!1?cu(p):null;h?So.render(h,_,Ie,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(H=>H.role==="user")?So.render([],_,Ie,p):So.render(r.suggestionChips,_,Ie,p,r.suggestionChipsConfig)},Mr=!1,kr=Gu(),$r=new Map,Lr=new Map,ur=new Map,Ko=0,ba=as()!==null,Xn=ai(),Jn=0,mr=null,gr=!1,To=!1,qr=0,Sn=null,Ir=null,Go=!1,Eo=!1,Qo=null,ya=4,Xo=24,va=80,Jo=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ss=(Pc=(Ic=r.voiceRecognition)==null?void 0:Ic.autoResume)!=null?Pc:!1,ar=l=>{s.emit("voice:state",{active:yt.active,source:l,timestamp:Date.now()})},$n=()=>{m(l=>({...l,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},xa=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=Cl(d.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);yt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<pv&&setTimeout(()=>{var H,q;yt.active||(yt.manuallyDeactivated=!1,((q=(H=r.voiceRecognition)==null?void 0:H.provider)==null?void 0:q.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("restore"),_.isVoiceActive()&&ts()}):Wa("restore"))},1e3)},wa=()=>_?qm(_.getMessages()).filter(l=>!l.__skipPersist):[];function Yo(l){if(!(i!=null&&i.save))return;let h={messages:l?qm(l):_?wa():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let b=i.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 Ur=null,Ts=()=>Ee.querySelector("#persona-scroll-container")||ke,so=()=>{Ur!==null&&(cancelAnimationFrame(Ur),Ur=null),gr=!1},Es=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),To=!1,so()},Ms=()=>{qr>0?(Pn.textContent=String(qr),Pn.style.display="",ut.setAttribute("aria-label",`${sn()||"Jump to latest"} (${qr} new)`)):(Pn.textContent="",Pn.style.display="none",ut.setAttribute("aria-label",sn()||"Jump to latest"))},ks=()=>{qr!==0&&(qr=0,Ms())},Ls=()=>Ze()==="follow"?!Xn.isFollowing():!$o(ke,Xo),qn=()=>{if(!_t()||se){ut.parentNode&&ut.remove(),ut.style.display="none";return}ut.parentNode!==pe&&pe.appendChild(ut),_n();let p=Xr(ke)>0&&Ls();p||ks(),ut.style.display=p?"":"none"},Zo=()=>{Xn.pause()&&(Es(),qn())},Pr=()=>{Xn.resume(),ks(),qn()},Wr=(l=!1)=>{Ze()==="follow"&&Xn.isFollowing()&&(!l&&!Mr||(mr!==null&&(cancelAnimationFrame(mr),mr=null),To=!0,mr=requestAnimationFrame(()=>{mr=null,To=!1,Xn.isFollowing()&&Ca(Ts(),l?220:140)})))},Is=(l,p,h,b=()=>!0)=>{let S=l.scrollTop,H=p(),q=H-S;so();let F=performance.now();gr=!0;let B=le=>1-Math.pow(1-le,3),ie=le=>{if(!b()){so();return}let J=p();J!==H&&(H=J,q=H-S);let ve=le-F,_e=Math.min(ve/h,1),Ce=B(_e),et=S+q*Ce;l.scrollTop=et,Jn=l.scrollTop,_e<1?Ur=requestAnimationFrame(ie):(l.scrollTop=H,Jn=l.scrollTop,Ur=null,gr=!1)};Ur=requestAnimationFrame(ie)},Ca=(l,p=500)=>{let h=Xr(l)-l.scrollTop;if(Math.abs(h)<1){Jn=l.scrollTop;return}if(Math.abs(h)>=va){so(),gr=!0,l.scrollTop=Xr(l),Jn=l.scrollTop,gr=!1;return}Is(l,()=>Xr(l),p,()=>Xn.isFollowing())},Ps=()=>{let l=Ts();gr=!0,l.scrollTop=Xr(l),Jn=l.scrollTop,gr=!1,qn()},Ws=l=>{an.style.height=`${Math.max(0,Math.round(l))}px`,Sn&&(Sn.spacerHeight=Math.max(0,l))},Mo=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),so(),Sn=null,an.style.height="0px"},Aa=l=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var ie;Ir=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=ke.querySelector(`[data-message-id="${p}"]`);if(!h)return;let b=0,S=h;for(;S&&S!==ke;)b+=S.offsetTop,S=S.offsetParent;let H=(ie=Sn==null?void 0:Sn.spacerHeight)!=null?ie:0,q=ke.scrollHeight-H,{targetScrollTop:F,spacerHeight:B}=Zu({anchorOffsetTop:b,topOffset:Ft(),viewportHeight:ke.clientHeight,contentHeight:q});Sn={initialSpacerHeight:B,contentHeightAtAnchor:q,spacerHeight:B},Ws(B),Is(ke,()=>F,220)})},Sa=()=>{if(Ze()==="follow"){if(!Xn.isFollowing()||$o(ke,1))return;Wr(!Mr);return}if(Sn&&Sn.initialSpacerHeight>0){let l=ke.scrollHeight-Sn.spacerHeight,p=em({initialSpacerHeight:Sn.initialSpacerHeight,contentHeightAtAnchor:Sn.contentHeightAtAnchor,currentContentHeight:l});p!==Sn.spacerHeight&&Ws(p)}qn()},Ta=l=>{let p=Ze();p==="follow"?(Pr(),Wr(!0)):p==="anchor-top"&&Aa(l)},Ea=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"&&(s.emit("assistant:message",h),!Eo&&Ze()!=="anchor-top"&&Ls()&&(qr+=1,Ms(),qn())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Jo.clear(),p.forEach((h,b)=>{Jo.set(b,h)})},Ma=(l,p,h)=>{var lt,Be,Pe,ze,Ge,xt;let b=document.createElement("div"),H=(()=>{var Ne;let P=o.find(He=>He.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),q=(P,Ne)=>Ne==null?!1:typeof Ne=="string"?(P.textContent=Ne,!0):(P.appendChild(Ne),!0),F=new Set,B=new Set,ie=o.some(P=>P.renderAskUserQuestion),le=[],J=[],ve=r.enableComponentStreaming!==!1,_e=o.some(P=>P.renderApproval)&&r.approval!==!1,Ce=[];if(p.forEach(P=>{var Xe,Wt,dn,lr,Zn,ko,Lo,rs,os,Jt,Io,mo,go,Vr,Po,fr;F.add(P.id);let Ne=ie&&Do(P),He=_e&&P.variant==="approval"&&!!P.approval,me=!Ne&&P.role==="assistant"&&!P.variant&&ve&&Fm(P);if(!He&&ur.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),ur.delete(P.id)}if(!me&&Lr.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),Lr.delete(P.id)}let zt=Do(P)?`:${(Xe=P.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Wt=P.agentMetadata)!=null&&Wt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",qt=Ku(P,Ko)+zt,Xt=Ne||He||me?null:Qu(kr,P.id,qt);if(Xt){b.appendChild(Xt.cloneNode(!0)),Do(P)&&((dn=P.toolCall)!=null&&dn.id)&&((lr=P.agentMetadata)==null?void 0:lr.awaitingLocalTool)===!0&&!((Zn=P.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),$a(P,r,X.composerOverlay));return}let Ct=null,Gt=o.find(Ye=>!!(P.variant==="reasoning"&&Ye.renderReasoning||P.variant==="tool"&&Ye.renderToolCall||!P.variant&&Ye.renderMessage)),Yn=(ko=r.layout)==null?void 0:ko.messages;if(Do(P)&&((Lo=P.agentMetadata)==null?void 0:Lo.askUserQuestionAnswered)===!0){$r.delete(P.id);let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime");return}if(zi(P)&&((os=(rs=r.features)==null?void 0:rs.suggestReplies)==null?void 0:os.enabled)!==!1)return;if(Do(P)&&((Io=(Jt=r.features)==null?void 0:Jt.askUserQuestion)==null?void 0:Io.enabled)!==!1){let Ye=o.find(gn=>typeof gn.renderAskUserQuestion=="function");if(Ye&&Mt.current){let gn=$r.get(P.id),Vt=gn!==qt,jt=null;if(Vt){let{payload:Tt,complete:En}=ls(P),Bn=P.id,Br=()=>{var vn;return(vn=Mt.current)==null?void 0:vn.getMessages().find(Hn=>Hn.id===Bn)};jt=Ye.renderAskUserQuestion({message:P,payload:Tt,complete:En,resolve:vn=>{var Dn;let Hn=Br();Hn&&((Dn=Mt.current)==null||Dn.resolveAskUserQuestion(Hn,vn))},dismiss:()=>{var Hn,Dn,Wo;let vn=Br();(Hn=vn==null?void 0:vn.agentMetadata)!=null&&Hn.awaitingLocalTool&&((Dn=Mt.current)==null||Dn.markAskUserQuestionResolved(vn),(Wo=Mt.current)==null||Wo.resolveAskUserQuestion(vn,"(dismissed)"))},config:r})}let bt=gn!=null;if(Vt&&jt===null&&!bt){((mo=P.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((go=P.agentMetadata)!=null&&go.askUserQuestionAnswered)&&(B.add(P.toolCall.id),$a(P,r,X.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),b.appendChild(Yt),le.push({messageId:P.id,fingerprint:qt,bubble:jt});return}else{((Vr=P.agentMetadata)==null?void 0:Vr.awaitingLocalTool)===!0&&!((Po=P.agentMetadata)!=null&&Po.askUserQuestionAnswered)&&(B.add(P.toolCall.id),$a(P,r,X.composerOverlay));return}}else if(He){let Ye=o.find(bt=>typeof bt.renderApproval=="function"),Vt=ur.get(P.id)!==qt,jt=null;if(Vt&&(Ye!=null&&Ye.renderApproval)){let bt=P.id,Yt=(Tt,En)=>{var Br,vn,Hn;let Bn=(Br=Mt.current)==null?void 0:Br.getMessages().find(Dn=>Dn.id===bt);Bn!=null&&Bn.approval&&(Bn.approval.toolType==="webmcp"?(vn=Mt.current)==null||vn.resolveWebMcpApproval(Bn.id,Tt):(Hn=Mt.current)==null||Hn.resolveApproval(Bn.approval,Tt,En))};jt=Ye.renderApproval({message:P,defaultRenderer:()=>Ai(P,r),config:r,approve:Tt=>Yt("approved",Tt),deny:Tt=>Yt("denied",Tt)})}if(Vt&&jt===null){let bt=l.querySelector(`#wrapper-${P.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),ur.delete(P.id),Ct=Ai(P,r)}else{let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${P.id}`,bt.setAttribute("data-wrapper-id",P.id),bt.setAttribute("data-approval-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),b.appendChild(bt),Ce.push({messageId:P.id,fingerprint:qt,bubble:jt});return}}else if(Gt)if(P.variant==="reasoning"&&P.reasoning&&Gt.renderReasoning){if(!je)return;Ct=Gt.renderReasoning({message:P,defaultRenderer:()=>pl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&Gt.renderToolCall){if(!ye)return;Ct=Gt.renderToolCall({message:P,defaultRenderer:()=>ul(P,r),config:r})}else Gt.renderMessage&&(Ct=Gt.renderMessage({message:P,defaultRenderer:()=>{let Ye=dl(P,h,Yn,r.messageActions,Y,{loadingIndicatorRenderer:H,widgetConfig:r});return P.role!=="user"&&hl(Ye,P,r,_),Ye},config:r}));if(!Ct&&me){let Ye=_m(P);if(Ye){let gn=Lr.get(P.id),Vt=gn!==qt,jt=r.wrapComponentDirectiveInBubble!==!1,bt=null;if(Vt){let Yt=Dm(Ye,{config:r,message:P,transform:h});if(Yt)if(jt){let Tt=document.createElement("div");if(Tt.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(" "),Tt.id=`bubble-${P.id}`,Tt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-mb-3 persona-text-sm persona-leading-relaxed",En.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),Tt.appendChild(En)}Tt.appendChild(Yt),bt=Tt}else{let Tt=document.createElement("div");if(Tt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Tt.id=`bubble-${P.id}`,Tt.setAttribute("data-message-id",P.id),Tt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",En.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),Tt.appendChild(En)}Tt.appendChild(Yt),bt=Tt}}if(bt||gn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),jt||Yt.classList.add("persona-w-full"),b.appendChild(Yt),J.push({messageId:P.id,fingerprint:qt,bubble:bt});return}}}if(!Ct)if(P.variant==="reasoning"&&P.reasoning){if(!je)return;Ct=pl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!ye)return;Ct=ul(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;Ct=Ai(P,r)}else{let Ye=(fr=r.layout)==null?void 0:fr.messages;Ye!=null&&Ye.renderUserMessage&&P.role==="user"?Ct=Ye.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):Ye!=null&&Ye.renderAssistantMessage&&P.role==="assistant"?Ct=Ye.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):Ct=dl(P,h,Ye,r.messageActions,Y,{loadingIndicatorRenderer:H,widgetConfig:r}),P.role!=="user"&&Ct&&hl(Ct,P,r,_)}let on=document.createElement("div");on.className="persona-flex",on.id=`wrapper-${P.id}`,on.setAttribute("data-wrapper-id",P.id),P.role==="user"&&on.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&on.classList.add("persona-w-full"),on.appendChild(Ct),Xu(kr,P.id,qt,on),b.appendChild(on)}),X.composerOverlay&&X.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let He=Ne.getAttribute("data-persona-ask-sheet-for");He&&!B.has(He)&&ds(X.composerOverlay,He)}),(Be=(lt=r.features)==null?void 0:lt.toolCallDisplay)!=null&&Be.grouped){let P=[],Ne=[];p.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&ye){Ne.push(He);return}Ne.length>1&&P.push(Ne),Ne=[]}),Ne.length>1&&P.push(Ne),P.forEach((He,me)=>{var Xe,Wt;let zt=He.map(dn=>Array.from(b.children).find(lr=>lr instanceof HTMLElement&&lr.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if(zt.length<2)return;let qt=document.createElement("div");qt.className="persona-flex",qt.id=`wrapper-tool-group-${me}-${He[0].id}`,qt.setAttribute("data-wrapper-id",`tool-group-${me}-${He[0].id}`);let Xt=document.createElement("div");Xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Xt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Gt=`Called ${He.length} tools`,Yn=(Wt=(Xe=r.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Wt.call(Xe,{messages:He,toolCalls:He.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:Gt,config:r});q(Ct,Yn)||(Ct.textContent=Gt);let on=document.createElement("div");on.className="persona-tool-group-stack persona-flex persona-flex-col",Xt.append(Ct,on),qt.appendChild(Xt),zt[0].before(qt),zt.forEach((dn,lr)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),lr<zt.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(dn),on.appendChild(Zn)})})}Ju(kr,F);let et=p.some(P=>P.role==="assistant"&&P.streaming),Ue=p[p.length-1],ht=(Ue==null?void 0:Ue.role)==="assistant"&&!Ue.streaming&&Ue.variant!=="approval";if(Mr&&p.some(P=>P.role==="user")&&!et&&!ht){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:pa},Ne=o.find(me=>me.renderLoadingIndicator),He=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(He=Ne.renderLoadingIndicator(P)),He===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(He=r.loadingIndicator.render(P)),He===null&&(He=pa()),He){let me=document.createElement("div"),zt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;me.className=zt?["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(He);let qt=document.createElement("div");qt.className="persona-flex",qt.id="wrapper-typing-indicator",qt.setAttribute("data-wrapper-id","typing-indicator"),qt.appendChild(me),b.appendChild(qt)}}if(!Mr&&p.length>0){let P=p[p.length-1],Ne={config:r,lastMessage:P,messageCount:p.length},He=o.find(zt=>zt.renderIdleIndicator),me=null;if(He!=null&&He.renderIdleIndicator&&(me=He.renderIdleIndicator(Ne)),me===null&&((Ge=r.loadingIndicator)!=null&&Ge.renderIdle)&&(me=r.loadingIndicator.renderIdle(Ne)),me){let zt=document.createElement("div"),qt=((xt=r.loadingIndicator)==null?void 0:xt.showBubble)!==!1;zt.className=qt?["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(" "),zt.setAttribute("data-idle-indicator","true"),zt.appendChild(me);let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id="wrapper-idle-indicator",Xt.setAttribute("data-wrapper-id","idle-indicator"),Xt.appendChild(zt),b.appendChild(Xt)}}if(oi(l,b),le.length>0)for(let{messageId:P,fingerprint:Ne,bubble:He}of le){let me=l.querySelector(`#wrapper-${P}`);me&&He!==null&&(me.replaceChildren(He),me.setAttribute("data-bubble-fp",Ne),$r.set(P,Ne))}if($r.size>0)for(let P of $r.keys())F.has(P)||$r.delete(P);if(J.length>0)for(let{messageId:P,fingerprint:Ne,bubble:He}of J){let me=l.querySelector(`#wrapper-${P}`);me&&He!==null&&(me.replaceChildren(He),me.setAttribute("data-bubble-fp",Ne),Lr.set(P,Ne))}if(Lr.size>0)for(let P of Lr.keys())F.has(P)||Lr.delete(P);if(Ce.length>0)for(let{messageId:P,fingerprint:Ne,bubble:He}of Ce){let me=l.querySelector(`#wrapper-${P}`);me&&He!==null&&(me.replaceChildren(He),me.setAttribute("data-bubble-fp",Ne),ur.set(P,Ne))}if(ur.size>0)for(let P of ur.keys())F.has(P)||ur.delete(P)},ao=(l,p,h)=>{Ma(l,p,h),eo()},io=null,ka=()=>{var h;if(io)return;let l=b=>{let S=b.composedPath();S.includes(Ee)||Ke&&S.includes(Ke)||he(!1,"user")};io=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Rs=()=>{var p;if(!io)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",io,!0),io=null};mt.push(()=>Rs());let lo=null,La=()=>{var h;if(lo)return;let l=b=>{b.key==="Escape"&&(b.isComposing||he(!1,"user"))};lo=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Bs=()=>{var p;if(!lo)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",lo,!0),lo=null};mt.push(()=>Bs());let co=!1,Hs=new Set,Ia=()=>{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)},zr=()=>{var ht,lt,Be,Pe;if(!D())return;let l=X.peekBanner,p=X.peekTextNode;if(!l||!p)return;if(M){l.classList.remove("persona-pill-peek--visible");return}let h=(ht=_==null?void 0:_.getMessages())!=null?ht:[],b;for(let ze=h.length-1;ze>=0;ze--){let Ge=h[ze];if(Ge.role==="assistant"&&Ge.content){b=Ge;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let S=b.content,H=!!b.streaming,q=Ia(),F=ci(q),B=F.type!=="none"?oa(F.type,q==null?void 0:q.plugins):null,ie=((lt=B==null?void 0:B.isAnimating)==null?void 0:lt.call(B,b))===!0,le=B!==null&&(H||ie);le&&B&&!Hs.has(B.name)&&(nl(B,n),Hs.add(B.name));let J=le&&(B!=null&&B.containerClass)?B.containerClass:null,ve=(Be=p.dataset.personaPeekStreamClass)!=null?Be:null;ve&&ve!==J&&(p.classList.remove(ve),delete p.dataset.personaPeekStreamClass),J&&ve!==J&&(p.classList.add(J),p.dataset.personaPeekStreamClass=J),le?(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 _e=le?di(S,F.buffer,B,b,H):S;if(le&&F.placeholder==="skeleton"&&H&&(!_e||!_e.trim())){let ze=document.createElement("div"),Ge=aa();Ge.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ge),oi(p,ze)}else{let ze=Math.max(0,_e.length-100),Ge=_e.length>100?_e.slice(-100):_e,xt=fo(Ge);if(!le||!B){let P=_e.length>100?`\u2026${Ge}`:Ge;p.textContent!==P&&(p.textContent=P)}else{let P=xt;(B.wrap==="char"||B.wrap==="word")&&(P=sa(xt,B.wrap,`peek-${b.id}`,{skipTags:B.skipTags,startIndex:ze}));let Ne=document.createElement("div");if(Ne.innerHTML=P,B.useCaret&&Ge.length>0){let He=pi(),me=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),zt=me[me.length-1];zt!=null&&zt.parentNode?zt.parentNode.insertBefore(He,zt.nextSibling):Ne.appendChild(He)}oi(p,Ne),(Pe=B.onAfterRender)==null||Pe.call(B,{container:p,bubble:l,messageId:b.id,message:b,speed:F.speed,duration:F.duration})}}let Ue=Mr||co;l.classList.toggle("persona-pill-peek--visible",Ue)};if(D()){let l=X.peekBanner;if(l){let b=S=>{S.preventDefault(),S.stopPropagation(),he(!0,"user")};l.addEventListener("pointerdown",b),mt.push(()=>{l.removeEventListener("pointerdown",b)})}let p=()=>{co||(co=!0,zr())},h=()=>{co&&(co=!1,zr())};fe.addEventListener("pointerenter",p),fe.addEventListener("pointerleave",h),mt.push(()=>{fe.removeEventListener("pointerenter",p),fe.removeEventListener("pointerleave",h)}),Ke&&(Ke.addEventListener("pointerenter",p),Ke.addEventListener("pointerleave",h),mt.push(()=>{Ke.removeEventListener("pointerenter",p),Ke.removeEventListener("pointerleave",h)}))}let Pa=l=>{var ve,_e,Ce,et,Ue,ht,lt,Be;let p=(_e=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?_e:{},h=(Ce=p.expandedSize)!=null?Ce:"anchored",b=(et=p.bottomOffset)!=null?et:"16px",S=p.collapsedMaxWidth,H=(Ue=p.expandedMaxWidth)!=null?Ue:"880px",q=(ht=p.expandedTopOffset)!=null?ht:"5vh",F=(lt=p.modalMaxWidth)!=null?lt:"880px",B=(Be=p.modalMaxHeight)!=null?Be:"min(90vh, 800px)",ie="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",J=Ee.style;if(J.left="",J.right="",J.top="",J.bottom="",J.transform="",J.width="",J.maxWidth="",J.height="",J.maxHeight="",Ke){let Pe=Ke.style;Pe.bottom=b,Pe.width=S!=null?S:""}if(l&&h!=="fullscreen"){if(h==="modal"){J.top="50%",J.left="50%",J.transform="translate(-50%, -50%)",J.bottom="auto",J.right="auto",J.width=F,J.maxWidth=ie,J.maxHeight=B,J.height=B;return}J.left="50%",J.transform="translateX(-50%)",J.bottom=`calc(${b} + ${le})`,J.top=q,J.width=H,J.maxWidth=ie}},Rr=()=>{var B,ie,le,J,ve,_e,Ce,et;if(!N())return;if(D()){let ht=(le=((ie=(B=r.launcher)==null?void 0:B.composerBar)!=null?ie:{}).expandedSize)!=null?le:"anchored",lt=M?"expanded":"collapsed";Ee.dataset.state=lt,Ee.dataset.expandedSize=ht,Ke&&(Ke.dataset.state=lt,Ke.dataset.expandedSize=ht),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pa(M),pe.style.display=M?"flex":"none",be(),M?(ka(),La()):(Rs(),Bs()),zr();return}let l=Cn(r),p=(J=n.ownerDocument.defaultView)!=null?J:window,h=(_e=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?_e:640,b=(et=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?et:!0,S=p.innerWidth<=h,H=b&&S&&E,q=yr(r).reveal;M?(Ee.style.removeProperty("display"),Ee.style.display=l?"flex":"",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),rn?rn.element.style.display="none":mn&&(mn.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!H?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.setProperty("display","none","important"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.display="",Ee.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),rn?rn.element.style.display=l?"none":"":mn&&(mn.style.display=l?"none":""))},he=(l,p="user")=>{var H,q;if(!N()||M===l)return;let h=M;M=l,Rr();let b=(()=>{var Ce,et,Ue,ht,lt,Be,Pe,ze,Ge,xt;let F=(et=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?et:!1,B=(Ue=n.ownerDocument.defaultView)!=null?Ue:window,ie=(lt=(ht=r.launcher)==null?void 0:ht.mobileFullscreen)!=null?lt:!0,le=(Pe=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Pe:640,J=B.innerWidth<=le,ve=Cn(r)&&ie&&J,_e=D()&&((xt=(Ge=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ge.expandedSize)!=null?xt:"fullscreen")==="fullscreen";return F||ie&&J&&E||ve||_e})();if(M&&b){if(!nn){let F=n.getRootNode(),B=F instanceof ShadowRoot?F.host:n.closest(".persona-host");B&&(nn=rl(B,(q=(H=r.launcher)==null?void 0:H.zIndex)!=null?q:Ln))}pn||(pn=ol(n.ownerDocument))}else M||(nn==null||nn(),nn=null,pn==null||pn(),pn=null);M&&(Ds(),Ze()==="follow"?Wr(!0):Ps());let S={open:M,source:p,timestamp:Date.now()};M&&!h?s.emit("widget:opened",S):!M&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:M,launcherEnabled:E,voiceActive:yt.active,streaming:_.isStreaming()})},w=l=>{Et(l?"stop":"send"),j&&(j.disabled=l),So.buttons.forEach(p=>{p.disabled=l}),Fe.dataset.personaComposerStreaming=l?"true":"false",Fe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},O=()=>{yt.active||Ie&&Ie.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>O(),200)});let I=()=>{var h,b,S,H,q,F,B,ie,le,J,ve;xr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",An.textContent=(H=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",Ie.placeholder=(F=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?F:"How can I help...";let l=ke.querySelector("[data-persona-intro-card]");if(l){let _e=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=_e?"":"none",_e?(ke.classList.remove("persona-gap-3"),ke.classList.add("persona-gap-6")):(ke.classList.remove("persona-gap-6"),ke.classList.add("persona-gap-3"))}!((le=(ie=r.sendButton)==null?void 0:ie.useIcon)!=null&&le)&&!(_!=null&&_.isStreaming())&&(qe.textContent=(ve=(J=r.copy)==null?void 0:J.sendButtonLabel)!=null?ve:"Send"),Ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ie.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=>{m(p=>({...p,sessionId:l}))}});let K=null,ae=()=>{K==null&&(K=setInterval(()=>{let l=Qe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(K),K=null;return}let p=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Ua(p-b))})},100))};_=new ti(r,{onMessagesChanged(l){var b;ao(Qe,l,Le),ae(),Vo(l),Wr(!Mr),Ea(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&Mo(),!Go||Eo?(Go=!0,Qo=(b=p==null?void 0:p.id)!=null?b:null):p&&p.id!==Qo&&(Qo=p.id,Ta(p.id));let h=yt.lastUserMessageId;p&&p.id!==h&&(yt.lastUserMessageId=p.id,s.emit("user:message",p)),yt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Yo(l),zr()},onStatusChanged(l){var b;let p=(b=r.statusIndicator)!=null?b:{};st(bn,(S=>{var H,q,F,B;return S==="idle"?(H=p.idleText)!=null?H:kn.idle:S==="connecting"?(q=p.connectingText)!=null?q:kn.connecting:S==="connected"?(F=p.connectedText)!=null?F:kn.connected:S==="error"?(B=p.errorText)!=null?B:kn.error:kn[S]})(l),p,l)},onStreamingChanged(l){Mr=l,w(l),_&&ao(Qe,_.getMessages(),Le),l||Wr(!0),zr()},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":jr(),ts();break;case"processing":jr(),rg();break;case"speaking":jr(),og();break;default:l==="idle"&&_.isBargeInActive()?(jr(),ts(),j==null||j.setAttribute("aria-label","End voice session")):(yt.active=!1,jr(),ar("system"),$n());break}},onArtifactsState(l){Vn=l,Qn(),Yo()}}),Mt.current=_;let G=null;if(_.onReadAloudChange((l,p)=>{var S;Yr=l,Zr=p,eo();let h=l!=null?l:G;l&&(G=l);let b=h&&(S=_.getMessages().find(H=>H.id===h))!=null?S:null;s.emit("message:read-aloud",{messageId:h,message:b,state:p,timestamp:Date.now()}),p==="idle"&&(G=null)}),Go=!0,((Rc=(Wc=r.voiceRecognition)==null?void 0:Wc.provider)==null?void 0:Rc.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ge||r.onSSEEvent)&&_.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),de==null||de.processEvent(l,p),ge==null||ge.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,b;if(l){if(l.metadata&&(d=Cl(l.metadata),T.syncFromMetadata()),(p=l.messages)!=null&&p.length){Eo=!0;try{_.hydrateMessages(l.messages)}finally{Eo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let We=()=>{var p,h,b;!D()||M||!((b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||he(!0,"auto")},Oe=l=>{var S;if(l.preventDefault(),_.isStreaming()){_.cancel(),de==null||de.reset(),V==null||V.update();return}let p=Ie.value.trim(),h=(S=wt==null?void 0:wt.hasAttachments())!=null?S:!1;if(!p&&!h)return;We();let b;h&&(b=[],b.push(...wt.getContentParts()),p&&b.push(Gi(p))),Ie.value="",Ie.style.height="auto",$t(),_.sendMessage(p,{contentParts:b}),h&&wt.clearAttachments()},it=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},Je={...si},It=!1,$t=()=>{Je={...si}},yn=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Pt=l=>{if(!Ie)return;It=!0,Ie.value=l,Ie.dispatchEvent(new Event("input",{bubbles:!0})),It=!1;let p=Ie.value.length;Ie.setSelectionRange(p,p)},Bt=()=>{It||$t()},un=l=>{if(Ie){if(it()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Ie.selectionStart===0&&Ie.selectionEnd===0,h=Vu({direction:l.key==="ArrowUp"?"up":"down",history:yn(),currentValue:Ie.value,atStart:p,state:Je});if(Je=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Pt(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}$t(),l.preventDefault(),qe.click()}}},Tn=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(pe)&&(_.cancel(),de==null||de.reset(),V==null||V.update(),$t(),l.preventDefault(),l.stopImmediatePropagation())},wn=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!wt)return;let p=mv(l.clipboardData);p.length!==0&&(l.preventDefault(),await wt.handleFiles(p))},Ht=null,ln=!1,es=null,ft=null,Ll=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Wa=(l="user")=>{var H,q,F,B,ie,le,J;if(ln||_.isStreaming())return;let p=Ll();if(!p)return;Ht=new p;let b=(q=((H=r.voiceRecognition)!=null?H:{}).pauseDuration)!=null?q:2e3;Ht.continuous=!0,Ht.interimResults=!0,Ht.lang="en-US";let S=Ie.value;Ht.onresult=ve=>{let _e="",Ce="";for(let Ue=0;Ue<ve.results.length;Ue++){let ht=ve.results[Ue],lt=ht[0].transcript;ht.isFinal?_e+=lt+" ":Ce=lt}let et=S+_e+Ce;Ie.value=et,es&&clearTimeout(es),(_e||Ce)&&(es=window.setTimeout(()=>{let Ue=Ie.value.trim();Ue&&Ht&&ln&&(po(),Ie.value="",Ie.style.height="auto",_.sendMessage(Ue,{viaVoice:!0}))},b))},Ht.onerror=ve=>{ve.error!=="no-speech"&&po()},Ht.onend=()=>{if(ln){let ve=Ie.value.trim();ve&&ve!==S.trim()&&(Ie.value="",Ie.style.height="auto",_.sendMessage(ve,{viaVoice:!0})),po()}};try{if(Ht.start(),ln=!0,yt.active=!0,l!=="system"&&(yt.manuallyDeactivated=!1),ar(l),$n(),j){let ve=(F=r.voiceRecognition)!=null?F:{};ft={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(B=ve.iconName)!=null?B:"mic",iconSize:parseFloat((J=(le=ve.iconSize)!=null?le:(ie=r.sendButton)==null?void 0:ie.size)!=null?J:"40")||24};let _e=ve.recordingBackgroundColor,Ce=ve.recordingIconColor,et=ve.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let Ue=j.querySelector("svg");Ue&&Ue.setAttribute("stroke",Ce)}et&&(j.style.borderColor=et),j.setAttribute("aria-label","Stop voice recognition")}}catch{po("system")}},po=(l="user")=>{if(ln){if(ln=!1,es&&(clearTimeout(es),es=null),Ht){try{Ht.stop()}catch{}Ht=null}if(yt.active=!1,ar(l),$n(),j){if(j.classList.remove("persona-voice-recording"),ft){j.style.backgroundColor=ft.backgroundColor,j.style.color=ft.color,j.style.borderColor=ft.borderColor;let p=j.querySelector("svg");p&&p.setAttribute("stroke",ft.color||"currentColor"),ft=null}j.setAttribute("aria-label","Start voice recognition")}}},ng=(l,p)=>{var lt,Be,Pe,ze,Ge,xt,P,Ne,He;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((lt=l==null?void 0:l.provider)==null?void 0:lt.type)==="runtype",S=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||b||S))return null;let q=y("div","persona-send-button-wrapper"),F=y("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 B=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",ie=(ze=p==null?void 0:p.size)!=null?ze:"40px",le=(Ge=l==null?void 0:l.iconSize)!=null?Ge:ie,J=parseFloat(le)||24,ve=(xt=l==null?void 0:l.backgroundColor)!=null?xt:p==null?void 0:p.backgroundColor,_e=(P=l==null?void 0:l.iconColor)!=null?P:p==null?void 0:p.textColor;F.style.width=le,F.style.height=le,F.style.minWidth=le,F.style.minHeight=le,F.style.fontSize="18px",F.style.lineHeight="1",_e?F.style.color=_e:F.style.color="var(--persona-text, #111827)";let et=Ae(B,J,_e||"currentColor",1.5);et?F.appendChild(et):F.textContent="\u{1F3A4}",ve?F.style.backgroundColor=ve: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 Ue=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((He=l==null?void 0:l.showTooltip)!=null?He:!1)&&Ue){let me=y("div","persona-send-button-tooltip");me.textContent=Ue,q.appendChild(me)}return{micButton:F,micButtonWrapper:q}},Li=()=>{var p,h,b,S,H;if(!j||ft)return;let l=(p=r.voiceRecognition)!=null?p:{};ft={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((H=(S=l.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?H:"40")||24}},Ii=(l,p)=>{var H,q,F,B,ie;if(!j)return;let h=j.querySelector("svg");h&&h.remove();let b=(ie=ft==null?void 0:ft.iconSize)!=null?ie:parseFloat((B=(F=(H=r.voiceRecognition)==null?void 0:H.iconSize)!=null?F:(q=r.sendButton)==null?void 0:q.size)!=null?B:"40")||24,S=Ae(l,b,p,1.5);S&&j.appendChild(S)},Ra=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ts=()=>{var S;if(!j)return;Li();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(Ra(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let H=j.querySelector("svg");H&&H.setAttribute("stroke",h)}b&&(j.style.borderColor=b),j.setAttribute("aria-label","Stop voice recognition")},rg=()=>{var F,B,ie,le,J,ve,_e,Ce;if(!j)return;Li();let l=(F=r.voiceRecognition)!=null?F:{},p=_.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",b=(le=(ie=l.processingIconColor)!=null?ie:ft==null?void 0:ft.color)!=null?le:"",S=(ve=(J=l.processingBackgroundColor)!=null?J:ft==null?void 0:ft.backgroundColor)!=null?ve:"",H=(Ce=(_e=l.processingBorderColor)!=null?_e:ft==null?void 0:ft.borderColor)!=null?Ce:"";Ra(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=S,j.style.borderColor=H;let q=b||"currentColor";j.style.color=q,Ii(h,q),j.setAttribute("aria-label","Processing voice input"),p==="none"&&(j.style.cursor="default")},og=()=>{var ie,le,J,ve,_e,Ce,et,Ue,ht,lt,Be,Pe;if(!j)return;Li();let l=(ie=r.voiceRecognition)!=null?ie:{},p=_.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",b=(le=l.speakingIconName)!=null?le:h,S=(Ce=l.speakingIconColor)!=null?Ce:p==="barge-in"?(ve=(J=l.recordingIconColor)!=null?J:ft==null?void 0:ft.color)!=null?ve:"":(_e=ft==null?void 0:ft.color)!=null?_e:"",H=(ht=l.speakingBackgroundColor)!=null?ht:p==="barge-in"?(et=l.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Ue=ft==null?void 0:ft.backgroundColor)!=null?Ue:"",q=(Pe=l.speakingBorderColor)!=null?Pe:p==="barge-in"?(lt=l.recordingBorderColor)!=null?lt:"":(Be=ft==null?void 0:ft.borderColor)!=null?Be:"";Ra(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=H,j.style.borderColor=q;let F=S||"currentColor";j.style.color=F,Ii(b,F);let B=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",B),p==="none"&&(j.style.cursor="default"),p==="barge-in"&&j.classList.add("persona-voice-recording")},jr=()=>{var l,p,h;j&&(Ra(),ft&&(j.style.backgroundColor=(l=ft.backgroundColor)!=null?l:"",j.style.color=(p=ft.color)!=null?p:"",j.style.borderColor=(h=ft.borderColor)!=null?h:"",Ii(ft.iconName,ft.color||"currentColor"),ft=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},Ba=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),ar("user"),jr()});return}_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),yt.manuallyDeactivated=!_.isVoiceActive(),$n(),ar("user"),_.isVoiceActive()?ts():jr()});return}if(ln){let h=Ie.value.trim();yt.manuallyDeactivated=!0,$n(),po("user"),h&&(Ie.value="",Ie.style.height="auto",_.sendMessage(h))}else yt.manuallyDeactivated=!1,$n(),Wa("user")};zn=Ba,j&&(j.addEventListener("click",Ba),mt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),jr()):po("system"),j&&j.removeEventListener("click",Ba)}));let sg=s.on("assistant:complete",()=>{Ss&&(yt.active||yt.manuallyDeactivated||Ss==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!yt.active&&!yt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("auto"),_.isVoiceActive()&&ts()}):Wa("auto"))},600))});mt.push(sg);let ag=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});mt.push(ag);let Il=()=>{he(!M,"user")},rn=null,mn=null;if(E&&!D()){let{instance:l,element:p}=il({config:r,plugins:o,onToggle:Il});rn=l,l||(mn=p)}rn?n.appendChild(rn.element):mn&&n.appendChild(mn),Rr(),Vo(),I(),w(_.isStreaming()),Ze()==="follow"?Wr(!0):Ps(),xa(),R&&(!E||D()?setTimeout(()=>O(),0):M&&setTimeout(()=>O(),200));let Ds=()=>{var B,ie,le,J,ve,_e,Ce,et,Ue,ht,lt,Be,Pe,ze,Ge,xt,P,Ne,He,me,zt,qt;if(D()){_n(),Rr();return}let l=Cn(r),p=(ie=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?ie:!1,h=l||p||((J=(le=r.launcher)==null?void 0:le.fullHeight)!=null?J:!1),b=(ve=n.ownerDocument.defaultView)!=null?ve:window,S=(Ce=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ce:!0,H=(Ue=(et=r.launcher)==null?void 0:et.mobileBreakpoint)!=null?Ue:640,q=b.innerWidth<=H,F=S&&q&&E;try{if(F){be(),hs(n,r);return}if(k&&(k=!1,be(),hs(n,r)),!E&&!l){fe.style.height="",fe.style.width="";return}if(!p&&!l){let Xt=(lt=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?lt:r==null?void 0:r.launcherWidth,Ct=Xt!=null?Xt:Qr;fe.style.width=Ct,fe.style.maxWidth=Ct}if(Sr(),!h){let Xt=b.innerHeight,Ct=64,Gt=(Pe=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?Pe:0,Yn=Math.max(200,Xt-Ct),on=Math.min(640,Yn),Xe=Math.max(200,on-Gt);fe.style.height=`${Xe}px`}}finally{if(_n(),Rr(),M&&E){let Ct=((ze=n.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((xt=(Ge=r.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?xt:640),Gt=(Ne=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Ne:!1,Yn=(me=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?me:!0,on=Cn(r)&&Yn&&Ct,Xe=Gt||Yn&&Ct&&E||on;if(Xe&&!pn){let Wt=n.getRootNode(),dn=Wt instanceof ShadowRoot?Wt.host:n.closest(".persona-host");dn&&!nn&&(nn=rl(dn,(qt=(zt=r.launcher)==null?void 0:zt.zIndex)!=null?qt:Ln)),pn=ol(n.ownerDocument)}else Xe||(nn==null||nn(),nn=null,pn==null||pn(),pn=null)}}};Ds();let Pl=(Bc=n.ownerDocument.defaultView)!=null?Bc:window;if(Pl.addEventListener("resize",Ds),mt.push(()=>Pl.removeEventListener("resize",Ds)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{_n()});l.observe(Fe),mt.push(()=>l.disconnect())}Jn=ke.scrollTop;let Wl=Xr(ke),ig=()=>{let l=ke.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:ke.ownerDocument.getSelection()},Pi=()=>Yu(ig(),ke),Rl=()=>{let l=ke.scrollTop,p=Xr(ke),h=p<Wl;if(Wl=p,Ze()!=="follow"){Jn=l,qn();return}let{action:b,nextLastScrollTop:S}=ii({following:Xn.isFollowing(),currentScrollTop:l,lastScrollTop:Jn,nearBottom:$o(ke,Xo),userScrollThreshold:ya,isAutoScrolling:gr||To||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Jn=S,b==="resume"){Pi()||Pr();return}b==="pause"&&Zo()};if(ke.addEventListener("scroll",Rl,{passive:!0}),mt.push(()=>ke.removeEventListener("scroll",Rl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Sa()});l.observe(Qe),l.observe(ke),mt.push(()=>l.disconnect())}let Bl=()=>{Ze()==="follow"&&Xn.isFollowing()&&Pi()&&Zo()},Hl=ke.ownerDocument;Hl.addEventListener("selectionchange",Bl),mt.push(()=>{Hl.removeEventListener("selectionchange",Bl)});let Dl=l=>{if(Ze()!=="follow")return;let p=li({following:Xn.isFollowing(),deltaY:l.deltaY,nearBottom:$o(ke,Xo),resumeWhenNearBottom:!0});p==="pause"?Zo():p==="resume"&&!Pi()&&Pr()};ke.addEventListener("wheel",Dl,{passive:!0}),mt.push(()=>ke.removeEventListener("wheel",Dl)),ut.addEventListener("click",()=>{Mo(),ke.scrollTop=ke.scrollHeight,Jn=ke.scrollTop,Pr(),Wr(!0),qn()}),mt.push(()=>ut.remove()),mt.push(()=>{Es(),Mo()});let Nl=()=>{Ve&&(Er&&(Ve.removeEventListener("click",Er),Er=null),N()?(Ve.style.display="",Er=()=>{he(!1,"user")},Ve.addEventListener("click",Er)):Ve.style.display="none")};Nl(),(()=>{let{clearChatButton:l}=X;l&&l.addEventListener("click",()=>{_.clearMessages(),kr.clear(),Pr(),ds(X.composerOverlay);try{localStorage.removeItem(ws),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ws}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ws)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(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)}d={},T.syncFromMetadata(),ge==null||ge.clear(),de==null||de.reset(),V==null||V.update()})})(),Dt&&Dt.addEventListener("submit",Oe),Ie==null||Ie.addEventListener("keydown",un),Ie==null||Ie.addEventListener("input",Bt),Ie==null||Ie.addEventListener("paste",wn);let Fl=(Hc=n.ownerDocument)!=null?Hc:document;Fl.addEventListener("keydown",Tn,!0);let _l="persona-attachment-drop-active",Ns=0,Wi=()=>{Ns=0,pe.classList.remove(_l)},ns=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&wt!==null},Ol=l=>{!Mi(l.dataTransfer)||!ns()||(Ns++,Ns===1&&pe.classList.add(_l))},$l=l=>{!Mi(l.dataTransfer)||!ns()||(Ns--,Ns<=0&&Wi())},ql=l=>{!Mi(l.dataTransfer)||!ns()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Ul=l=>{var h;if(!Mi(l.dataTransfer)||!ns())return;l.preventDefault(),l.stopPropagation(),Wi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&wt.handleFiles(p)},uo=!0;pe.addEventListener("dragenter",Ol,uo),pe.addEventListener("dragleave",$l,uo),n.addEventListener("dragover",ql,uo),n.addEventListener("drop",Ul,uo);let Ha=n.ownerDocument,zl=l=>{ns()&&l.preventDefault()},jl=l=>{ns()&&l.preventDefault()};Ha.addEventListener("dragover",zl),Ha.addEventListener("drop",jl),mt.push(()=>{Dt&&Dt.removeEventListener("submit",Oe),Ie==null||Ie.removeEventListener("keydown",un),Ie==null||Ie.removeEventListener("input",Bt),Ie==null||Ie.removeEventListener("paste",wn),Fl.removeEventListener("keydown",Tn,!0)}),mt.push(()=>{pe.removeEventListener("dragenter",Ol,uo),pe.removeEventListener("dragleave",$l,uo),n.removeEventListener("dragover",ql,uo),n.removeEventListener("drop",Ul,uo),Ha.removeEventListener("dragover",zl),Ha.removeEventListener("drop",jl),Wi()}),mt.push(()=>{_.cancel()}),rn?mt.push(()=>{rn==null||rn.destroy()}):mn&&mt.push(()=>{mn==null||mn.remove()});let cn={update(l){var En,Bn,Br,vn,Hn,Dn,Wo,Fs,qc,Uc,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,bd,yd,vd,xd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Id,Pd,Wd,Rd,Bd,Hd,Dd,Nd,Fd,_d,Od,$d,qd,Ud,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,bp,yp,vp,xp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Ip,Pp,Wp,Rp,Bp,Hp,Dp,Np,Fp,_p,Op;let p=r.toolCall,h=r.messageActions,b=(En=r.layout)==null?void 0:En.messages,S=r.colorScheme,H=r.loadingIndicator,q=r.iterationDisplay,F=(Bn=r.features)==null?void 0:Bn.showReasoning,B=(Br=r.features)==null?void 0:Br.showToolCalls,ie=(vn=r.features)==null?void 0:vn.toolCallDisplay,le=(Hn=r.features)==null?void 0:Hn.reasoningDisplay;r={...r,...l},be(),hs(n,r),Ti(n,r),Ei(n,r),Qn(),r.colorScheme!==S&&As();let J=yl.getForInstance(r.plugins);o.length=0,o.push(...J),E=(Wo=(Dn=r.launcher)==null?void 0:Dn.enabled)!=null?Wo:!0,A=(qc=(Fs=r.launcher)==null?void 0:Fs.autoExpand)!=null?qc:!1,je=(zc=(Uc=r.features)==null?void 0:Uc.showReasoning)!=null?zc:!0,ye=(Vc=(jc=r.features)==null?void 0:jc.showToolCalls)!=null?Vc:!0,$e=(Gc=(Kc=r.features)==null?void 0:Kc.scrollToBottom)!=null?Gc:{};let ve=Ze();Se=(Xc=(Qc=r.features)==null?void 0:Qc.scrollBehavior)!=null?Xc:{},ve!==Ze()&&(Mo(),Pr()),wr(),qn();let _e=De;if(De=(Yc=(Jc=r.features)==null?void 0:Jc.showEventStreamToggle)!=null?Yc:!1,De&&!_e){if(ge||(Q=new ma(re),ge=new ua(oe,Q),de=de!=null?de:new ga,Q.open().then(()=>ge==null?void 0:ge.restore()).catch(()=>{}),_.setSSEEventCallback((ee,kt)=>{var Qt;(Qt=r.onSSEEvent)==null||Qt.call(r,ee,kt),de==null||de.processEvent(ee,kt),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!vt&&we){let ee=(ed=(Zc=r.features)==null?void 0:Zc.eventStream)==null?void 0:ed.classNames,kt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");vt=y("button",kt),vt.style.width="28px",vt.style.height="28px",vt.style.color=Fn.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let Qt=Ae("activity","18px","currentColor",1.5);Qt&&vt.appendChild(Qt);let ct=X.clearChatButtonWrapper,Rt=X.closeButtonWrapper,fn=ct||Rt;fn&&fn.parentNode===we?we.insertBefore(vt,fn):we.appendChild(vt),vt.addEventListener("click",()=>{se?pr():Dr()})}}else!De&&_e&&(pr(),vt&&(vt.remove(),vt=null),ge==null||ge.clear(),Q==null||Q.destroy(),ge=null,Q=null,de==null||de.reset(),de=null);if(((td=r.launcher)==null?void 0:td.enabled)===!1&&rn&&(rn.destroy(),rn=null),((nd=r.launcher)==null?void 0:nd.enabled)===!1&&mn&&(mn.remove(),mn=null),((rd=r.launcher)==null?void 0:rd.enabled)!==!1&&!rn&&!mn){let{instance:ee,element:kt}=il({config:r,plugins:o,onToggle:Il});rn=ee,ee||(mn=kt),n.appendChild(kt)}rn&&rn.update(r),$&&((od=r.launcher)==null?void 0:od.title)!==void 0&&($.textContent=r.launcher.title),Me&&((sd=r.launcher)==null?void 0:sd.subtitle)!==void 0&&(Me.textContent=r.launcher.subtitle);let Ce=(ad=r.layout)==null?void 0:ad.header;if((Ce==null?void 0:Ce.layout)!==C&&we){let ee=Ce?gi(r,Ce,{showClose:N(),onClose:()=>he(!1,"user")}):qo({config:r,showClose:N(),onClose:()=>he(!1,"user")});tt.replaceHeader(ee),we=tt.header.element,Nt=tt.header.iconHolder,$=tt.header.headerTitle,Me=tt.header.headerSubtitle,Ve=tt.header.closeButton,C=Ce==null?void 0:Ce.layout}else if(Ce&&(Nt&&(Nt.style.display=Ce.showIcon===!1?"none":""),$&&($.style.display=Ce.showTitle===!1?"none":""),Me&&(Me.style.display=Ce.showSubtitle===!1?"none":""),Ve&&(Ve.style.display=Ce.showCloseButton===!1?"none":""),X.clearChatButtonWrapper)){let ee=Ce.showClearChat;if(ee!==void 0){X.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:kt}=X;kt&&!kt.classList.contains("persona-absolute")&&(ee?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let Ue=((id=r.layout)==null?void 0:id.showHeader)!==!1;we&&(we.style.display=Ue?"":"none");let ht=((ld=r.layout)==null?void 0:ld.showFooter)!==!1;Fe&&(Fe.style.display=ht?"":"none"),_n(),qn(),E!==W?E?he(A,"auto"):(M=!0,Rr()):A!==L&&he(A,"auto"),L=A,W=E,Ds(),Nl();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(p),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((cd=r.layout)==null?void 0:cd.messages)!==JSON.stringify(b),xt=((dd=r.loadingIndicator)==null?void 0:dd.render)!==(H==null?void 0:H.render)||((pd=r.loadingIndicator)==null?void 0:pd.renderIdle)!==(H==null?void 0:H.renderIdle)||((ud=r.loadingIndicator)==null?void 0:ud.showBubble)!==(H==null?void 0:H.showBubble),P=r.iterationDisplay!==q,Ne=((gd=(md=r.features)==null?void 0:md.showReasoning)!=null?gd:!0)!==(F!=null?F:!0)||((hd=(fd=r.features)==null?void 0:fd.showToolCalls)!=null?hd:!0)!==(B!=null?B:!0)||JSON.stringify((bd=r.features)==null?void 0:bd.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify((yd=r.features)==null?void 0:yd.reasoningDisplay)!==JSON.stringify(le);(Pe||ze||Ge||xt||P||Ne)&&_&&(Ko++,ao(Qe,_.getMessages(),Le));let me=(vd=r.launcher)!=null?vd:{},zt=(xd=me.headerIconHidden)!=null?xd:!1,qt=(Cd=(wd=r.layout)==null?void 0:wd.header)==null?void 0:Cd.showIcon,Xt=zt||qt===!1,Ct=me.headerIconName,Gt=(Ad=me.headerIconSize)!=null?Ad:"48px";if(Nt){let ee=pe.querySelector(".persona-border-b-persona-divider"),kt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(Xt)Nt.style.display="none",ee&&kt&&!ee.contains(kt)&&ee.insertBefore(kt,ee.firstChild);else{if(Nt.style.display="",Nt.style.height=Gt,Nt.style.width=Gt,ee&&kt&&(ee.contains(Nt)?Nt.nextSibling!==kt&&(Nt.remove(),ee.insertBefore(Nt,kt)):ee.insertBefore(Nt,kt)),Ct){let ct=parseFloat(Gt)||24,Rt=Ae(Ct,ct*.6,"currentColor",1);Rt?Nt.replaceChildren(Rt):Nt.textContent=(Sd=me.agentIconText)!=null?Sd:"\u{1F4AC}"}else if(me.iconUrl){let ct=Nt.querySelector("img");if(ct)ct.src=me.iconUrl,ct.style.height=Gt,ct.style.width=Gt;else{let Rt=document.createElement("img");Rt.src=me.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=Gt,Rt.style.width=Gt,Nt.replaceChildren(Rt)}}else{let ct=Nt.querySelector("svg"),Rt=Nt.querySelector("img");(ct||Rt)&&Nt.replaceChildren(),Nt.textContent=(Td=me.agentIconText)!=null?Td:"\u{1F4AC}"}let Qt=Nt.querySelector("img");Qt&&(Qt.style.height=Gt,Qt.style.width=Gt)}}let Yn=(Md=(Ed=r.layout)==null?void 0:Ed.header)==null?void 0:Md.showTitle,on=(Ld=(kd=r.layout)==null?void 0:kd.header)==null?void 0:Ld.showSubtitle;if($&&($.style.display=Yn===!1?"none":""),Me&&(Me.style.display=on===!1?"none":""),Ve){((Pd=(Id=r.layout)==null?void 0:Id.header)==null?void 0:Pd.showCloseButton)===!1?Ve.style.display="none":Ve.style.display="";let kt=(Wd=me.closeButtonSize)!=null?Wd:"32px",Qt=(Rd=me.closeButtonPlacement)!=null?Rd:"inline";Ve.style.height=kt,Ve.style.width=kt;let{closeButtonWrapper:ct}=X,Rt=Qt==="top-right",fn=ct==null?void 0:ct.classList.contains("persona-absolute");if(ct&&Rt!==fn)if(ct.remove(),Rt)ct.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(ct);else{let gt=(Hd=(Bd=me.clearChat)==null?void 0:Bd.placement)!=null?Hd:"inline",hn=(Nd=(Dd=me.clearChat)==null?void 0:Dd.enabled)!=null?Nd:!0;ct.className=hn&&gt==="inline"?"":"persona-ml-auto";let Un=pe.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(ct)}if(Ve.style.color=me.closeButtonColor||Fn.actionIconColor,me.closeButtonBackgroundColor?(Ve.style.backgroundColor=me.closeButtonBackgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let gt=me.closeButtonBorderWidth||"0px",hn=me.closeButtonBorderColor||"transparent";Ve.style.border=`${gt} solid ${hn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");me.closeButtonBorderRadius?(Ve.style.borderRadius=me.closeButtonBorderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(Ve.style.paddingLeft=me.closeButtonPaddingX,Ve.style.paddingRight=me.closeButtonPaddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),me.closeButtonPaddingY?(Ve.style.paddingTop=me.closeButtonPaddingY,Ve.style.paddingBottom=me.closeButtonPaddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Mn=(Fd=me.closeButtonIconName)!=null?Fd:"x",hr=(_d=me.closeButtonIconText)!=null?_d:"\xD7";Ve.innerHTML="";let Nn=Ae(Mn,"28px","currentColor",1);Nn?Ve.appendChild(Nn):Ve.textContent=hr;let tn=(Od=me.closeButtonTooltipText)!=null?Od:"Close chat",er=($d=me.closeButtonShowTooltip)!=null?$d:!0;if(Ve.setAttribute("aria-label",tn),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),er&&tn)){let gt=null,hn=()=>{if(gt||!Ve)return;let Ro=Ve.ownerDocument,_s=Ro.body;if(!_s)return;gt=Hr(Ro,"div","persona-clear-chat-tooltip"),gt.textContent=tn;let Os=Hr(Ro,"div");Os.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Os);let Bo=Ve.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(yo),gt.style.left=`${Bo.left+Bo.width/2}px`,gt.style.top=`${Bo.top-8}px`,gt.style.transform="translate(-50%, -100%)",_s.appendChild(gt)},Un=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};ct.addEventListener("mouseenter",hn),ct.addEventListener("mouseleave",Un),Ve.addEventListener("focus",hn),Ve.addEventListener("blur",Un),ct._cleanupTooltip=()=>{Un(),ct&&(ct.removeEventListener("mouseenter",hn),ct.removeEventListener("mouseleave",Un)),Ve&&(Ve.removeEventListener("focus",hn),Ve.removeEventListener("blur",Un))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Wt}=X;if(Xe){let ee=(qd=me.clearChat)!=null?qd:{},kt=(Ud=ee.enabled)!=null?Ud:!0,Qt=(jd=(zd=r.layout)==null?void 0:zd.header)==null?void 0:jd.showClearChat,ct=Qt!==void 0?Qt:kt,Rt=(Vd=ee.placement)!=null?Vd:"inline";if(Wt){Wt.style.display=ct?"":"none";let{closeButtonWrapper:fn}=X;!D()&&fn&&!fn.classList.contains("persona-absolute")&&(ct?fn.classList.remove("persona-ml-auto"):fn.classList.add("persona-ml-auto"));let Mn=Rt==="top-right",hr=Wt.classList.contains("persona-absolute");if(!D()&&Mn!==hr&&ct){if(Wt.remove(),Mn)Wt.className="persona-absolute persona-top-4 persona-z-50",Wt.style.right="48px",pe.style.position="relative",pe.appendChild(Wt);else{Wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wt.style.right="";let tn=pe.querySelector(".persona-border-b-persona-divider"),er=X.closeButtonWrapper;tn&&er&&er.parentElement===tn?tn.insertBefore(Wt,er):tn&&tn.appendChild(Wt)}let Nn=X.closeButtonWrapper;Nn&&!Nn.classList.contains("persona-absolute")&&(Mn?Nn.classList.add("persona-ml-auto"):Nn.classList.remove("persona-ml-auto"))}}if(ct){if(!D()){let gt=(Kd=ee.size)!=null?Kd:"32px";Xe.style.height=gt,Xe.style.width=gt}let fn=(Gd=ee.iconName)!=null?Gd:"refresh-cw",Mn=(Qd=ee.iconColor)!=null?Qd:"";Xe.style.color=Mn||Fn.actionIconColor,Xe.innerHTML="";let hr=D()?"14px":"20px",Nn=Ae(fn,hr,"currentColor",2);if(Nn&&Xe.appendChild(Nn),ee.backgroundColor?(Xe.style.backgroundColor=ee.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let gt=ee.borderWidth||"0px",hn=ee.borderColor||"transparent";Xe.style.border=`${gt} solid ${hn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");ee.borderRadius?(Xe.style.borderRadius=ee.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),ee.paddingX?(Xe.style.paddingLeft=ee.paddingX,Xe.style.paddingRight=ee.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),ee.paddingY?(Xe.style.paddingTop=ee.paddingY,Xe.style.paddingBottom=ee.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let tn=(Xd=ee.tooltipText)!=null?Xd:"Clear chat",er=(Jd=ee.showTooltip)!=null?Jd:!0;if(Xe.setAttribute("aria-label",tn),Wt&&(Wt._cleanupTooltip&&(Wt._cleanupTooltip(),delete Wt._cleanupTooltip),er&&tn)){let gt=null,hn=()=>{if(gt||!Xe)return;let Ro=Xe.ownerDocument,_s=Ro.body;if(!_s)return;gt=Hr(Ro,"div","persona-clear-chat-tooltip"),gt.textContent=tn;let Os=Hr(Ro,"div");Os.className="persona-clear-chat-tooltip-arrow",gt.appendChild(Os);let Bo=Xe.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(yo),gt.style.left=`${Bo.left+Bo.width/2}px`,gt.style.top=`${Bo.top-8}px`,gt.style.transform="translate(-50%, -100%)",_s.appendChild(gt)},Un=()=>{gt&&gt.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};Wt.addEventListener("mouseenter",hn),Wt.addEventListener("mouseleave",Un),Xe.addEventListener("focus",hn),Xe.addEventListener("blur",Un),Wt._cleanupTooltip=()=>{Un(),Wt&&(Wt.removeEventListener("mouseenter",hn),Wt.removeEventListener("mouseleave",Un)),Xe&&(Xe.removeEventListener("focus",hn),Xe.removeEventListener("blur",Un))}}}}let dn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[xl],lr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[fa.message,fa.messageAndClick];T=wl({parsers:dn,handlers:lr,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Le=Um(r,T,ne),_.updateConfig(r),ao(Qe,_.getMessages(),Le),Vo(),I(),w(_.isStreaming());let Zn=((Yd=r.voiceRecognition)==null?void 0:Yd.enabled)===!0,ko=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Lo=((ep=(Zd=r.voiceRecognition)==null?void 0:Zd.provider)==null?void 0:ep.type)==="runtype";if(Zn&&(ko||Lo))if(!j||!At){let ee=ng(r.voiceRecognition,r.sendButton);ee&&(j=ee.micButton,At=ee.micButtonWrapper,rt.insertBefore(At,nt),j.addEventListener("click",Ba),j.disabled=_.isStreaming())}else{let ee=(tp=r.voiceRecognition)!=null?tp:{},kt=(np=r.sendButton)!=null?np:{},Qt=(rp=ee.iconName)!=null?rp:"mic",ct=(op=kt.size)!=null?op:"40px",Rt=(sp=ee.iconSize)!=null?sp:ct,fn=parseFloat(Rt)||24;j.style.width=Rt,j.style.height=Rt,j.style.minWidth=Rt,j.style.minHeight=Rt;let Mn=(ip=(ap=ee.iconColor)!=null?ap:kt.textColor)!=null?ip:"currentColor";j.innerHTML="";let hr=Ae(Qt,fn,Mn,2);hr?j.appendChild(hr):j.textContent="\u{1F3A4}";let Nn=(lp=ee.backgroundColor)!=null?lp:kt.backgroundColor;Nn?j.style.backgroundColor=Nn:j.style.backgroundColor="",Mn?j.style.color=Mn:j.style.color="var(--persona-text, #111827)",ee.borderWidth?(j.style.borderWidth=ee.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),ee.borderColor?j.style.borderColor=ee.borderColor:j.style.borderColor="",ee.paddingX?(j.style.paddingLeft=ee.paddingX,j.style.paddingRight=ee.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),ee.paddingY?(j.style.paddingTop=ee.paddingY,j.style.paddingBottom=ee.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let tn=At==null?void 0:At.querySelector(".persona-send-button-tooltip"),er=(cp=ee.tooltipText)!=null?cp:"Start voice recognition";if(((dp=ee.showTooltip)!=null?dp:!1)&&er)if(tn)tn.textContent=er,tn.style.display="";else{let hn=document.createElement("div");hn.className="persona-send-button-tooltip",hn.textContent=er,At==null||At.insertBefore(hn,j)}else tn&&(tn.style.display="none");At.style.display="",j.disabled=_.isStreaming()}else j&&At&&(At.style.display="none",((up=(pp=r.voiceRecognition)==null?void 0:pp.provider)==null?void 0:up.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():ln&&po());if(((mp=r.attachments)==null?void 0:mp.enabled)===!0)if(!ue||!ce){let ee=(gp=r.attachments)!=null?gp:{},Qt=(hp=((fp=r.sendButton)!=null?fp:{}).size)!=null?hp:"40px";pt||(pt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),pt.style.display="none",Dt.insertBefore(pt,Ie)),Te||(Te=document.createElement("input"),Te.type="file",Te.accept=((bp=ee.allowedTypes)!=null?bp:Gr).join(","),Te.multiple=((yp=ee.maxFiles)!=null?yp:4)>1,Te.style.display="none",Te.setAttribute("aria-label","Attach files"),Dt.insertBefore(Te,Ie)),ue=y("div","persona-send-button-wrapper"),ce=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ce.type="button",ce.setAttribute("aria-label",(vp=ee.buttonTooltipText)!=null?vp:"Attach file");let ct=(xp=ee.buttonIconName)!=null?xp:"paperclip",Rt=Qt,fn=parseFloat(Rt)||40,Mn=Math.round(fn*.6);ce.style.width=Rt,ce.style.height=Rt,ce.style.minWidth=Rt,ce.style.minHeight=Rt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.style.backgroundColor="transparent",ce.style.color="var(--persona-primary, #111827)",ce.style.border="none",ce.style.borderRadius="6px",ce.style.transition="background-color 0.15s ease",ce.addEventListener("mouseenter",()=>{ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ce.addEventListener("mouseleave",()=>{ce.style.backgroundColor="transparent"});let hr=Ae(ct,Mn,"currentColor",1.5);hr?ce.appendChild(hr):ce.textContent="\u{1F4CE}",ce.addEventListener("click",er=>{er.preventDefault(),Te==null||Te.click()}),ue.appendChild(ce);let Nn=(wp=ee.buttonTooltipText)!=null?wp:"Attach file",tn=y("div","persona-send-button-tooltip");tn.textContent=Nn,ue.appendChild(tn),dt.append(ue),!wt&&Te&&pt&&(wt=ta.fromConfig(ee),wt.setPreviewsContainer(pt),Te.addEventListener("change",async()=>{wt&&(Te!=null&&Te.files)&&(await wt.handleFileSelect(Te.files),Te.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(zm(ee.dropOverlay))}else{ue.style.display="";let ee=(Cp=r.attachments)!=null?Cp:{};Te&&(Te.accept=((Ap=ee.allowedTypes)!=null?Ap:Gr).join(","),Te.multiple=((Sp=ee.maxFiles)!=null?Sp:4)>1),wt&&wt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else ue&&(ue.style.display="none"),wt&&wt.clearAttachments(),(Tp=pe.querySelector(".persona-attachment-drop-overlay"))==null||Tp.remove();let Jt=(Ep=r.sendButton)!=null?Ep:{},Io=(Mp=Jt.useIcon)!=null?Mp:!1,mo=(kp=Jt.iconText)!=null?kp:"\u2191",go=Jt.iconName,Vr=(Lp=Jt.tooltipText)!=null?Lp:"Send message",Po=(Ip=Jt.showTooltip)!=null?Ip:!1,fr=(Pp=Jt.size)!=null?Pp:"40px",Ye=Jt.backgroundColor,gn=Jt.textColor;if(Io){if(qe.style.width=fr,qe.style.height=fr,qe.style.minWidth=fr,qe.style.minHeight=fr,qe.style.fontSize="18px",qe.style.lineHeight="1",qe.innerHTML="",gn?qe.style.color=gn:qe.style.color="var(--persona-button-primary-fg, #ffffff)",go){let ee=parseFloat(fr)||24,kt=(gn==null?void 0:gn.trim())||"currentColor",Qt=Ae(go,ee,kt,2);Qt?qe.appendChild(Qt):qe.textContent=mo}else qe.textContent=mo;qe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ye?(qe.style.backgroundColor=Ye,qe.classList.remove("persona-bg-persona-primary")):(qe.style.backgroundColor="",qe.classList.add("persona-bg-persona-primary"))}else qe.textContent=(Rp=(Wp=r.copy)==null?void 0:Wp.sendButtonLabel)!=null?Rp:"Send",qe.style.width="",qe.style.height="",qe.style.minWidth="",qe.style.minHeight="",qe.style.fontSize="",qe.style.lineHeight="",qe.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",Ye?(qe.style.backgroundColor=Ye,qe.classList.remove("persona-bg-persona-accent")):qe.classList.add("persona-bg-persona-accent"),gn?qe.style.color=gn:qe.classList.add("persona-text-white");Jt.borderWidth?(qe.style.borderWidth=Jt.borderWidth,qe.style.borderStyle="solid"):(qe.style.borderWidth="",qe.style.borderStyle=""),Jt.borderColor?qe.style.borderColor=Jt.borderColor:qe.style.borderColor="",Jt.paddingX?(qe.style.paddingLeft=Jt.paddingX,qe.style.paddingRight=Jt.paddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Jt.paddingY?(qe.style.paddingTop=Jt.paddingY,qe.style.paddingBottom=Jt.paddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let Vt=nt==null?void 0:nt.querySelector(".persona-send-button-tooltip");if(Po&&Vr)if(Vt)Vt.textContent=Vr,Vt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=Vr,nt==null||nt.insertBefore(ee,qe)}else Vt&&(Vt.style.display="none");let jt=(Fp=(Bp=r.layout)==null?void 0:Bp.contentMaxWidth)!=null?Fp:D()?(Np=(Dp=(Hp=r.launcher)==null?void 0:Hp.composerBar)==null?void 0:Dp.contentMaxWidth)!=null?Np:"720px":void 0;jt?(Qe.style.maxWidth=jt,Qe.style.marginLeft="auto",Qe.style.marginRight="auto",Qe.style.width="100%",Dt&&(Dt.style.maxWidth=jt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Kt&&(Kt.style.maxWidth=jt,Kt.style.marginLeft="auto",Kt.style.marginRight="auto")):(Qe.style.maxWidth="",Qe.style.marginLeft="",Qe.style.marginRight="",Qe.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),Kt&&(Kt.style.maxWidth="",Kt.style.marginLeft="",Kt.style.marginRight=""));let bt=(_p=r.statusIndicator)!=null?_p:{},Yt=(Op=bt.visible)!=null?Op:!0;if(bn.style.display=Yt?"":"none",_){let ee=_.getStatus();st(bn,(Qt=>{var ct,Rt,fn,Mn;return Qt==="idle"?(ct=bt.idleText)!=null?ct:kn.idle:Qt==="connecting"?(Rt=bt.connectingText)!=null?Rt:kn.connecting:Qt==="connected"?(fn=bt.connectedText)!=null?fn:kn.connected:Qt==="error"?(Mn=bt.errorText)!=null?Mn:kn.error:kn[Qt]})(ee),bt,ee)}bn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Tt=bt.align==="left"?"persona-text-left":bt.align==="center"?"persona-text-center":"persona-text-right";bn.classList.add(Tt)},open(){N()&&he(!0,"api")},close(){N()&&he(!1,"api")},toggle(){N()&&he(!M,"api")},clearChat(){Wn=!1,_.clearMessages(),kr.clear(),Pr();try{localStorage.removeItem(ws),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ws}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ws)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={},T.syncFromMetadata(),ge==null||ge.clear(),de==null||de.reset(),V==null||V.update()},setMessage(l){return!Ie||_.isStreaming()?!1:(!M&&N()&&he(!0,"system"),Ie.value=l,Ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Ie.value.trim();return p?(!M&&N()&&he(!0,"system"),Ie.value="",Ie.style.height="auto",_.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return _.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!M&&N()&&he(!0,"system"),yt.manuallyDeactivated=!1,$n(),_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("user"),_.isVoiceActive()&&ts()})),!0):ln?!0:Ll()?(!M&&N()&&he(!0,"system"),yt.manuallyDeactivated=!1,$n(),Wa("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),ar("user"),jr()}),!0):!1:ln?(yt.manuallyDeactivated=!0,$n(),po("user"),!0):!1},injectMessage(l){return!M&&N()&&he(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!M&&N()&&he(!0,"system");let p=_.injectAssistantMessage(l);return U&&(U=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(l){return!M&&N()&&he(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!M&&N()&&he(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!M&&N()&&he(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!M&&N()&&he(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!M&&N()&&he(!0,"system"),_.injectTestEvent(l)},async connectStream(l,p){return _.connectStream(l,p)},__pushEventStreamEvent(l){ge&&(de==null||de.processEvent(l.type,l.payload),ge.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!De||!ge||Dr()},hideEventStream(){se&&pr()},isEventStreamVisible(){return se},showArtifacts(){dr(r)&&(Wn=!1,Qn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){dr(r)&&(Wn=!0,Qn())},upsertArtifact(l){return dr(r)?(Wn=!1,_.upsertArtifact(l)):null},selectArtifact(l){dr(r)&&_.selectArtifact(l)},clearArtifacts(){dr(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return E&&!M&&!D()||!Ie?!1:(Ie.focus(),!0)},async resolveApproval(l,p,h){let S=_.getMessages().find(H=>{var q;return H.variant==="approval"&&((q=H.approval)==null?void 0:q.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){_.resolveWebMcpApproval(S.id,p);return}return _.resolveApproval(S.approval,p,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){m(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return N()&&M},isVoiceActive(){return yt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:N()&&M,launcherEnabled:E,voiceActive:yt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!M&&N()&&he(!0,"system");let p=Qe.querySelector(".persona-feedback-container");p&&p.remove();let h=Om({onSubmit:async(b,S)=>{var H;_.isClientTokenMode()&&await _.submitCSATFeedback(b,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!M&&N()&&he(!0,"system");let p=Qe.querySelector(".persona-feedback-container");p&&p.remove();let h=$m({onSubmit:async(b,S)=>{var H;_.isClientTokenMode()&&await _.submitNPSFeedback(b,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Qe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return _.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return _.submitNPSFeedback(l,p)},destroy(){K!=null&&(clearInterval(K),K=null),mt.forEach(l=>l()),Ee.remove(),Ke==null||Ke.remove(),rn==null||rn.destroy(),mn==null||mn.remove(),Er&&Ve.removeEventListener("click",Er)}};if((((Dc=e==null?void 0:e.debugTools)!=null?Dc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:cn,getMessages:cn.getMessages,getStatus:cn.getStatus,getMetadata:cn.getPersistentMetadata,updateMetadata:cn.updatePersistentMetadata,clearHistory:()=>cn.clearChat(),setVoiceActive:h=>h?cn.startVoiceRecognition():cn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,mt.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 B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",p),mt.push(()=>{window.removeEventListener("persona:focusInput",p)}),De){let F=ie=>{let le=ie.detail;(!(le!=null&&le.instanceId)||le.instanceId===l)&&cn.showEventStream()},B=ie=>{let le=ie.detail;(!(le!=null&&le.instanceId)||le.instanceId===l)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",B),mt.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",B)})}let h=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&cn.showArtifacts()},b=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&cn.hideArtifacts()},S=F=>{let B=F.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&cn.upsertArtifact(B.artifact)},H=F=>{let B=F.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&cn.selectArtifact(B.id)},q=F=>{let B=F.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",H),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",H),window.removeEventListener("persona:clearArtifacts",q)})}let ir=gv(r.persistState);if(ir&&N()){let l=fv(ir.storage),p=`${ir.keyPrefix}widget-open`,h=`${ir.keyPrefix}widget-voice`,b=`${ir.keyPrefix}widget-voice-mode`;if(l){let S=((Nc=ir.persist)==null?void 0:Nc.openState)&&l.getItem(p)==="true",H=((Fc=ir.persist)==null?void 0:Fc.voiceState)&&l.getItem(h)==="true",q=((_c=ir.persist)==null?void 0:_c.voiceState)&&l.getItem(b)==="true";if(S&&setTimeout(()=>{cn.open(),setTimeout(()=>{var F;if(H||q)cn.startVoiceRecognition();else if((F=ir.persist)!=null&&F.focusInput){let B=n.querySelector("textarea");B&&B.focus()}},100)},0),(Oc=ir.persist)!=null&&Oc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),($c=ir.persist)!=null&&$c.voiceState&&(s.on("voice:state",F=>{l.setItem(h,F.active?"true":"false")}),s.on("user:message",F=>{l.setItem(b,F.viaVoice?"true":"false")})),ir.clearOnChatClear){let F=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(b)},B=()=>F();window.addEventListener("persona:clear-chat",B),mt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return g&&N()&&setTimeout(()=>{cn.open()},0),zr(),ba||jp().then(()=>{_&&(Ko++,kr.clear(),ao(Qe,_.getMessages(),Le))}).catch(()=>{}),cn};var hv=(n,t)=>{let e=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(e);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(e);return o?Math.max(0,t*parseFloat(o[1])/100):420},bv=(n,t)=>{if(t===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=t},yv=(n,t)=>{t===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},vv=(n,t)=>{let e=n.parentElement;if(!e)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",e.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."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Vm=(n,t)=>{var r,o;let e=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=e?"":"100%",n.style.display=e?"":"flex",n.style.flexDirection=e?"":"column",n.style.flex=e?"":"1 1 auto",n.style.minHeight=e?"":"0"},El=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=""},Km=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",El(n)},Al=n=>{n.style.transition=""},Sl=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=""},Tl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},ki=(n,t)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",t.style.alignItems=""},xv=(n,t,e,r,o)=>{o?e.parentElement!==t&&(n.replaceChildren(),t.replaceChildren(e,r),n.appendChild(t)):e.parentElement===t&&(t.replaceChildren(),n.appendChild(e),n.appendChild(r))},wv=(n,t,e,r,o,s)=>{let a=s?t:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,e):a.lastElementChild!==r&&a.replaceChildren(e,r)},Gm=(n,t,e,r,o,s,a)=>{var v,x,T,E,A,R;let i=yr(s),d=i.reveal==="push";xv(n,t,e,r,d),wv(n,t,e,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",e.style.display="flex",e.style.flexDirection="column",e.style.minHeight="0",e.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,g=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(E=(T=s==null?void 0:s.launcher)==null?void 0:T.mobileBreakpoint)!=null?E:640,u=c!=null?c.innerWidth<=f:!1;if(g&&u&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),Sl(t),Al(r),Km(r),Tl(e),ki(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",e.style.flex="1 1 auto",e.style.width="100%",e.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((R=(A=s==null?void 0:s.launcher)==null?void 0:A.zIndex)!=null?R:Ln),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",e.style.flex="1 1 auto",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),Km(r),bv(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",Sl(t),Al(r),Tl(e),ki(o,r);let L=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=L,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",Al(r),El(r),ki(o,r);let L=hv(i.width,n.clientWidth),W=Math.max(0,n.clientWidth),C=i.animate?"margin-left 180ms ease":"none",k=i.side==="right"?a?-L:0:a?0:-L;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${W+L}px`,t.style.transition=C,t.style.marginLeft=`${k}px`,t.style.transform="",e.style.flex="0 0 auto",e.style.flexGrow="0",e.style.flexShrink="0",e.style.width=`${W}px`,e.style.maxWidth=`${W}px`,e.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="",Sl(t),El(r),Tl(e),ki(o,r);let L=i.reveal==="emerge";L?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",k=!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",yv(r,i.maxHeight),r.style.overflow=L||k?"hidden":"visible",r.style.transition=C,L&&(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")}},Cv=(n,t)=>{let e=n.ownerDocument.createElement("div");return Vm(e,t),n.appendChild(e),{mode:"direct",host:e,shell:null,syncWidgetState:()=>{},updateConfig(r){Vm(e,r)},destroy(){e.remove()}}},Av=(n,t)=>{var R,L,W,C;let{ownerDocument:e}=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=e.createElement("div"),i=e.createElement("div"),d=e.createElement("div"),c=e.createElement("aside"),g=e.createElement("div"),f=(L=(R=t==null?void 0:t.launcher)==null?void 0:R.enabled)==null||L?(C=(W=t==null?void 0:t.launcher)==null?void 0:W.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",c.appendChild(g),r.insertBefore(a,n),d.appendChild(n);let u=null,m=()=>{u==null||u.disconnect(),u=null},v=()=>{m(),yr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{Gm(a,i,d,c,g,t,f)}),u.observe(a))},x=!1,T=()=>{Gm(a,i,d,c,g,t,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,vv(a,yr(t)))},E=a.ownerDocument.defaultView,A=()=>{T()};return E==null||E.addEventListener("resize",A),yr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),T(),{mode:"docked",host:g,shell:a,syncWidgetState(k){let D=k.launcherEnabled?k.open:!0;f!==D&&(f=D,T())},updateConfig(k){var D,N;t=k,((N=(D=t==null?void 0:t.launcher)==null?void 0:D.enabled)!=null?N:!0)===!1&&(f=!0),T()},destroy(){E==null||E.removeEventListener("resize",A),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},Qm=(n,t)=>Cn(t)?Av(n,t):Cv(n,t);var ha={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Xm=.15,Jm=1.5,Ml="persona-preview-shell-theme",Sv={load:()=>null,save:()=>{},clear:()=>{}},Tv=["How do I get started?","Pricing & plans","Talk to support"];function kl(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ev(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 Ym(n){let t=Ev(n);return`* { box-sizing: border-box; }
110
110
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
111
111
  html { color-scheme: ${n}; }
112
- body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
112
+ body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
113
113
  .preview-iframe-mock { min-height: 100%; }
114
- .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
115
- .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${e.dot}; }
114
+ .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
115
+ .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${t.dot}; }
116
116
  .preview-iframe-copy { padding: 32px; }
117
- .preview-iframe-line { border-radius: 999px; background: ${e.skeleton}; margin-bottom: 12px; }
117
+ .preview-iframe-line { border-radius: 999px; background: ${t.skeleton}; margin-bottom: 12px; }
118
118
  .preview-iframe-line.hero { width: 48%; height: 16px; }
119
119
  .preview-iframe-line.body { width: 72%; height: 10px; }
120
120
  .preview-iframe-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 24px 0; }
121
- .preview-iframe-card { height: 84px; border-radius: 14px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
121
+ .preview-iframe-card { height: 84px; border-radius: 14px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
122
122
  .preview-workspace-shell { height: 100%; min-height: 100%; display: flex; flex-direction: column; }
123
- .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
123
+ .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
124
124
  .preview-workspace-topbar-left { display: flex; align-items: center; gap: 12px; }
125
- .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
126
- .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${e.skeleton}; }
127
- .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
125
+ .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
126
+ .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${t.skeleton}; }
127
+ .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
128
128
  .preview-workspace-body { flex: 1; min-height: 0; display: flex; padding: 20px; }
129
- .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
129
+ .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
130
130
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
131
131
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
132
- .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}; }
133
- .preview-workspace-card.short { height: 96px; }`}function Gm(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=Km(e)}var wv=`
132
+ .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
133
+ .preview-workspace-card.short { height: 96px; }`}function Zm(n,t){let e=n.contentDocument;if(!(e!=null&&e.documentElement))return;let r=e.getElementById(Ml);r||(r=e.createElement("style"),r.id=Ml,e.head.appendChild(r)),r.textContent=Ym(t)}var Mv=`
134
134
  <div class="preview-iframe-mock" aria-hidden="true">
135
135
  <div class="preview-iframe-chrome">
136
136
  <span class="preview-iframe-dot"></span>
@@ -149,7 +149,7 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
149
149
  <div class="preview-iframe-line body"></div>
150
150
  <div class="preview-iframe-line body"></div>
151
151
  </div>
152
- </div>`,Cv=`
152
+ </div>`,kv=`
153
153
  <div class="preview-workspace-content-shell" aria-hidden="true">
154
154
  <div class="preview-iframe-line hero"></div>
155
155
  <div class="preview-iframe-line body"></div>
@@ -162,8 +162,8 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
162
162
  <div class="preview-workspace-card short"></div>
163
163
  <div class="preview-workspace-card short"></div>
164
164
  </div>
165
- </div>`;function Qm(n,e,t,r){let o=`
166
- ${wv}
165
+ </div>`;function eg(n,t,e,r){let o=`
166
+ ${Mv}
167
167
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
168
168
  <div class="preview-workspace-shell">
169
169
  <div class="preview-workspace-topbar">
@@ -175,7 +175,7 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
175
175
  </div>
176
176
  <div class="preview-workspace-body">
177
177
  <div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
178
- ${Cv}
178
+ ${kv}
179
179
  </div>
180
180
  </div>
181
181
  </div>`;return`<!DOCTYPE html>
@@ -183,16 +183,16 @@ _Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]
183
183
  <head>
184
184
  <meta charset="UTF-8">
185
185
  <meta name="viewport" content="width=device-width, initial-scale=1">
186
- <link rel="stylesheet" href="${Tl(r)}">
187
- <style id="${Sl}">${Km(e)}</style>
186
+ <link rel="stylesheet" href="${kl(r)}">
187
+ <style id="${Ml}">${Ym(t)}</style>
188
188
  </head>
189
189
  <body>
190
- ${t?s:o}
190
+ ${e?s:o}
191
191
  </body>
192
- </html>`}var Av=()=>[{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()}],Sv=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 Tv(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"&&Sv(e)?[...Av(),...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 Mv(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:vv:n.suggestionChips,initialMessages:Tv(e,n,t),storageAdapter:bv};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Ev(n,e){var r,o;let t=n.theme?_o(n.theme,{validate:!1}):_o();return{...Ot,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function As(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Mv(Ev(n,e),t,(o=n.appendedMessages)!=null?o:[])}function Xm(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:As(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:As(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:As(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:As(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:As(n,t),shellMode:t}]}function kv(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function g(){var k;return(k=t.device)!=null?k:"desktop"}function f(){var k;return(k=t.zoom)!=null?k:i}function u(){var T,q;let k=getComputedStyle(n),N=parseFloat(k.paddingLeft)+parseFloat(k.paddingRight),P=parseFloat(k.paddingTop)+parseFloat(k.paddingBottom),W=40,C=((T=t.compareMode)!=null?T:"off")!=="off",I=(n.clientWidth-N-W)/(C?2:1),B=n.clientHeight-P-W;if(I<=0||B<=0)return 1;let D=(q=ha[g()])!=null?q:ha.desktop;return Math.min(I/D.w,B/D.h,1)}function m(){var P,W,C;i=u();let k=Math.max(Vm,Math.min(jm,f()));d=k;let N=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let I of N){let B=(P=I.dataset.device)!=null?P:"desktop",D=(W=ha[B])!=null?W:ha.desktop;I.style.width=`${D.w*k}px`,I.style.height=`${D.h*k}px`,B==="mobile"&&(I.style.borderRadius=`${32*k}px`);let T=I.querySelector("iframe");T&&(T.style.width=`${D.w}px`,T.style.height=`${D.h}px`,T.style.transformOrigin="top left",T.style.transition="none",T.style.transform=`scale(${k})`)}(C=t.onScaleChange)==null||C.call(t,k)}function v(){var k;(k=t.onBeforeDestroy)==null||k.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 M(){var be,He,Fe,Se;if(a)return;v();let k=++c,N=Xm(t),P=g(),W=((be=t.compareMode)!=null?be:"off")!=="off",C=((He=t.scene)!=null?He:"conversation")==="minimized",I=(Fe=t.widgetCssPath)!=null?Fe:"/widget-dist/widget.css",B=(Se=t.buildSrcdoc)!=null?Se:Qm,D=P==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",T=xe=>`<div class="${D}" data-mount-id="${xe.mountId}" data-device="${P}" data-shell-mode="${xe.shellMode}">
193
- ${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${Tl(xe.label)}</span></div>`:""}
192
+ </html>`}var Lv=()=>[{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()}],Iv=n=>{var t,e,r,o,s,a,i,d;return!!((e=(t=n==null?void 0:n.features)==null?void 0:t.toolCallDisplay)!=null&&e.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 Pv(n,t,e=[]){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"&&Iv(t)?[...Lv(),...e]:[{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()},...e]}function Wv(n,t,e=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:t!=="minimized"},o={...n,launcher:r,suggestionChips:t==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:Tv:n.suggestionChips,initialMessages:Pv(t,n,e),storageAdapter:Sv};return t==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Rv(n,t){var r,o;let e=n.theme?Oo(n.theme,{validate:!1}):Oo();return{...Ut,...n.config,theme:e,darkTheme:n.darkTheme,colorScheme:(o=t!=null?t:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function Cs(n,t){var r,o;let e=(r=n.scene)!=null?r:"conversation";return Wv(Rv(n,t),e,(o=n.appendedMessages)!=null?o:[])}function tg(n){var r,o,s,a,i;let t=(r=n.compareMode)!=null?r:"off",e=(o=n.shellMode)!=null?o:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Cs(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Cs(n,"dark"),shellMode:"dark"}];if(t==="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:Cs(d,e),shellMode:e},{mountId:"preview-current",label:"Current",config:Cs(n,e),shellMode:e}]}return[{mountId:"preview-current",label:"Current",config:Cs(n,e),shellMode:e}]}function Bv(n,t){let e={...t},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function g(){var A;return(A=e.device)!=null?A:"desktop"}function f(){var A;return(A=e.zoom)!=null?A:i}function u(){var M,U;let A=getComputedStyle(n),R=parseFloat(A.paddingLeft)+parseFloat(A.paddingRight),L=parseFloat(A.paddingTop)+parseFloat(A.paddingBottom),W=40,C=((M=e.compareMode)!=null?M:"off")!=="off",k=(n.clientWidth-R-W)/(C?2:1),D=n.clientHeight-L-W;if(k<=0||D<=0)return 1;let N=(U=ha[g()])!=null?U:ha.desktop;return Math.min(k/N.w,D/N.h,1)}function m(){var L,W,C;i=u();let A=Math.max(Xm,Math.min(Jm,f()));d=A;let R=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let k of R){let D=(L=k.dataset.device)!=null?L:"desktop",N=(W=ha[D])!=null?W:ha.desktop;k.style.width=`${N.w*A}px`,k.style.height=`${N.h*A}px`,D==="mobile"&&(k.style.borderRadius=`${32*A}px`);let M=k.querySelector("iframe");M&&(M.style.width=`${N.w}px`,M.style.height=`${N.h}px`,M.style.transformOrigin="top left",M.style.transition="none",M.style.transform=`scale(${A})`)}(C=e.onScaleChange)==null||C.call(e,A)}function v(){var A;(A=e.onBeforeDestroy)==null||A.call(e);for(let R of r)R.destroy();for(let R of o)R();r=[],o=[]}function x(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function T(){var ye,De,$e,Se;if(a)return;v();let A=++c,R=tg(e),L=g(),W=((ye=e.compareMode)!=null?ye:"off")!=="off",C=((De=e.scene)!=null?De:"conversation")==="minimized",k=($e=e.widgetCssPath)!=null?$e:"/widget-dist/widget.css",D=(Se=e.buildSrcdoc)!=null?Se:eg,N=L==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",M=xe=>`<div class="${N}" data-mount-id="${xe.mountId}" data-device="${L}" data-shell-mode="${xe.shellMode}">
193
+ ${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${kl(xe.label)}</span></div>`:""}
194
194
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${xe.mountId}"></iframe>
195
- </div>`,q=W?`<div class="preview-compare-grid">${N.map(xe=>`<div class="preview-compare-cell">${T(xe)}</div>`).join("")}</div>`:`<div class="preview-single">${T(N[0])}</div>`;t.morphContainer?t.morphContainer(n,q):n.innerHTML=q,m();let z=x(),re=0,ke=z.length,Ve=()=>{var oe,G,se,ge,pe;if(a||k!==c)return;for(let j of z){let ae=j.dataset.mountId;if(!ae||!j.contentDocument)continue;let Ie=N.find(it=>it.mountId===ae);if(!Ie)continue;let ee=()=>{},Z=wn(Ie.config),ne=Z?(()=>{var J;let it=(J=j.contentDocument)==null?void 0:J.getElementById(`preview-content-${ae}`);if(!it)return null;let ot=zm(it,Ie.config),Me=j.contentDocument.createElement("div");Me.id=ae,Me.style.height="100%",Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1",Me.style.minHeight="0",ot.host.appendChild(Me);let fe=()=>ot.syncWidgetState(at.getState()),Xe=ee;return ee=()=>{ot.destroy(),Xe()},Me.__syncDock=fe,Me.__hostLayout=ot,Me})():j.contentDocument.getElementById(ae);if(!ne)continue;let at=_m(ne,Ie.config);if(r.push(at),Z&&ne.__syncDock){let it=ne.__syncDock,ot=at.on("widget:opened",it),Me=at.on("widget:closed",it),fe=ee;ee=()=>{ot(),Me(),fe()},it()}o.push(ee),C&&at.close()}if(((oe=t.scene)!=null?oe:"conversation")==="artifact"||(ge=(se=(G=t.config)==null?void 0:G.features)==null?void 0:se.artifacts)!=null&&ge.enabled)for(let j of r)j.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
195
+ </div>`,U=W?`<div class="preview-compare-grid">${R.map(xe=>`<div class="preview-compare-cell">${M(xe)}</div>`).join("")}</div>`:`<div class="preview-single">${M(R[0])}</div>`;e.morphContainer?e.morphContainer(n,U):n.innerHTML=U,m();let z=x(),ne=0,Le=z.length,je=()=>{var re,Q,oe,ge,de;if(a||A!==c)return;for(let V of z){let se=V.dataset.mountId;if(!se||!V.contentDocument)continue;let Re=R.find(st=>st.mountId===se);if(!Re)continue;let Z=()=>{},Y=Cn(Re.config),te=Y?(()=>{var X;let st=(X=V.contentDocument)==null?void 0:X.getElementById(`preview-content-${se}`);if(!st)return null;let tt=Qm(st,Re.config),Ee=V.contentDocument.createElement("div");Ee.id=se,Ee.style.height="100%",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1",Ee.style.minHeight="0",tt.host.appendChild(Ee);let fe=()=>tt.syncWidgetState(ot.getState()),Ke=Z;return Z=()=>{tt.destroy(),Ke()},Ee.__syncDock=fe,Ee.__hostLayout=tt,Ee})():V.contentDocument.getElementById(se);if(!te)continue;let ot=jm(te,Re.config);if(r.push(ot),Y&&te.__syncDock){let st=te.__syncDock,tt=ot.on("widget:opened",st),Ee=ot.on("widget:closed",st),fe=Z;Z=()=>{tt(),Ee(),fe()},st()}o.push(Z),C&&ot.close()}if(((re=e.scene)!=null?re:"conversation")==="artifact"||(ge=(oe=(Q=e.config)==null?void 0:Q.features)==null?void 0:oe.artifacts)!=null&&ge.enabled)for(let V of r)V.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
196
196
 
197
197
  This is a preview of the artifact sidebar.
198
198
 
@@ -200,4 +200,4 @@ This is a preview of the artifact sidebar.
200
200
 
201
201
  - Markdown rendering
202
202
  - Document toolbar
203
- - Resizable panes`});(pe=t.onAfterMount)==null||pe.call(t,{iframes:z,controllers:[...r]})};for(let xe of z){let oe=xe.dataset.mountId;if(!oe)continue;let G=N.find(se=>se.mountId===oe);G&&(xe.addEventListener("load",()=>{re++,re>=ke&&Ve()},{once:!0}),xe.srcdoc=B(oe,G.shellMode,wn(G.config),I))}ke===0&&Ve()}function E(){var P;if(a)return;let k=Xm(t);if(r.length!==k.length){M();return}if(k.some(W=>{let C=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!C||C.dataset.shellMode!==W.shellMode})){M();return}r.forEach((W,C)=>{var I;W.update(k[C].config),((I=t.scene)!=null?I:"conversation")==="minimized"&&W.close()});for(let W of k){let C=n.querySelector(`iframe[data-mount-id="${W.mountId}"]`);C&&Gm(C,W.shellMode)}(P=t.onAfterUpdate)==null||P.call(t,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),M(),{update(k){if(a)return;let N=k.device!==void 0&&k.device!==t.device||k.scene!==void 0&&k.scene!==t.scene||k.compareMode!==void 0&&k.compareMode!==t.compareMode||k.widgetCssPath!==void 0&&k.widgetCssPath!==t.widgetCssPath;t={...t,...k},N?M():E()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(k){a||(t={...t,zoom:k},m())}}}export{kv as createThemePreview};
203
+ - Resizable panes`});(de=e.onAfterMount)==null||de.call(e,{iframes:z,controllers:[...r]})};for(let xe of z){let re=xe.dataset.mountId;if(!re)continue;let Q=R.find(oe=>oe.mountId===re);Q&&(xe.addEventListener("load",()=>{ne++,ne>=Le&&je()},{once:!0}),xe.srcdoc=D(re,Q.shellMode,Cn(Q.config),k))}Le===0&&je()}function E(){var L;if(a)return;let A=tg(e);if(r.length!==A.length){T();return}if(A.some(W=>{let C=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!C||C.dataset.shellMode!==W.shellMode})){T();return}r.forEach((W,C)=>{var k;W.update(A[C].config),((k=e.scene)!=null?k:"conversation")==="minimized"&&W.close()});for(let W of A){let C=n.querySelector(`iframe[data-mount-id="${W.mountId}"]`);C&&Zm(C,W.shellMode)}(L=e.onAfterUpdate)==null||L.call(e,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),T(),{update(A){if(a)return;let R=A.device!==void 0&&A.device!==e.device||A.scene!==void 0&&A.scene!==e.scene||A.compareMode!==void 0&&A.compareMode!==e.compareMode||A.widgetCssPath!==void 0&&A.widgetCssPath!==e.widgetCssPath;e={...e,...A},R?T():E()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(e={...e,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(A){a||(e={...e,zoom:A},m())}}}export{Bv as createThemePreview};