@runtypelabs/persona 4.4.2 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,22 +1,22 @@
1
- var If=Object.defineProperty;var _s=(e,t)=>()=>(e&&(t=e(e=0)),t);var bu=(e,t)=>{for(var n in t)If(e,n,{get:t[n],enumerable:!0})};var xu={};bu(xu,{DOMPurify:()=>Wf,Marked:()=>Rf});import{Marked as Rf}from"marked";import Wf from"dompurify";var vu=_s(()=>{"use strict"});var ys,tl=_s(()=>{"use strict";ys=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Zh(e){return e.replace(/\/+$/,"")}async function ey(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var za,fm=_s(()=>{"use strict";tl();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,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new ys(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;t===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;t===this.generation&&((g=r.onEnd)==null||g.call(r))});let l=`${Zh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await ey(p));let u=p.body.getReader();for(;;){let{done:g,value:f}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let l=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,l),(i=r.onError)==null||i.call(r,l)}}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 Va,hm=_s(()=>{"use strict";Va=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var ym={};bu(ym,{FallbackSpeechEngine:()=>Va,RuntypeSpeechEngine:()=>za});var bm=_s(()=>{"use strict";fm();hm()});import{Marked as Hf}from"marked";import Bf from"dompurify";var wu=null,ps=null,ds=null;var Cu=e=>{ps=e},Au=()=>ps?Promise.resolve(ps):ds||(wu?(ds=wu().then(e=>(ps=e,e)),ds):(ds=Promise.resolve().then(()=>(vu(),xu)).then(e=>(ps=e,e)),ds)),No=()=>ps;Cu({Marked:Hf,DOMPurify:Bf});var Df=e=>{if(e)return e},ka=e=>{let t=null;return n=>{var o,s;let r=No();if(!r)return Vr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.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=Df(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},us=e=>e?ka({markedOptions:e.options,renderer:e.renderer}):ka(),Nf=ka(),Tu=e=>Nf(e),Vr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Eu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Su=e=>`%%FORM_PLACEHOLDER_${e}%%`,Mu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Su(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Su(t.length);return t.push({token:s,type:o}),s}),n},Of=e=>{let t=us(e);return n=>{let r=[],o=Mu(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Eu(i)}"></div>`;s=s.replace(d,p)}),s}},Ff=e=>{let t=[],n=Mu(e,t),r=Tu(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Eu(s)}"></div>`;r=r.replace(a,d)}),r};var _f={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"]},$f=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ku=()=>{let e=null;return t=>{let n=No();if(!n)return Vr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!$f.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,_f)}},$s=e=>e===!1?null:typeof e=="function"?e:ku();var Lu=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Pu=e=>e.includes("|"),Iu=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},jf=e=>`| ${e.join(" | ")} |`,Uf=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,qf=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ru=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!Pu(o)||Lu.test(o)||!Lu.test(s))continue;let a=Iu(o).length;if(a<1)continue;let i=Uf(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let l=t[d];if(l.trim()===""||!Pu(l))break;let p=jf(qf(Iu(l),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
- `):e};var Rr="webmcp:",Fi=new Map,Wu=e=>{var t;Fi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Fi.set(n.name,r)}},Us=e=>Fi.get(_i(e)),La={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Hu=null;function Du(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${zf(t.join(""))}`}function Bu(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function zf(e){let t=Bu(e,0).toString(36),n=Bu(e,2654435761).toString(36);return`${t}.${n}`}var js=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(o){return La.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Wu(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Kf(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return gr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return gr(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=_i(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return gr(`Failed to read WebMCP registry: ${x}`)}Wu(a);let i=a.find(v=>v.name===s);if(!i)return gr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return gr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let d=Us(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return gr("User declined the tool call.");if(r!=null&&r.aborted)return gr("Aborted by cancel()");let p=new AbortController,u=!1,g=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),f=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",f,{once:!0}));try{let v=await o.executeTool(i,Qf(n),{signal:p.signal});return Gf(v)}catch(v){if(u)return gr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return gr(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Hu?await Hu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){La.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 n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,La.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 n=(r=this.confirmHandler)!=null?r:Jf;try{return await n(t)}catch(o){return La.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Vf(t,r))}},_i=e=>e.startsWith(Rr)?e.slice(Rr.length):e,Oo=e=>e.startsWith(Rr),Vf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Kf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Gf=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Yf(t)}]}},gr=e=>({isError:!0,content:[{type:"text",text:e}]}),Jf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Xf(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var Xf=Object.defineProperty;var Gs=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wu=(e,t)=>{for(var n in t)Xf(e,n,{get:t[n],enumerable:!0})};var Hu={};Wu(Hu,{DOMPurify:()=>Yf,Marked:()=>Qf});import{Marked as Qf}from"marked";import Yf from"dompurify";var Bu=Gs(()=>{"use strict"});var As,ll=Gs(()=>{"use strict";As=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function by(e){return e.replace(/\/+$/,"")}async function xy(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Xa,Pm=Gs(()=>{"use strict";ll();Xa=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,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new As(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;t===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;t===this.generation&&((g=r.onEnd)==null||g.call(r))});let l=`${by(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await xy(p));let u=p.body.getReader();for(;;){let{done:g,value:f}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let l=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,l),(i=r.onError)==null||i.call(r,l)}}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 Qa,Im=Gs(()=>{"use strict";Qa=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Rm={};Wu(Rm,{FallbackSpeechEngine:()=>Qa,RuntypeSpeechEngine:()=>Xa});var Wm=Gs(()=>{"use strict";Pm();Im()});import{Marked as Zf}from"marked";import eh from"dompurify";var Du=null,ys=null,hs=null;var Nu=e=>{ys=e},Ou=()=>ys?Promise.resolve(ys):hs||(Du?(hs=Du().then(e=>(ys=e,e)),hs):(hs=Promise.resolve().then(()=>(Bu(),Hu)).then(e=>(ys=e,e)),hs)),Vo=()=>ys;Nu({Marked:Zf,DOMPurify:eh});var th=e=>{if(e)return e},Wa=e=>{let t=null;return n=>{var o,s;let r=Vo();if(!r)return Yr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.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=th(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},bs=e=>e?Wa({markedOptions:e.options,renderer:e.renderer}):Wa(),nh=Wa(),_u=e=>nh(e),Yr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),$u=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Fu=e=>`%%FORM_PLACEHOLDER_${e}%%`,ju=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Fu(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Fu(t.length);return t.push({token:s,type:o}),s}),n},rh=e=>{let t=bs(e);return n=>{let r=[],o=ju(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${$u(i)}"></div>`;s=s.replace(d,p)}),s}},oh=e=>{let t=[],n=ju(e,t),r=_u(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${$u(s)}"></div>`;r=r.replace(a,d)}),r};var sh={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"]},ah=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Uu=()=>{let e=null;return t=>{let n=Vo();if(!n)return Yr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!ah.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,sh)}},Js=e=>e===!1?null:typeof e=="function"?e:Uu();var qu=/^\s*\|?[\s:|-]*-[\s:|-]*$/,zu=e=>e.includes("|"),Vu=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},ih=e=>`| ${e.join(" | ")} |`,lh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,ch=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ku=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!zu(o)||qu.test(o)||!qu.test(s))continue;let a=Vu(o).length;if(a<1)continue;let i=lh(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let l=t[d];if(l.trim()===""||!zu(l))break;let p=ih(ch(Vu(l),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
+ `):e};var Dr="webmcp:",Vi=new Map,Gu=e=>{var t;Vi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Vi.set(n.name,r)}},Qs=e=>Vi.get(Ki(e)),Ha={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Ju=null;function Qu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${dh(t.join(""))}`}function Xu(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function dh(e){let t=Xu(e,0).toString(36),n=Xu(e,2654435761).toString(36);return`${t}.${n}`}var Xs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(o){return Ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Gu(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=uh(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return hr(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=Ki(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return hr(`Failed to read WebMCP registry: ${x}`)}Gu(a);let i=a.find(v=>v.name===s);if(!i)return hr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return hr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d=Qs(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let p=new AbortController,u=!1,g=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),f=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",f,{once:!0}));try{let v=await o.executeTool(i,hh(n),{signal:p.signal});return mh(v)}catch(v){if(u)return hr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return hr(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Ju?await Ju():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:gh;try{return await n(t)}catch(o){return Ha.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>ph(t,r))}},Ki=e=>e.startsWith(Dr)?e.slice(Dr.length):e,Ko=e=>e.startsWith(Dr),ph=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},uh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},mh=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:yh(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),gh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=fh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
4
4
 
5
5
  Arguments:
6
6
  ${t}`:"")+(e.description?`
7
7
 
8
- ${e.description}`:"");return window.confirm(n)},Xf=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Qf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Yf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Zf="agent_",eh="flow_";function Nu(e){return e.startsWith(Zf)?{kind:"agentId",agentId:e}:e.startsWith(eh)?{kind:"flowId",flowId:e}:null}function Ou(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let l=Nu(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Nu(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as th,ARR as nh,OBJ as rh,STR as oh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var St=(e,t={},...n)=>{let r=document.createElement(e);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=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},qs=(...e)=>e.filter(Boolean).join(" ");var Pa="ask_user_question",zs=8,ms="data-persona-ask-sheet-for",sh="Other",ah="Other\u2026",_u="Type your own answer here",$u="Send",ih="Next",lh="Back",ch="Submit all",dh="Skip",ph=3,$i="data-ask-current-index",ji="data-ask-question-count",ju="data-ask-answers",Ui="data-ask-grouped",Uu="data-ask-layout",uh=e=>e.layout==="pills"?"pills":"rows",mh=e=>e.getAttribute(Uu)==="pills"?"pills":"rows",Fu=!1,qu=e=>e.replace(/["\\]/g,"\\$&"),po=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Pa,Ia=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},uo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=th(o,oh|rh|nh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Vs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>zs&&!Fu&&(Fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},gh=e=>{var t;return(t=Vs(e)[0])!=null?t:null},fh=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},zu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Vu=(e,t,n)=>{if(e!=="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(n+1),r.appendChild(o)}return r},hh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Vu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},yh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},bh=(e,t,n,r)=>{var p,u,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<ph;f++)s.appendChild(yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(hh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?sh:ah;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"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=t.freeTextPlaceholder)!=null?p:_u,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(E),v.appendChild(x);let T=Vu(r,a,d.length);T&&v.appendChild(T),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=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},Ku=(e,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=e.freeTextPlaceholder)!=null?s:_u,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=e.submitLabel)!=null?a:$u,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},xh=e=>{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 n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:$u,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},vh=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:lh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===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=(p=n.skipLabel)!=null?p:dh,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=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:ch:(g=n.nextLabel)!=null?g:ih,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Fo=e=>{let t=e.getAttribute(ju);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Gu=(e,t)=>{e.setAttribute(ju,JSON.stringify(t))},or=e=>{var n;let t=Number((n=e.getAttribute($i))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wh=(e,t)=>{e.setAttribute($i,String(Math.max(0,Math.floor(t))))},gs=e=>{var n;let t=Number((n=e.getAttribute(ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Ui)==="true",Ch=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="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(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Ah=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ra=(e,t)=>{let{payload:n}=uo(t),r=Vs(n),o=Fo(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Ju=e=>{let t=Fo(e),n=or(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.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=""},Xu=e=>{if(!mo(e))return;let t=Fo(e),n=or(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},qi=(e,t,n)=>{let r=Ia(n),o=mh(e),{payload:s,complete:a}=uo(t),i=mo(e),d=or(e),l=gs(e),p=i?fh(s,d):gh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=bh(p,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ku(r,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(xh(r)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=vh(d,l,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();Ju(e),Xu(e)},Sh=(e,t,n)=>{let r=Ia(t),o=uh(r),s=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=Ch(e,a),p=d?Ah(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ms,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(ji,String(i)),u.setAttribute($i,String(p)),u.setAttribute(Ui,d?"true":"false"),u.setAttribute(Uu,o),Gu(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),zu(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let E=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 E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),o!=="rows"&&u.appendChild(Ku(r,o)),qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Th=(e,t,n)=>{let{payload:r}=uo(t),o=Math.max(1,Vs(r).length);o>gs(e)&&(e.setAttribute(ji,String(o)),o>1&&!mo(e)&&e.setAttribute(Ui,"true")),qi(e,t,n)},Eh=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Ia(t);zu(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=uo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ks=(e,t,n)=>{if(!n||!po(e)||Ia(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==o&&l.remove()});let a=n.querySelector(`[${ms}="${qu(o)}"]`);if(a){Th(a,e,t);return}let{payload:i}=uo(e),d=Sh(e,t,i);n.appendChild(d)},_o=(e,t)=>{if(!e)return;let n=t?`[${ms}="${qu(t)}"]`:`[${ms}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},zi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),go=(e,t)=>{let n=Fo(e),r=or(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Gu(e,n),Ju(e),Xu(e)},Wa=(e,t,n,r)=>{let o=gs(e),s=Math.max(0,Math.min(o-1,r));wh(e,s),qi(e,t,n)};var Hr="suggest_replies";var Qu={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},Vi={name:Hr,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:Qu,origin:"sdk",annotations:{readOnlyHint:!0}},Ki=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ha=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Yu=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Gi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Ha(r))continue;let o=Yu((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Zu=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var em={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,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},tm={name:Pa,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:em,origin:"sdk",annotations:{readOnlyHint:!0}},Ba=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(tm),Zu(e)&&t.push(Vi),t};import{parse as nm,STR as rm,OBJ as om}from"partial-json";var Da=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Mh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},sm=e=>e.status==="complete"?Mh(e):e.status==="pending"?"Waiting":"",kh=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var am=e=>e.status==="complete"?kh(e):"Using tool...",Na=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Na(t)},Oa=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Na(t)},Ji=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Js(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Fa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Gs(r,n.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<n.length&&Gs(r,n.slice(s),[]),r},Gs=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Lh=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${e.description}`:"");return window.confirm(n)},fh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},hh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},yh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var bh="agent_",xh="flow_";function Yu(e){return e.startsWith(bh)?{kind:"agentId",agentId:e}:e.startsWith(xh)?{kind:"flowId",flowId:e}:null}function Zu(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let l=Yu(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Yu(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as vh,ARR as wh,OBJ as Ch,STR as Ah}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Nr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var At=(e,t={},...n)=>{let r=document.createElement(e);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=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Ys=(...e)=>e.filter(Boolean).join(" ");var Ba="ask_user_question",Zs=8,xs="data-persona-ask-sheet-for",Sh="Other",Th="Other\u2026",tm="Type your own answer here",nm="Send",Eh="Next",Mh="Back",kh="Submit all",Lh="Skip",Ph=3,Gi="data-ask-current-index",Ji="data-ask-question-count",rm="data-ask-answers",Xi="data-ask-grouped",om="data-ask-layout",Ih=e=>e.layout==="pills"?"pills":"rows",Rh=e=>e.getAttribute(om)==="pills"?"pills":"rows",em=!1,sm=e=>e.replace(/["\\]/g,"\\$&"),xo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ba,Da=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},vo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=vh(o,Ah|Ch|wh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ea=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Zs&&!em&&(em=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Zs}.`)),t.slice(0,Zs)},Wh=e=>{var t;return(t=ea(e)[0])!=null?t:null},Hh=(e,t)=>{var n;return(n=ea(e)[t])!=null?n:null},am=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},im=(e,t,n)=>{if(e!=="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(n+1),r.appendChild(o)}return r},Bh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=im(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Dh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Nh=(e,t,n,r)=>{var p,u,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Ph;f++)s.appendChild(Dh(r));return s}if(d.forEach((f,v)=>{s.appendChild(Bh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?Sh:Th;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"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=t.freeTextPlaceholder)!=null?p:tm,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(E),v.appendChild(x);let T=im(r,a,d.length);T&&v.appendChild(T),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=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},lm=(e,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=e.freeTextPlaceholder)!=null?s:tm,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=e.submitLabel)!=null?a:nm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Oh=e=>{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 n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:nm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Fh=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:Mh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===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=(p=n.skipLabel)!=null?p:Lh,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=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:kh:(g=n.nextLabel)!=null?g:Eh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},tr=e=>{var n;let t=Number((n=e.getAttribute(Gi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},_h=(e,t)=>{e.setAttribute(Gi,String(Math.max(0,Math.floor(t))))},vs=e=>{var n;let t=Number((n=e.getAttribute(Ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},wo=e=>e.getAttribute(Xi)==="true",$h=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="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(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},jh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=vo(t),r=ea(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},dm=e=>{let t=Go(e),n=tr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.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=""},pm=e=>{if(!wo(e))return;let t=Go(e),n=tr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Qi=(e,t,n)=>{let r=Da(n),o=Rh(e),{payload:s,complete:a}=vo(t),i=wo(e),d=tr(e),l=vs(e),p=i?Hh(s,d):Wh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=Nh(p,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(lm(r,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(Oh(r)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Fh(d,l,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();dm(e),pm(e)},Uh=(e,t,n)=>{let r=Da(t),o=Ih(r),s=e.toolCall.id,a=ea(n),i=Math.max(1,a.length),d=i>1,l=$h(e,a),p=d?jh(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(xs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Ji,String(i)),u.setAttribute(Gi,String(p)),u.setAttribute(Xi,d?"true":"false"),u.setAttribute(om,o),cm(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),am(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let E=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 E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),o!=="rows"&&u.appendChild(lm(r,o)),Qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},qh=(e,t,n)=>{let{payload:r}=vo(t),o=Math.max(1,ea(r).length);o>vs(e)&&(e.setAttribute(Ji,String(o)),o>1&&!wo(e)&&e.setAttribute(Xi,"true")),Qi(e,t,n)},zh=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Da(t);am(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=vo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},ta=(e,t,n)=>{if(!n||!xo(e)||Da(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${xs}]`).forEach(l=>{l.getAttribute(xs)!==o&&l.remove()});let a=n.querySelector(`[${xs}="${sm(o)}"]`);if(a){qh(a,e,t);return}let{payload:i}=vo(e),d=Uh(e,t,i);n.appendChild(d)},Jo=(e,t)=>{if(!e)return;let n=t?`[${xs}="${sm(t)}"]`:`[${xs}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Yi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Co=(e,t)=>{let n=Go(e),r=tr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,cm(e,n),dm(e),pm(e)},Oa=(e,t,n,r)=>{let o=vs(e),s=Math.max(0,Math.min(o-1,r));_h(e,s),Qi(e,t,n)};var Or="suggest_replies";var um={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},Zi={name:Or,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:um,origin:"sdk",annotations:{readOnlyHint:!0}},el=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Fa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Or},mm=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},tl=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Fa(r))continue;let o=mm((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},gm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var fm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Zs,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},hm={name:Ba,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:fm,origin:"sdk",annotations:{readOnlyHint:!0}},_a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(hm),gm(e)&&t.push(Zi),t};import{parse as ym,STR as bm,OBJ as xm}from"partial-json";var $a=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ao=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Vh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},vm=e=>e.status==="complete"?Vh(e):e.status==="pending"?"Waiting":"",Kh=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var wm=e=>e.status==="complete"?Kh(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ra=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},Ua=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},nl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=ra(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&na(r,n.slice(s,a.index),[]),a[1]!==void 0?na(r,a[1],["bold"]):a[2]!==void 0?na(r,a[2],["italic"]):a[3]!==void 0&&na(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&na(r,n.slice(s),[]),r},na=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Gh=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Yi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var im="4.4.2";var fr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(e){var s,a;let t=e.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 el=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(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 js(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Ou(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/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":fr},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,n){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:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(el).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Du(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/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:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||_a}/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:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!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 a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(el).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...Ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);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 p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var xt,hn,yr,br;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Te=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,De=A.tools?A.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Te,tools:De}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Te=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Te||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Te,De,Pe,Ne;return W((Ne=(Pe=(De=(Te=(te=A.stepId)!=null?te:A.step_id)!=null?Te:A.step)!=null?De:A.parentId)!=null?Pe:A.flowStepId)!=null?Ne:A.flow_step_id)},N=A=>{var te,Te,De,Pe,Ne,Ge,it;return W((it=(Ge=(Ne=(Pe=(De=(Te=(te=A.callId)!=null?te:A.call_id)!=null?Te:A.requestId)!=null?De:A.request_id)!=null?Pe:A.toolCallId)!=null?Ne:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Y=r,Ee=!1,de=()=>{if(f)return f;let A,te=T;return!Ee&&Y?(A=Y,Ee=!0):Y&&te?A=`${Y}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},Z=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},Ce=(A,te)=>{var Ne;let Te=(Ne=A.reasoningId)!=null?Ne:A.id,De=O(A);if(Te){let Ge=String(Te);return Z(De,Ge),Ge}if(De){let Ge=F.byStep.get(De);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Pe=`reason-${l()}`;return Z(De,Pe),Pe},ke=A=>{let te=C.get(A);if(te)return te;let Te={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Te),g(Te),Te},re=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},we=new Set,le=new Map,se=new Set,oe=new Map,be=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},He=(A,te)=>{var Ne;let Te=(Ne=A.toolId)!=null?Ne:A.id,De=N(A);if(Te){let Ge=String(Te);return re(De,Ge),Ge}if(De){let Ge=j.byCall.get(De);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Pe=`tool-${l()}`;return re(De,Pe),Pe},V=A=>{let te=R.get(A);if(te)return te;let Te={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Te),g(Te),Te},X=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Te=Date.parse(A);if(!Number.isNaN(Te))return Te}return Date.now()},We=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},K=new Map,pe=new Map,$e=new Map,ge=(A,te,Te)=>{var it;let De=$e.get(A);De||(De=[],$e.set(A,De));let Pe=0,Ne=De.length;for(;Pe<Ne;){let It=Pe+Ne>>>1;De[It].seq<te?Pe=It+1:Ne=It}((it=De[Pe])==null?void 0:it.seq)===te?De[Pe]={seq:te,text:Te}:De.splice(Pe,0,{seq:te,text:Te});let Ge="";for(let It=0;It<De.length;It++)Ge+=De[It].text;return Ge},Ve=(A,te)=>{let Te=We(te),De=pe.get(A.id),Pe=Bh(De,Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=he=>{var vt;let Fe=(vt=A.content)!=null?vt:"";he.trim()!==""&&(Fe.trim().length===0||he.startsWith(Fe)||he.trimStart().startsWith(Fe.trim()))&&(A.content=he)},it=()=>{var he;if(Ne){let Fe=(he=Ne.close)==null?void 0:he.call(Ne);Fe instanceof Promise&&Fe.catch(()=>{})}K.delete(A.id),pe.delete(A.id),A.streaming=!1,g(A)};if(!Ne){Ge(Te),it();return}let It=Xs(Pe);if(It!==null&&It.trim()!==""){Ge(It),it();return}let ce=he=>{var Ye;let Fe=typeof he=="string"?he:(Ye=he==null?void 0:he.text)!=null?Ye:null;if(Fe!==null&&Fe.trim()!=="")return Fe;let vt=Ne.getExtractedText();return vt!==null&&vt.trim()!==""?vt:Te},H;try{H=Ne.processChunk(Pe)}catch{Ge(Te),it();return}if(H instanceof Promise){H.then(he=>{Ge(ce(he)),it()}).catch(()=>{Ge(Te),it()});return}Ge(ce(H)),it()},et=null,$t=(A,te,Te,De)=>{var It;A.rawContent=te,K.has(A.id)||K.set(A.id,this.createStreamParser());let Pe=K.get(A.id),Ne=te.trim().startsWith("{")||te.trim().startsWith("[");if(Ne&&pe.set(A.id,te),Pe.__isPlainTextParser===!0){A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A);return}let it=Pe.processChunk(te);if(it instanceof Promise)it.then(ce=>{var he;let H=typeof ce=="string"?ce:(he=ce==null?void 0:ce.text)!=null?he:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A)});else{let ce=typeof it=="string"?it:(It=it==null?void 0:it.text)!=null?It:null;ce!==null&&ce.trim()!==""?(A.content=ce,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}},Xe=(A,te)=>{var It,ce;let Te=te!=null?te:A.content;if(Te==null||Te===""){A.streaming=!1,g(A);return}let De=pe.get(A.id),Pe=De!=null?De:We(Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=null,it=!1;if(Ne&&(Ge=Ne.getExtractedText(),Ge===null&&(Ge=Xs(Pe)),Ge===null)){let H=Ne.processChunk(Pe);H instanceof Promise?(it=!0,H.then(he=>{var vt;let Fe=typeof he=="string"?he:(vt=he==null?void 0:he.text)!=null?vt:null;Fe!==null&&(A.content=Fe,A.streaming=!1,K.delete(A.id),pe.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(It=H==null?void 0:H.text)!=null?It:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:pe.has(A.id)||(A.content=We(Te));let H=K.get(A.id);if(H){let he=(ce=H.close)==null?void 0:ce.call(H);he instanceof Promise&&he.catch(()=>{}),K.delete(A.id)}pe.delete(A.id),A.streaming=!1,g(A)}},fe=(A,te,Te)=>{let De=M.get(A);if(De)return De;let Pe={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Pe),g(Pe),Pe},J=[],dt,qe=new Map,Ae=0,Me="agent",nt=!1,Pt=null,ee=null,je=new Map,Cn=(xt=this.config.iterationDisplay)!=null?xt:"separate";for(dt=()=>{var A,te,Te,De,Pe,Ne,Ge,it,It,ce,H,he,Fe,vt,Ye,Ht,Tt,ht,Lt,Qt,Ft,Hn,jt,Bn,Gn,yn,kn,Jn,Xr,wt,xr,vr,Dr,lr,ut,Co,wr,Ao,Ln,Xo,Qr,Nr,Yr,Zr,So,To,eo,bt,Dn,Nn,An,Ct,Xn,Qn,On,to,Or,no,Fn,Rt,Sn,Yn,ro,Fr,oo,xe,Pn,Cr,mt,rn,on,Ar,ks,_r,Eo,Sr,$,Qo,Tr,Er,$r,Mr,cr,Yo,xa,_n,$n,dr,pr,Mo,jr,bn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,In,Ca;for(let rs=0;rs<J.length;rs++){let tt=J[rs].payloadType,w=J[rs].payload;if(!nt&&Me!=="flow"&&typeof w.stepType=="string"&&(Me="flow"),tt==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),fe(z,U,"reasoning");continue}let G=(A=Ce(w,!0))!=null?A:`reason-${l()}`,ye=ke(G);ye.reasoning=(te=ye.reasoning)!=null?te:{id:G,status:"streaming",chunks:[]},ye.reasoning.startedAt=(De=ye.reasoning.startedAt)!=null?De:X((Te=w.startedAt)!=null?Te:w.timestamp),ye.reasoning.completedAt=void 0,ye.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),ye.streaming=!0,ye.reasoning.status="streaming",g(ye)}else if(tt==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let _e=M.get(z),gt=(Ge=(Ne=(Pe=w.reasoningText)!=null?Pe:w.text)!=null?Ne:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(gt)),g(_e));continue}let U=(It=(it=Ce(w,!1))!=null?it:Ce(w,!0))!=null?It:`reason-${l()}`,G=ke(U);G.reasoning=(ce=G.reasoning)!=null?ce:{id:U,status:"streaming",chunks:[]},G.reasoning.startedAt=(he=G.reasoning.startedAt)!=null?he:X((H=w.startedAt)!=null?H:w.timestamp);let ye=(Ye=(vt=(Fe=w.reasoningText)!=null?Fe:w.text)!=null?vt:w.delta)!=null?Ye:"";if(ye&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let gt=ge(U,_e,String(ye));G.reasoning.chunks=[gt]}else G.reasoning.chunks.push(String(ye))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=X((Ht=w.completedAt)!=null?Ht:w.timestamp);let _e=(Tt=G.reasoning.startedAt)!=null?Tt:Date.now();G.reasoning.durationMs=Math.max(0,((ht=G.reasoning.completedAt)!=null?ht:Date.now())-_e)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(tt==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&&gt.reasoning.chunks.length===0&&gt.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(Qt=(Lt=Ce(w,!1))!=null?Lt:Ce(w,!0))!=null?Qt:`reason-${l()}`,G=typeof w.text=="string"?w.text:"";!C.get(U)&&(G||w.scope==="loop")&&ke(U);let ye=C.get(U);if(ye!=null&&ye.reasoning){(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),G&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(G),ye.reasoning.status="complete",ye.reasoning.completedAt=X((Ft=w.completedAt)!=null?Ft:w.timestamp);let gt=(Hn=ye.reasoning.startedAt)!=null?Hn:Date.now();ye.reasoning.durationMs=Math.max(0,((jt=ye.reasoning.completedAt)!=null?jt:Date.now())-gt),ye.streaming=!1,g(ye)}let _e=O(w);_e&&F.byStep.delete(_e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Ae=w.iteration);let z=(Gn=(Bn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Bn:He(w,!0))!=null?Gn:`tool-${l()}`,U=(yn=w.toolName)!=null?yn:w.name;if(be(U)){we.add(z);continue}re(N(w),z);let G=V(z),ye=(kn=G.toolCall)!=null?kn:{id:z,status:"pending"};ye.name=U!=null?U:ye.name,ye.status="running",w.parameters!==void 0?ye.args=w.parameters:w.args!==void 0&&(ye.args=w.args),ye.startedAt=(Xr=ye.startedAt)!=null?Xr:X((Jn=w.startedAt)!=null?Jn:w.timestamp),ye.completedAt=void 0,ye.durationMs=void 0,G.toolCall=ye,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(tt==="tool_output_delta"){let z=(xr=(wt=He(w,!1))!=null?wt:He(w,!0))!=null?xr:`tool-${l()}`;if(we.has(z))continue;let U=V(z),G=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};G.startedAt=(lr=G.startedAt)!=null?lr:X((Dr=w.startedAt)!=null?Dr:w.timestamp);let ye=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";ye&&(G.chunks=(Ao=G.chunks)!=null?Ao:[],G.chunks.push(String(ye))),G.status="running",U.toolCall=G,U.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Ln=_e==null?void 0:_e.executionId)!=null?Ln:w.executionId,iteration:(Xo=_e==null?void 0:_e.iteration)!=null?Xo:w.iteration}),g(U)}else if(tt==="tool_complete"){let z=(Yr=(Nr=He(w,!1))!=null?Nr:He(w,!0))!=null?Yr:`tool-${l()}`;if(we.has(z)){we.delete(z);continue}let U=V(z),G=(Zr=U.toolCall)!=null?Zr:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=X((So=w.completedAt)!=null?So:w.timestamp);let ye=(To=w.duration)!=null?To:w.executionTime;if(typeof ye=="number")G.durationMs=ye;else{let st=(eo=G.startedAt)!=null?eo:Date.now();G.durationMs=Math.max(0,((bt=G.completedAt)!=null?bt:Date.now())-st)}U.toolCall=G,U.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(An=U.agentMetadata)!=null?An:{executionId:(Dn=_e==null?void 0:_e.executionId)!=null?Dn:w.executionId,iteration:(Nn=_e==null?void 0:_e.iteration)!=null?Nn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(tt==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(Ct=z!=null?z:w.toolId)!=null?Ct:`local-${l()}`,G=V(U),ye=w.toolName,_e=w.origin==="webmcp"&&!Oo(ye)?`webmcp:${ye}`:ye,gt=Oo(_e),st=(Xn=G.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=_e,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Or=st.startedAt)!=null?Or:X((to=(On=w.startedAt)!=null?On:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,G.toolCall=st,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:(Fn=G.agentMetadata)==null?void 0:Fn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(tt==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let G=f;G&&(Me==="flow"?(Xe(G),et=G):(G.streaming=!1,g(G)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(tt==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let ye=typeof w.delta=="string"?w.delta:"",_e=((Sn=P.get(z))!=null?Sn:"")+ye;if(P.set(z,_e),_e.trim()==="")continue;let gt=fe(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},$t(gt,_e,ye,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Me==="flow"){let ye=typeof w.delta=="string"?w.delta:"";if(L+=ye,L.trim()==="")continue;let _e=de();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},$t(_e,L,ye,void 0),v=_e;continue}let G=de();G.content+=(Yn=w.delta)!=null?Yn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Pt!=null?Pt:void 0,agentName:ee==null?void 0:ee.agentName},v=G,g(G)}else if(tt==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let G=M.get(z);G&&Xe(G),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(Me==="flow"?(Xe(U),et=U):(((ro=U.content)!=null?ro:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(tt==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let G=w.error,ye=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Fr=G.message)!=null?Fr:"Step failed"):"Step failed";n({type:"error",error:new Error(ye)});let _e=f;_e&&_e.streaming&&(_e.streaming=!1,g(_e)),n({type:"status",status:"idle"});continue}{let G=et;et=null;let ye=w.stopReason,_e=(oo=w.result)==null?void 0:oo.response;if(G)ye&&(G.stopReason=ye),_e!=null?Ve(G,_e):G.streaming!==!1&&(K.delete(G.id),pe.delete(G.id),G.streaming=!1,g(G));else{let gt=_e!=null&&_e!=="";if(gt||ye){let st=de();ye&&(st.stopReason=ye),gt?Xe(st,_e):(st.streaming=!1,g(st))}}continue}}else if(tt==="execution_start")Me=w.kind==="flow"?"flow":"agent",nt=!0,Me==="agent"&&(ee={executionId:w.executionId,agentId:(xe=w.agentId)!=null?xe:"virtual",agentName:(Pn=w.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:X(w.startedAt)});else if(tt==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:Ae;if(z!==Ae){if(ee&&(ee.currentIteration=z),Cn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),je.set(z-1,U),f=null)}Ae=z}Pt=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),g(U))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let G=w.id;(!G||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===G)&&(U.stopReason=z,g(U))}Pt===w.id&&(Pt=null)}else if(tt==="media_start"){let z=String(w.id);qe.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(tt==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let G=(_r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?_r:"application/octet-stream",ye=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(ye)gt={type:"media",data:ye,mediaType:G};else if(_e){let dn=G.toLowerCase();gt={type:dn==="image"||dn.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:G}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Rn=[];for(let dn of Ps){if(!dn||typeof dn!="object")continue;let pn=dn,Lo=typeof pn.type=="string"?pn.type:void 0,Ur=typeof pn.mediaType=="string"?pn.mediaType.toLowerCase():"",Tn=null,fn="";if(Lo==="media"){let jn=typeof pn.data=="string"?pn.data:void 0;if(!jn)continue;fn=Ur.length>0?Ur:"application/octet-stream",Tn=`data:${fn};base64,${jn}`}else if(Lo==="image-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else if(Lo==="file-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else continue;if(Tn)if(Lo==="image-url"||fn.startsWith("image/"))Rn.push({type:"image",image:Tn,...fn.includes("/")?{mimeType:fn}:{}});else if(fn.startsWith("audio/"))Rn.push({type:"audio",audio:Tn,mimeType:fn});else if(fn.startsWith("video/"))Rn.push({type:"video",video:Tn,mimeType:fn});else{let jn=fn||"application/octet-stream";Rn.push({type:"file",data:Tn,mimeType:jn,filename:Wh(jn)})}}if(Rn.length>0){let dn=l(),pn=st,Ur={id:`agent-media-${typeof pn=="string"&&pn.length>0?`${pn}-${dn}`:String(dn)}`,role:"assistant",content:"",contentParts:Rn,createdAt:new Date().toISOString(),streaming:!1,sequence:dn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ae}};g(Ur);let Tn=f;Tn&&(Tn.streaming=!1,g(Tn)),f=null,x.current=null}}else if(tt==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Me;z==="agent"&&ee&&(ee.status=w.success?"complete":"error",ee.completedAt=X(w.completedAt),ee.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Xe(U):(U.streaming=!1,g(U)),f=null),T=null,L="",et=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let z=typeof w.error=="string"?w.error:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(tt!=="ping"){if(tt==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Er=ee==null?void 0:ee.agentId)!=null?Er:"virtual",executionId:(Mr=($r=w.executionId)!=null?$r:ee==null?void 0:ee.executionId)!=null?Mr:"",toolName:(cr=w.toolName)!=null?cr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let z=(_n=w.approvalId)!=null?_n:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:($n=ee==null?void 0:ee.agentId)!=null?$n:"virtual",executionId:(pr=(dr=w.executionId)!=null?dr:ee==null?void 0:ee.executionId)!=null?pr:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(bn=w.description)!=null?bn:`Execute ${(jr=w.toolName)!=null?jr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ee==null?void 0:ee.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ee==null?void 0:ee.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",resolvedAt:Date.now()}};g(G)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let z=w.artifactType,U=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),oe.set(U,{markdown:"",title:G}),!se.has(U)){se.add(U);let ye={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:G,artifactType:z,status:"streaming"}})};le.set(U,ye),g(ye)}}else if(tt==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let G=oe.get(z);G&&(G.markdown+=U)}else if(tt==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=le.get(z);if(U){U.streaming=!1;try{let G=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(G.props){G.props.status="complete";let ye=oe.get(z);ye!=null&&ye.markdown&&(G.props.markdown=ye.markdown)}U.rawContent=JSON.stringify(G)}catch{}oe.delete(z),g(U),le.delete(z)}}}else if(tt==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),G=z.role,_e={id:U,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(_e),_e.rawContent)try{let gt=JSON.parse(_e.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&se.add(st)}catch{}f=null,x.current=null,K.delete(U),pe.delete(U)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(tt==="dispatch_error"){let U=(In=w.message)!=null?In:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((Ca=U.message)!=null?Ca:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Te=a.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},oa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},rl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ol=()=>{var t;let e=Gh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},sl=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=ym(n,bm|xm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?$a(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=$a(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Jh=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=ym(s,bm|xm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},al=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Cm="4.5.0";var yr=Cm;var Qh="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function Yh(e){var s,a;let t=e.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 il=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Zh(e){switch(e){case"json":return sl;case"regex-json":return ol;case"xml":return al;default:return rl}}var Am=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ey(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Am(n);if(!Am(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=oa(e);return oa(t)!==null&&a===null?t:e}var ws=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:Qh,this.headers={"Content-Type":"application/json","X-Persona-Version":yr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Zh(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 Xs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Zu(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":yr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/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":yr},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,n){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:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(il).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Qu(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":yr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/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:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||za}/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:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!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 a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(il).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[..._a(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(il).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[..._a(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);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 p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var bt,fn,xr,vr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Me=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Ne=A.tools?A.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Me,tools:Ne}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Me=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Me||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},H=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Me,Ne,Ie,Oe;return H((Oe=(Ie=(Ne=(Me=(te=A.stepId)!=null?te:A.step_id)!=null?Me:A.step)!=null?Ne:A.parentId)!=null?Ie:A.flowStepId)!=null?Oe:A.flow_step_id)},N=A=>{var te,Me,Ne,Ie,Oe,Ge,at;return H((at=(Ge=(Oe=(Ie=(Ne=(Me=(te=A.callId)!=null?te:A.call_id)!=null?Me:A.requestId)!=null?Ne:A.request_id)!=null?Ie:A.toolCallId)!=null?Oe:A.tool_call_id)!=null?Ge:A.stepId)!=null?at:A.step_id)},Y=r,ke=!1,pe=()=>{if(f)return f;let A,te=T;return!ke&&Y?(A=Y,ke=!0):Y&&te?A=`${Y}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},Z=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},Te=(A,te)=>{var Oe;let Me=(Oe=A.reasoningId)!=null?Oe:A.id,Ne=O(A);if(Me){let Ge=String(Me);return Z(Ne,Ge),Ge}if(Ne){let Ge=F.byStep.get(Ne);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Ie=`reason-${l()}`;return Z(Ne,Ie),Ie},Le=A=>{let te=C.get(A);if(te)return te;let Me={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Me),g(Me),Me},oe=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},Ae=new Set,se=new Map,ie=new Set,ae=new Map,xe=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Be=(A,te)=>{var Oe;let Me=(Oe=A.toolId)!=null?Oe:A.id,Ne=N(A);if(Me){let Ge=String(Me);return oe(Ne,Ge),Ge}if(Ne){let Ge=j.byCall.get(Ne);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Ie=`tool-${l()}`;return oe(Ne,Ie),Ie},V=A=>{let te=R.get(A);if(te)return te;let Me={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Me),g(Me),Me},X=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Me=Date.parse(A);if(!Number.isNaN(Me))return Me}return Date.now()},He=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},K=new Map,ue=new Map,$e=new Map,fe=(A,te,Me)=>{var at;let Ne=$e.get(A);Ne||(Ne=[],$e.set(A,Ne));let Ie=0,Oe=Ne.length;for(;Ie<Oe;){let Pt=Ie+Oe>>>1;Ne[Pt].seq<te?Ie=Pt+1:Oe=Pt}((at=Ne[Ie])==null?void 0:at.seq)===te?Ne[Ie]={seq:te,text:Me}:Ne.splice(Ie,0,{seq:te,text:Me});let Ge="";for(let Pt=0;Pt<Ne.length;Pt++)Ge+=Ne[Pt].text;return Ge},Ve=(A,te)=>{let Me=He(te),Ne=ue.get(A.id),Ie=ey(Ne,Me);A.rawContent=Ie;let Oe=K.get(A.id),Ge=be=>{var xt;let _e=(xt=A.content)!=null?xt:"";be.trim()!==""&&(_e.trim().length===0||be.startsWith(_e)||be.trimStart().startsWith(_e.trim()))&&(A.content=be)},at=()=>{var be;if(Oe){let _e=(be=Oe.close)==null?void 0:be.call(Oe);_e instanceof Promise&&_e.catch(()=>{})}K.delete(A.id),ue.delete(A.id),A.streaming=!1,g(A)};if(!Oe){Ge(Me),at();return}let Pt=oa(Ie);if(Pt!==null&&Pt.trim()!==""){Ge(Pt),at();return}let ce=be=>{var Ye;let _e=typeof be=="string"?be:(Ye=be==null?void 0:be.text)!=null?Ye:null;if(_e!==null&&_e.trim()!=="")return _e;let xt=Oe.getExtractedText();return xt!==null&&xt.trim()!==""?xt:Me},B;try{B=Oe.processChunk(Ie)}catch{Ge(Me),at();return}if(B instanceof Promise){B.then(be=>{Ge(ce(be)),at()}).catch(()=>{Ge(Me),at()});return}Ge(ce(B)),at()},et=null,Ot=(A,te,Me,Ne)=>{var Pt;A.rawContent=te,K.has(A.id)||K.set(A.id,this.createStreamParser());let Ie=K.get(A.id),Oe=te.trim().startsWith("{")||te.trim().startsWith("[");if(Oe&&ue.set(A.id,te),Ie.__isPlainTextParser===!0){A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A);return}let at=Ie.processChunk(te);if(at instanceof Promise)at.then(ce=>{var be;let B=typeof ce=="string"?ce:(be=ce==null?void 0:ce.text)!=null?be:null;B!==null&&B.trim()!==""?(A.content=B,g(A)):!Oe&&!te.trim().startsWith("<")&&(A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A)});else{let ce=typeof at=="string"?at:(Pt=at==null?void 0:at.text)!=null?Pt:null;ce!==null&&ce.trim()!==""?(A.content=ce,g(A)):!Oe&&!te.trim().startsWith("<")&&(A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}},Xe=(A,te)=>{var Pt,ce;let Me=te!=null?te:A.content;if(Me==null||Me===""){A.streaming=!1,g(A);return}let Ne=ue.get(A.id),Ie=Ne!=null?Ne:He(Me);A.rawContent=Ie;let Oe=K.get(A.id),Ge=null,at=!1;if(Oe&&(Ge=Oe.getExtractedText(),Ge===null&&(Ge=oa(Ie)),Ge===null)){let B=Oe.processChunk(Ie);B instanceof Promise?(at=!0,B.then(be=>{var xt;let _e=typeof be=="string"?be:(xt=be==null?void 0:be.text)!=null?xt:null;_e!==null&&(A.content=_e,A.streaming=!1,K.delete(A.id),ue.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof B=="string"?B:(Pt=B==null?void 0:B.text)!=null?Pt:null}if(!at){Ge!==null&&Ge.trim()!==""?A.content=Ge:ue.has(A.id)||(A.content=He(Me));let B=K.get(A.id);if(B){let be=(ce=B.close)==null?void 0:ce.call(B);be instanceof Promise&&be.catch(()=>{}),K.delete(A.id)}ue.delete(A.id),A.streaming=!1,g(A)}},ye=(A,te,Me)=>{let Ne=M.get(A);if(Ne)return Ne;let Ie={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Ie),g(Ie),Ie},J=[],dt,qe=new Map,Se=0,ve="agent",nt=!1,Lt=null,ee=null,je=new Map,wn=(bt=this.config.iterationDisplay)!=null?bt:"separate";for(dt=()=>{var A,te,Me,Ne,Ie,Oe,Ge,at,Pt,ce,B,be,_e,xt,Ye,Rt,St,ht,kt,Xt,Ft,en,wr,$r,sr,ar,to,qt,ir,jr,In,kn,Rn,lr,Cr,no,qn,ro,vt,Ar,Sr,Ur,cr,ut,Io,Tr,Ro,Ln,os,oo,qr,so,ao,Wo,Ho,io,yt,Wn,Hn,Cn,wt,zn,Vn,Bn,lo,Ce,zr,Kn,_t,Gn,Vr,Hs,ss,Bs,Bo,Er,co,it,rn,on,Mr,Ds,Kr,Do,kr,$,as,dr,Lr,Gr,Pr,pr,is,Ma,hn,An,ur,Sn,No,mr,yn,Ir,ls,Oo,cs;for(let Rr=0;Rr<J.length;Rr++){let tt=J[Rr].payloadType,w=J[Rr].payload;if(!nt&&ve!=="flow"&&typeof w.stepType=="string"&&(ve="flow"),tt==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),ye(z,U,"reasoning");continue}let G=(A=Te(w,!0))!=null?A:`reason-${l()}`,he=Le(G);he.reasoning=(te=he.reasoning)!=null?te:{id:G,status:"streaming",chunks:[]},he.reasoning.startedAt=(Ne=he.reasoning.startedAt)!=null?Ne:X((Me=w.startedAt)!=null?Me:w.timestamp),he.reasoning.completedAt=void 0,he.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),he.streaming=!0,he.reasoning.status="streaming",g(he)}else if(tt==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let re=M.get(z),mt=(Ge=(Oe=(Ie=w.reasoningText)!=null?Ie:w.text)!=null?Oe:w.delta)!=null?Ge:"";mt&&w.hidden!==!0&&re.reasoning&&(re.reasoning.chunks.push(String(mt)),g(re));continue}let U=(Pt=(at=Te(w,!1))!=null?at:Te(w,!0))!=null?Pt:`reason-${l()}`,G=Le(U);G.reasoning=(ce=G.reasoning)!=null?ce:{id:U,status:"streaming",chunks:[]},G.reasoning.startedAt=(be=G.reasoning.startedAt)!=null?be:X((B=w.startedAt)!=null?B:w.timestamp);let he=(Ye=(xt=(_e=w.reasoningText)!=null?_e:w.text)!=null?xt:w.delta)!=null?Ye:"";if(he&&w.hidden!==!0){let re=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(re!==void 0){let mt=fe(U,re,String(he));G.reasoning.chunks=[mt]}else G.reasoning.chunks.push(String(he))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=X((Rt=w.completedAt)!=null?Rt:w.timestamp);let re=(St=G.reasoning.startedAt)!=null?St:Date.now();G.reasoning.durationMs=Math.max(0,((ht=G.reasoning.completedAt)!=null?ht:Date.now())-re)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(tt==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let mt=M.get(z);if(mt.reasoning){let pt=typeof w.text=="string"?w.text:"";pt&&mt.reasoning.chunks.length===0&&mt.reasoning.chunks.push(pt),mt.reasoning.status="complete",mt.streaming=!1,g(mt)}k.delete(z),M.delete(z);continue}let U=(Xt=(kt=Te(w,!1))!=null?kt:Te(w,!0))!=null?Xt:`reason-${l()}`,G=typeof w.text=="string"?w.text:"";!C.get(U)&&(G||w.scope==="loop")&&Le(U);let he=C.get(U);if(he!=null&&he.reasoning){(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),G&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(G),he.reasoning.status="complete",he.reasoning.completedAt=X((Ft=w.completedAt)!=null?Ft:w.timestamp);let mt=(en=he.reasoning.startedAt)!=null?en:Date.now();he.reasoning.durationMs=Math.max(0,((wr=he.reasoning.completedAt)!=null?wr:Date.now())-mt),he.streaming=!1,g(he)}let re=O(w);re&&F.byStep.delete(re)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Se=w.iteration);let z=(sr=($r=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?$r:Be(w,!0))!=null?sr:`tool-${l()}`,U=(ar=w.toolName)!=null?ar:w.name;if(xe(U)){Ae.add(z);continue}oe(N(w),z);let G=V(z),he=(to=G.toolCall)!=null?to:{id:z,status:"pending"};he.name=U!=null?U:he.name,he.status="running",w.parameters!==void 0?he.args=w.parameters:w.args!==void 0&&(he.args=w.args),he.startedAt=(ir=he.startedAt)!=null?ir:X((qt=w.startedAt)!=null?qt:w.timestamp),he.completedAt=void 0,he.durationMs=void 0,G.toolCall=he,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(tt==="tool_output_delta"){let z=(In=(jr=Be(w,!1))!=null?jr:Be(w,!0))!=null?In:`tool-${l()}`;if(Ae.has(z))continue;let U=V(z),G=(kn=U.toolCall)!=null?kn:{id:z,status:"running"};G.startedAt=(lr=G.startedAt)!=null?lr:X((Rn=w.startedAt)!=null?Rn:w.timestamp);let he=(qn=(no=(Cr=w.text)!=null?Cr:w.delta)!=null?no:w.message)!=null?qn:"";he&&(G.chunks=(ro=G.chunks)!=null?ro:[],G.chunks.push(String(he))),G.status="running",U.toolCall=G,U.streaming=!0;let re=w.agentContext;(re||w.executionId)&&(U.agentMetadata=(Sr=U.agentMetadata)!=null?Sr:{executionId:(vt=re==null?void 0:re.executionId)!=null?vt:w.executionId,iteration:(Ar=re==null?void 0:re.iteration)!=null?Ar:w.iteration}),g(U)}else if(tt==="tool_complete"){let z=(cr=(Ur=Be(w,!1))!=null?Ur:Be(w,!0))!=null?cr:`tool-${l()}`;if(Ae.has(z)){Ae.delete(z);continue}let U=V(z),G=(ut=U.toolCall)!=null?ut:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=X((Io=w.completedAt)!=null?Io:w.timestamp);let he=(Tr=w.duration)!=null?Tr:w.executionTime;if(typeof he=="number")G.durationMs=he;else{let pt=(Ro=G.startedAt)!=null?Ro:Date.now();G.durationMs=Math.max(0,((Ln=G.completedAt)!=null?Ln:Date.now())-pt)}U.toolCall=G,U.streaming=!1;let re=w.agentContext;(re||w.executionId)&&(U.agentMetadata=(qr=U.agentMetadata)!=null?qr:{executionId:(os=re==null?void 0:re.executionId)!=null?os:w.executionId,iteration:(oo=re==null?void 0:re.iteration)!=null?oo:w.iteration}),g(U);let mt=N(w);mt&&j.byCall.delete(mt)}else if(tt==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(so=z!=null?z:w.toolId)!=null?so:`local-${l()}`,G=V(U),he=w.toolName,re=w.origin==="webmcp"&&!Ko(he)?`webmcp:${he}`:he,mt=Ko(re),pt=(ao=G.toolCall)!=null?ao:{id:U,status:"pending"};pt.name=re,pt.args=w.parameters,pt.status=mt?"running":"complete",pt.chunks=(Wo=pt.chunks)!=null?Wo:[],pt.startedAt=(yt=pt.startedAt)!=null?yt:X((io=(Ho=w.startedAt)!=null?Ho:w.timestamp)!=null?io:w.awaitedAt),mt?(pt.completedAt=void 0,pt.duration=void 0,pt.durationMs=void 0):pt.completedAt=(Wn=pt.completedAt)!=null?Wn:pt.startedAt,G.toolCall=pt,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Cn=w.executionId)!=null?Cn:(Hn=G.agentMetadata)==null?void 0:Hn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(tt==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let G=f;G&&(ve==="flow"?(Xe(G),et=G):(G.streaming=!1,g(G)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(tt==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let he=typeof w.delta=="string"?w.delta:"",re=((wt=P.get(z))!=null?wt:"")+he;if(P.set(z,re),re.trim()==="")continue;let mt=ye(z,U);mt.agentMetadata={...mt.agentMetadata,executionId:w.executionId,parentToolId:U},Ot(mt,re,he,void 0);continue}if(T=typeof w.id=="string"?w.id:T,ve==="flow"){let he=typeof w.delta=="string"?w.delta:"";if(L+=he,L.trim()==="")continue;let re=pe();re.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ot(re,L,he,void 0),v=re;continue}let G=pe();G.content+=(zn=w.delta)!=null?zn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Lt!=null?Lt:void 0,agentName:ee==null?void 0:ee.agentName},v=G,g(G)}else if(tt==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let G=M.get(z);G&&Xe(G),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(ve==="flow"?(Xe(U),et=U):(((Vn=U.content)!=null?Vn:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(tt==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let G=w.error,he=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Bn=G.message)!=null?Bn:"Step failed"):"Step failed";n({type:"error",error:new Error(he)});let re=f;re&&re.streaming&&(re.streaming=!1,g(re)),n({type:"status",status:"idle"});continue}{let G=et;et=null;let he=w.stopReason,re=(lo=w.result)==null?void 0:lo.response;if(G)he&&(G.stopReason=he),re!=null?Ve(G,re):G.streaming!==!1&&(K.delete(G.id),ue.delete(G.id),G.streaming=!1,g(G));else{let mt=re!=null&&re!=="";if(mt||he){let pt=pe();he&&(pt.stopReason=he),mt?Xe(pt,re):(pt.streaming=!1,g(pt))}}continue}}else if(tt==="execution_start")ve=w.kind==="flow"?"flow":"agent",nt=!0,ve==="agent"&&(ee={executionId:w.executionId,agentId:(Ce=w.agentId)!=null?Ce:"virtual",agentName:(zr=w.agentName)!=null?zr:"",status:"running",currentIteration:0,maxTurns:(Kn=w.maxTurns)!=null?Kn:1,startedAt:X(w.startedAt)});else if(tt==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:Se;if(z!==Se){if(ee&&(ee.currentIteration=z),wn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),je.set(z-1,U),f=null)}Se=z}Lt=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let z=(_t=w.toolCallId)!=null?_t:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(Gn=U.toolCall.chunks)!=null?Gn:[],U.toolCall.chunks.push((Vr=w.delta)!=null?Vr:""),g(U))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let G=w.id;(!G||((Hs=U.agentMetadata)==null?void 0:Hs.turnId)===G)&&(U.stopReason=z,g(U))}Lt===w.id&&(Lt=null)}else if(tt==="media_start"){let z=String(w.id);qe.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(tt==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let G=(Bs=(ss=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ss:U==null?void 0:U.mediaType)!=null?Bs:"application/octet-stream",he=typeof w.data=="string"?w.data:void 0,re=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,mt=null;if(he)mt={type:"media",data:he,mediaType:G};else if(re){let Jn=G.toLowerCase();mt={type:Jn==="image"||Jn.startsWith("image/")?"image-url":"file-url",url:re,mediaType:G}}let pt=(Bo=w.toolCallId)!=null?Bo:U==null?void 0:U.toolCallId,Dn=mt?[mt]:[],po=[];for(let Jn of Dn){if(!Jn||typeof Jn!="object")continue;let sn=Jn,Xn=typeof sn.type=="string"?sn.type:void 0,Jr=typeof sn.mediaType=="string"?sn.mediaType.toLowerCase():"",pn=null,Tn="";if(Xn==="media"){let Nn=typeof sn.data=="string"?sn.data:void 0;if(!Nn)continue;Tn=Jr.length>0?Jr:"application/octet-stream",pn=`data:${Tn};base64,${Nn}`}else if(Xn==="image-url"){let Nn=typeof sn.url=="string"?sn.url:void 0;if(!Nn)continue;Tn=Jr,pn=Nn}else if(Xn==="file-url"){let Nn=typeof sn.url=="string"?sn.url:void 0;if(!Nn)continue;Tn=Jr,pn=Nn}else continue;if(pn)if(Xn==="image-url"||Tn.startsWith("image/"))po.push({type:"image",image:pn,...Tn.includes("/")?{mimeType:Tn}:{}});else if(Tn.startsWith("audio/"))po.push({type:"audio",audio:pn,mimeType:Tn});else if(Tn.startsWith("video/"))po.push({type:"video",video:pn,mimeType:Tn});else{let Nn=Tn||"application/octet-stream";po.push({type:"file",data:pn,mimeType:Nn,filename:Yh(Nn)})}}if(po.length>0){let Jn=l(),sn=pt,Jr={id:`agent-media-${typeof sn=="string"&&sn.length>0?`${sn}-${Jn}`:String(Jn)}`,role:"assistant",content:"",contentParts:po,createdAt:new Date().toISOString(),streaming:!1,sequence:Jn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Se}};g(Jr);let pn=f;pn&&(pn.streaming=!1,g(pn)),f=null,x.current=null}}else if(tt==="execution_complete"){let z=(Er=w.kind)!=null?Er:ve;z==="agent"&&ee&&(ee.status=w.success?"complete":"error",ee.completedAt=X(w.completedAt),ee.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Xe(U):(U.streaming=!1,g(U)),f=null),T=null,L="",et=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let z=typeof w.error=="string"?w.error:(it=(co=w.error)==null?void 0:co.message)!=null?it:"Execution error";n({type:"error",error:new Error(z)})}else if(tt!=="ping"){if(tt==="approval_start"){let z=(rn=w.approvalId)!=null?rn:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(on=ee==null?void 0:ee.agentId)!=null?on:"virtual",executionId:(Ds=(Mr=w.executionId)!=null?Mr:ee==null?void 0:ee.executionId)!=null?Ds:"",toolName:(Kr=w.toolName)!=null?Kr:"",toolType:w.toolType,description:(kr=w.description)!=null?kr:`Execute ${(Do=w.toolName)!=null?Do:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let z=($=w.approvalId)!=null?$:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(as=ee==null?void 0:ee.agentId)!=null?as:"virtual",executionId:(Lr=(dr=w.executionId)!=null?dr:ee==null?void 0:ee.executionId)!=null?Lr:"",toolName:(Gr=w.toolName)!=null?Gr:"",toolType:w.toolType,description:(pr=w.description)!=null?pr:`Execute ${(Pr=w.toolName)!=null?Pr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(is=w.decision)!=null?is:"approved",agentId:(Ma=ee==null?void 0:ee.agentId)!=null?Ma:"virtual",executionId:(An=(hn=w.executionId)!=null?hn:ee==null?void 0:ee.executionId)!=null?An:"",toolName:(ur=w.toolName)!=null?ur:"",description:(Sn=w.description)!=null?Sn:"",resolvedAt:Date.now()}};g(G)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let z=w.artifactType,U=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),ae.set(U,{markdown:"",title:G}),!ie.has(U)){ie.add(U);let he={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:G,artifactType:z,status:"streaming"}})};se.set(U,he),g(he)}}else if(tt==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((No=w.delta)!=null?No:"");n({type:"artifact_delta",id:z,artDelta:U});let G=ae.get(z);G&&(G.markdown+=U)}else if(tt==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=se.get(z);if(U){U.streaming=!1;try{let G=JSON.parse((mr=U.rawContent)!=null?mr:"{}");if(G.props){G.props.status="complete";let he=ae.get(z);he!=null&&he.markdown&&(G.props.markdown=he.markdown)}U.rawContent=JSON.stringify(G)}catch{}ae.delete(z),g(U),se.delete(z)}}}else if(tt==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((yn=z.id)!=null?yn:`msg-${l()}`),G=z.role,re={id:U,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(re),re.rawContent)try{let mt=JSON.parse(re.rawContent),pt=(Ir=mt==null?void 0:mt.props)==null?void 0:Ir.artifactId;typeof pt=="string"&&ie.add(pt)}catch{}f=null,x.current=null,K.delete(U),ue.delete(U)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((ls=w.error)==null?void 0:ls.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(tt==="dispatch_error"){let U=(Oo=w.message)!=null?Oo:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((cs=U.message)!=null?cs:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Me=a.split(`
12
12
 
13
- `);a=(hn=Te.pop())!=null?hn:"";for(let De of Te){let Pe=De.split(`
14
- `),Ne="message",Ge="";for(let ce of Pe)ce.startsWith("event:")?Ne=ce.replace("event:","").trim():ce.startsWith("data:")&&(Ge+=ce.replace("data:","").trim());if(!Ge)continue;let it;try{it=JSON.parse(Ge)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let It=Ne!=="message"?Ne:(yr=it.type)!=null?yr:"message";if((br=this.onSSEEvent)==null||br.call(this,It,it),this.parseSSEEvent){x.current=f;let ce=await this.handleCustomSSEEvent(it,n,x,g,l,E);if(x.current&&x.current!==f&&(f=x.current),ce)continue}J.push({payloadType:It,payload:it}),dt()}}dt()}};function Dh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Qs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function hs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var $a="[Image]";function Nh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Oh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Fh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function _h(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ja(e){return{type:"text",text:e}}function $h(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function jh(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Uh(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var cm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qh=["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"],Kr=[...cm,...qh];function zh(e){return cm.includes(e)||e.startsWith("image/")}function Ua(e){return zh(e.type)}async function dm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ua(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function pm(e,t=Kr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Vh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function um(e,t){let n=Vh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}tl();var mm=16e3,Kh=24e3,Gh=4096,Jh=1380533830;function Xh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Jh?new Uint8Array(e,44):new Uint8Array(e)}function Qh(e){var r;let t=e.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,n=(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(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:mm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:mm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ys(Kh);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Qh(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,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 E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Gh,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);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,n){if(n!==this.callGeneration||!this.playback)return;let r=Xh(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(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(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,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(e.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function nl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return jo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return jo({type:"runtype",runtype:e.runtype});if($o.isSupported())return jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qa(e){try{return nl(e),!0}catch{return!1}}function Zs(e){var n;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=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Uo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(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):Zs(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var bs=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,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){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,n)}async play(t,n){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(n,{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,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function rl(e){if(!e)return"";let t=Yh(e);return gm(t!==null?t:e)}function Yh(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function gm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
+ `);a=(fn=Me.pop())!=null?fn:"";for(let Ne of Me){let Ie=Ne.split(`
14
+ `),Oe="message",Ge="";for(let ce of Ie)ce.startsWith("event:")?Oe=ce.replace("event:","").trim():ce.startsWith("data:")&&(Ge+=ce.replace("data:","").trim());if(!Ge)continue;let at;try{at=JSON.parse(Ge)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let Pt=Oe!=="message"?Oe:(xr=at.type)!=null?xr:"message";if((vr=this.onSSEEvent)==null||vr.call(this,Pt,at),this.parseSSEEvent){x.current=f;let ce=await this.handleCustomSSEEvent(at,n,x,g,l,E);if(x.current&&x.current!==f&&(f=x.current),ce)continue}J.push({payloadType:Pt,payload:at}),dt()}}dt()}};function ty(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function sa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Cs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function ny(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ry(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function oy(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function sy(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ka(e){return{type:"text",text:e}}function ay(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function iy(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function ly(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Sm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],cy=["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"],Zr=[...Sm,...cy];function dy(e){return Sm.includes(e)||e.startsWith("image/")}function Ga(e){return dy(e.type)}async function Tm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ga(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Em(e,t=Zr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function py(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Mm(e,t){let n=py(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}ll();var km=16e3,uy=24e3,my=4096,gy=1380533830;function fy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===gy?new Uint8Array(e,44):new Uint8Array(e)}function hy(e){var r;let t=e.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 aa=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,n=(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(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:km,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:km});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new As(uy);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${hy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,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 E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(my,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);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,n){if(n!==this.callGeneration||!this.playback)return;let r=fy(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(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Xo=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,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Qo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new aa(e.runtype);case"browser":if(!Xo.isSupported())throw new Error("Browser speech recognition not supported");return new Xo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function cl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Qo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Qo({type:"runtype",runtype:e.runtype});if(Xo.isSupported())return Qo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ja(e){try{return cl(e),!0}catch{return!1}}function ia(e){var n;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=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Yo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(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):ia(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Ss=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,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){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,n)}async play(t,n){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(n,{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,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function dl(e){if(!e)return"";let t=yy(e);return Lm(t!==null?t:e)}function yy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Lm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
- `),t.trim()}var xm=null;var ol=()=>xm?xm():Promise.resolve().then(()=>(bm(),ym));var ty=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ny(e,t){return ty.some(n=>e[n]!==t[n])}function vm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
16
+ `),t.trim()}var Hm=null;var pl=()=>Hm?Hm():Promise.resolve().then(()=>(Wm(),Rm));var vy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function wy(e,t){return vy.some(n=>e[n]!==t[n])}function Bm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
17
17
 
18
- _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]}),wm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Cm=e=>Oo(e)||e===Hr,ta=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 bs(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,l,p,u;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(Oo(g.name)||g.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&f&&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 g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,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 fs(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,l;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(l=(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)!=null?l:this.config.agentId;!n||!r||!this.config.clientToken||ol().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 qa((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,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.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,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Uo.isSupported()?new Uo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(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)!=null?d:this.config.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(l&&p&&u)return ol().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:v})=>{let x=new f({host:l,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&n?new v(x,n,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):x});if(g&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=jo(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,l;(l=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||l.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,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(d=this.callbacks).onVoiceStatusChanged)==null||l.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 n,r,o,s,a,i,d,l,p,u,g,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(l=(d=t.runtype)==null?void 0:d.host)!=null?l:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.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,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.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 n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}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,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!ny(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new fs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,f={id:a!=null?a:n==="user"?Qs():n==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=r,x={id:d!=null?d:o==="user"?Qs():o==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,u,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Qs(),s=hs(),a={id:o,role:"user",content:r||$a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=vm(v,this.config.errorMessage);if(E){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=hs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=vm(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}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 n={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-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){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:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,g,f,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let E=null;if(x instanceof Response){if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((g=T==null?void 0:T.error)!=null?g:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(f=this.callbacks).onError)==null||v.call(f,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,g,f,v,x,E,T,L,k,M,P;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!o||!s){(v=(f=this.callbacks).onError)==null||v.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(x=t.toolCall)==null?void 0:x.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let F=typeof((E=R[0])==null?void 0:E.question)=="string"?R[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,F])=>`${R}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};l.forEach((R,F)=>{let j=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!j)return;let W=C[j],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((k=R==null?void 0:R.error)!=null?k:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(P=(M=this.callbacks).onError)==null||P.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.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)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,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:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var P,C,R,F,j,W,O;let f=(P=g.toolCall)==null?void 0:P.name,v=(C=g.toolCall)==null?void 0:C.id;if(!f||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(g),T=(F=(R=g.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?F:f;if(f===Hr)return{dedupeKey:x,resumeKey:T,output:Ki(),toolMessage:g,startedAt:E,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let k=this.client.executeWebMcpToolCall(f,(j=g.toolCall)==null?void 0:j.args,L.signal),M;if(!k)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await k}catch(N){let Y=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return Y||(O=(W=this.callbacks).onError)==null||O.call(W,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(g,ea(Y?"Aborted by cancel()":wm(N)),E),this.webMcpInflightKeys.delete(x),null}return L.signal.aborted?(this.markWebMcpToolComplete(g,ea("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:T,output:M,toolMessage:g,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let f=await this.client.resumeFlow(t,g,{signal:s.signal});if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${f.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((l=v.toolMessage.toolCall)==null?void 0:l.name)===Hr?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ea("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,E,T,L,k,M,P,C,R,F,j;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(E=t.toolCall)==null?void 0:E.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let W=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(W)||this.webMcpResolvedKeys.has(W))return;this.webMcpInflightKeys.add(W);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(W)}catch(O){(M=(k=this.callbacks).onError)==null||M.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(W)}return}let s=`${n}:${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 l=r===Hr,p=(P=t.toolCall)==null?void 0:P.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let W;if(l?W=Ki():u?W=await u:W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ea("Aborted by cancel()"),a);return}let O=(R=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?R:r;g="resume",await this.resumeWithToolOutput(n,O,W,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,W,a,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(W){let O=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));(g==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,ea(O||d.aborted?"Aborted by cancel()":wm(W)),a),O||(j=(F=this.callbacks).onError)==null||j.call(F,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let 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 n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,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:(n=t.component)!=null?n:"",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 n;(n=this.abortController)==null||n.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,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=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=rl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Zs(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=rl(n.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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,W=n.approval;a.approval={...j,...W,executionId:W.executionId||j.executionId,toolName:W.toolName||j.toolName,description:W.description||j.description,toolType:(f=W.toolType)!=null?f:j.toolType,reason:(v=W.reason)!=null?v:j.reason,parameters:(x=W.parameters)!=null?x:j.parameters}}let i=(E=n.toolCall)==null?void 0:E.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,l=(L=n.toolCall)==null?void 0:L.id;if(i&&Cm(i)&&d&&l&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let j=`${d}:${l}`,W=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),N=(M=o.toolCall)==null?void 0:M.name,Y=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===l&&N!==void 0&&Cm(N)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(W||O||Y)&&(a.agentMetadata={...(F=a.agentMetadata)!=null?F:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as ry,ArrowDown as oy,ArrowUp as sy,ArrowUpRight as ay,Bot as iy,ChevronDown as ly,ChevronUp as cy,ChevronRight as dy,ChevronLeft as py,Check as uy,Clipboard as my,ClipboardCopy as gy,Copy as fy,File as hy,FileCode as yy,FileSpreadsheet as by,FileText as xy,ImagePlus as vy,Loader as wy,LoaderCircle as Cy,Mic as Ay,Paperclip as Sy,RefreshCw as Ty,Search as Ey,Send as My,ShieldAlert as ky,ShieldCheck as Ly,ShieldX as Py,Square as Iy,ThumbsDown as Ry,ThumbsUp as Wy,Upload as Hy,Volume2 as By,X as Dy,User as Ny,Mail as Oy,Phone as Fy,Calendar as _y,Clock as $y,Building as jy,MapPin as Uy,Lock as qy,Key as zy,CreditCard as Vy,AtSign as Ky,Hash as Gy,Globe as Jy,Link as Xy,CircleCheck as Qy,CircleX as Yy,TriangleAlert as Zy,Info as eb,Ban as tb,Shield as nb,ArrowLeft as rb,ArrowRight as ob,ExternalLink as sb,Ellipsis as ab,EllipsisVertical as ib,Menu as lb,House as cb,Plus as db,Minus as pb,Pencil as ub,Trash as mb,Trash2 as gb,Save as fb,Download as hb,Share as yb,Funnel as bb,Settings as xb,RotateCw as vb,Maximize as wb,Minimize as Cb,ShoppingCart as Ab,ShoppingBag as Sb,Package as Tb,Truck as Eb,Tag as Mb,Gift as kb,Receipt as Lb,Wallet as Pb,Store as Ib,DollarSign as Rb,Percent as Wb,Play as Hb,Pause as Bb,VolumeX as Db,Camera as Nb,Image as Ob,Film as Fb,Headphones as _b,MessageCircle as $b,MessageSquare as jb,Bell as Ub,Heart as qb,Star as zb,Eye as Vb,EyeOff as Kb,Bookmark as Gb,CalendarDays as Jb,History as Xb,Timer as Qb,Folder as Yb,FolderOpen as Zb,Files as ex,Sparkles as tx,Zap as nx,Sun as rx,Moon as ox,Flag as sx,Monitor as ax,Smartphone as ix}from"lucide";var lx={activity:ry,"arrow-down":oy,"arrow-up":sy,"arrow-up-right":ay,bot:iy,"chevron-down":ly,"chevron-up":cy,"chevron-right":dy,"chevron-left":py,check:uy,clipboard:my,"clipboard-copy":gy,copy:fy,file:hy,"file-code":yy,"file-spreadsheet":by,"file-text":xy,"image-plus":vy,loader:wy,"loader-circle":Cy,mic:Ay,paperclip:Sy,"refresh-cw":Ty,search:Ey,send:My,"shield-alert":ky,"shield-check":Ly,"shield-x":Py,square:Iy,"thumbs-down":Ry,"thumbs-up":Wy,upload:Hy,"volume-2":By,x:Dy,user:Ny,mail:Oy,phone:Fy,calendar:_y,clock:$y,building:jy,"map-pin":Uy,lock:qy,key:zy,"credit-card":Vy,"at-sign":Ky,hash:Gy,globe:Jy,link:Xy,"circle-check":Qy,"circle-x":Yy,"triangle-alert":Zy,info:eb,ban:tb,shield:nb,"arrow-left":rb,"arrow-right":ob,"external-link":sb,ellipsis:ab,"ellipsis-vertical":ib,menu:lb,house:cb,plus:db,minus:pb,pencil:ub,trash:mb,"trash-2":gb,save:fb,download:hb,share:yb,funnel:bb,settings:xb,"rotate-cw":vb,maximize:wb,minimize:Cb,"shopping-cart":Ab,"shopping-bag":Sb,package:Tb,truck:Eb,tag:Mb,gift:kb,receipt:Lb,wallet:Pb,store:Ib,"dollar-sign":Rb,percent:Wb,play:Hb,pause:Bb,"volume-x":Db,camera:Nb,image:Ob,film:Fb,headphones:_b,"message-circle":$b,"message-square":jb,bell:Ub,heart:qb,star:zb,eye:Vb,"eye-off":Kb,bookmark:Gb,"calendar-days":Jb,history:Xb,timer:Qb,folder:Yb,"folder-open":Zb,files:ex,sparkles:tx,zap:nx,sun:rx,moon:ox,flag:sx,monitor:ax,smartphone:ix},me=(e,t=24,n="currentColor",r=2)=>{let o=lx[e];return o?cx(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function cx(e,t,n,r){if(!Array.isArray(e))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",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.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(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var Ka={allowedTypes:Kr,maxFileSize:10*1024*1024,maxFiles:4};function dx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function px(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var xs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ka.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ka.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ka.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:Ka.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 n,r,o,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=pm(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await dm(l),g=Ua(l)?URL.createObjectURL(l):null,f={id:dx(),file:l,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ua(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",n&&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=px(t.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=um(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),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=me("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,n){return new e({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:n})}};var Am=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function na(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Am(s)&&Am(o)?n[r]=na(s,o):n[r]=o}return n}var sr="min(440px, calc(100vw - 24px))",sl="440px",ux={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:sr,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,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:ux,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 Sm(e,t){if(!(!e&&!t))return e?t?na(e,t):e:t}function al(e){var t,n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P;return e?{...Ot,...e,theme:Sm(Ot.theme,e.theme),darkTheme:Sm(Ot.darkTheme,e.darkTheme),launcher:{...Ot.launcher,...e.launcher,dock:{...(t=Ot.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ot.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ot.copy,...e.copy},sendButton:{...Ot.sendButton,...e.sendButton},statusIndicator:{...Ot.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ot.voiceRecognition,...e.voiceRecognition},features:(()=>{var le,se,oe,be,He,V,X,We,K,pe;let C=(le=Ot.features)==null?void 0:le.artifacts,R=(se=e.features)==null?void 0:se.artifacts,F=(oe=Ot.features)==null?void 0:oe.scrollToBottom,j=(be=e.features)==null?void 0:be.scrollToBottom,W=(He=Ot.features)==null?void 0:He.scrollBehavior,O=(V=e.features)==null?void 0:V.scrollBehavior,N=(X=Ot.features)==null?void 0:X.streamAnimation,Y=(We=e.features)==null?void 0:We.streamAnimation,Ee=(K=Ot.features)==null?void 0:K.askUserQuestion,de=(pe=e.features)==null?void 0:pe.askUserQuestion,Z=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},Ce=F===void 0&&j===void 0?void 0:{...F,...j},ke=W===void 0&&O===void 0?void 0:{...W,...O},re=N===void 0&&Y===void 0?void 0:{...N,...Y},we=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Ot.features,...e.features,...Ce!==void 0?{scrollToBottom:Ce}:{},...ke!==void 0?{scrollBehavior:ke}:{},...Z!==void 0?{artifacts:Z}:{},...re!==void 0?{streamAnimation:re}:{},...we!==void 0?{askUserQuestion:we}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Ot.suggestionChips,suggestionChipsConfig:{...Ot.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ot.layout,...e.layout,header:{...(a=Ot.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ot.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Ot.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(x=(v=Ot.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(E=e.layout)==null?void 0:E.messages)==null?void 0:T.timestamp}},slots:{...(L=Ot.layout)==null?void 0:L.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Ot.markdown,...e.markdown,options:{...(M=Ot.markdown)==null?void 0:M.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Ot.messageActions,...e.messageActions}}:Ot}var Tm={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"}},Em={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"}},Mm={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:sr,maxWidth:sl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vs(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?vs(e,r):r}function il(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=vs(e,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&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function km(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Lm(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Lm(s,o):n[r]=o}return n}function mx(e,t){return t?Lm(e,t):e}function ra(e,t={}){var o,s,a,i,d,l,p,u,g,f,v,x,E;let n={palette:Tm,semantic:Em,components:Mm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:mx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=km(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function ll(e){var x,E,T,L,k,M,P,C,R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke,re,we,le,se,oe,be,He,V,X,We,K,pe,$e,ge,Ve,et,$t,Xe,fe,J,dt,qe,Ae,Me,nt,Pt,ee,je,Cn,xt,hn,yr,br,A,te,Te,De,Pe,Ne,Ge,it,It,ce,H,he,Fe,vt,Ye,Ht,Tt,ht,Lt,Qt,Ft,Hn,jt,Bn,Gn,yn,kn,Jn,Xr,wt,xr,vr,Dr,lr,ut,Co,wr,Ao,Ln,Xo,Qr,Nr,Yr,Zr,So,To,eo,bt,Dn,Nn,An,Ct,Xn,Qn,On,to,Or,no,Fn,Rt,Sn,Yn,ro,Fr,oo;let t=il(e),n={};for(let[xe,Pn]of Object.entries(t)){let Cr=xe.replace(/\./g,"-");n[`--persona-${Cr}`]=Pn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(M=n["--persona-semantic-colors-container"])!=null?M:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(W=n["--persona-components-voice-recording-indicator"])!=null?W:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(N=n["--persona-components-voice-processing-icon"])!=null?N:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Y=n["--persona-components-voice-speaking-icon"])!=null?Y:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de:n["--persona-border"],n["--persona-approval-text"]=(Z=n["--persona-components-approval-requested-text"])!=null?Z:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Ce=n["--persona-components-approval-requested-shadow"])!=null?Ce:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=(ke=n["--persona-components-approval-approve-background"])!=null?ke:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(re=n["--persona-components-approval-deny-background"])!=null?re:n["--persona-container"],n["--persona-attachment-image-bg"]=(we=n["--persona-components-attachment-image-background"])!=null?we:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(le=n["--persona-components-attachment-image-border"])!=null?le:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(se=n["--persona-semantic-typography-fontFamily"])!=null?se:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(oe=n["--persona-semantic-typography-fontSize"])!=null?oe:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(be=n["--persona-semantic-typography-fontWeight"])!=null?be:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(He=n["--persona-semantic-typography-lineHeight"])!=null?He:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(X=n["--persona-palette-radius-md"])!=null?X:"0.375rem",n["--persona-radius-lg"]=(We=n["--persona-palette-radius-lg"])!=null?We:"0.5rem",n["--persona-radius-xl"]=(K=n["--persona-palette-radius-xl"])!=null?K:"0.75rem",n["--persona-radius-full"]=(pe=n["--persona-palette-radius-full"])!=null?pe:"9999px",n["--persona-launcher-radius"]=(ge=($e=n["--persona-components-launcher-borderRadius"])!=null?$e:n["--persona-palette-radius-full"])!=null?ge:"9999px",n["--persona-launcher-bg"]=(Ve=n["--persona-components-launcher-background"])!=null?Ve:n["--persona-primary"],n["--persona-launcher-fg"]=(et=n["--persona-components-launcher-foreground"])!=null?et:n["--persona-text-inverse"],n["--persona-launcher-border"]=($t=n["--persona-components-launcher-border"])!=null?$t:n["--persona-border"],n["--persona-button-primary-bg"]=(Xe=n["--persona-components-button-primary-background"])!=null?Xe:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=(dt=(J=n["--persona-components-button-primary-borderRadius"])!=null?J:n["--persona-palette-radius-full"])!=null?dt:"9999px",n["--persona-panel-radius"]=(Ae=(qe=n["--persona-components-panel-borderRadius"])!=null?qe:n["--persona-radius-xl"])!=null?Ae:"0.75rem",n["--persona-panel-border"]=(Me=n["--persona-components-panel-border"])!=null?Me:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Pt=(nt=n["--persona-components-panel-shadow"])!=null?nt:n["--persona-palette-shadows-xl"])!=null?Pt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(ee=n["--persona-components-launcher-shadow"])!=null?ee:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(Cn=(je=n["--persona-components-input-borderRadius"])!=null?je:n["--persona-radius-lg"])!=null?Cn:"0.5rem",n["--persona-message-user-radius"]=(hn=(xt=n["--persona-components-message-user-borderRadius"])!=null?xt:n["--persona-radius-lg"])!=null?hn:"0.5rem",n["--persona-message-assistant-radius"]=(br=(yr=n["--persona-components-message-assistant-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?br:"0.5rem",n["--persona-header-bg"]=(A=n["--persona-components-header-background"])!=null?A:n["--persona-surface"],n["--persona-header-border"]=(te=n["--persona-components-header-border"])!=null?te:n["--persona-divider"],n["--persona-header-icon-bg"]=(Te=n["--persona-components-header-iconBackground"])!=null?Te:n["--persona-primary"],n["--persona-header-icon-fg"]=(De=n["--persona-components-header-iconForeground"])!=null?De:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pe=n["--persona-components-header-titleForeground"])!=null?Pe:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Ne=n["--persona-components-header-subtitleForeground"])!=null?Ne:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ge=n["--persona-components-header-actionIconForeground"])!=null?Ge:n["--persona-muted"];let r=(it=e.components)==null?void 0:it.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(It=e.components)==null?void 0:It.introCard;n["--persona-intro-card-bg"]=(ce=n["--persona-components-introCard-background"])!=null?ce:n["--persona-surface"],n["--persona-intro-card-radius"]=(H=n["--persona-components-introCard-borderRadius"])!=null?H:"1rem",n["--persona-intro-card-padding"]=(he=n["--persona-components-introCard-padding"])!=null?he:"1.5rem",n["--persona-intro-card-shadow"]=(vt=(Fe=o==null?void 0:o.shadow)!=null?Fe:n["--persona-components-introCard-shadow"])!=null?vt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ye=n["--persona-components-input-background"])!=null?Ye:n["--persona-surface"],n["--persona-input-placeholder"]=(Ht=n["--persona-components-input-placeholder"])!=null?Ht:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Tt=n["--persona-components-message-user-background"])!=null?Tt:n["--persona-accent"],n["--persona-message-user-text"]=(ht=n["--persona-components-message-user-text"])!=null?ht:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Lt=n["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qt=n["--persona-components-message-assistant-background"])!=null?Qt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ft=n["--persona-components-message-assistant-text"])!=null?Ft:n["--persona-text"],n["--persona-message-assistant-border"]=(Hn=n["--persona-components-message-assistant-border"])!=null?Hn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(jt=n["--persona-components-message-assistant-shadow"])!=null?jt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Gn=(Bn=n["--persona-components-scrollToBottom-background"])!=null?Bn:n["--persona-button-primary-bg"])!=null?Gn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(kn=(yn=n["--persona-components-scrollToBottom-foreground"])!=null?yn:n["--persona-button-primary-fg"])!=null?kn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Jn=n["--persona-components-scrollToBottom-border"])!=null?Jn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Xr=n["--persona-components-scrollToBottom-size"])!=null?Xr:"40px",n["--persona-scroll-to-bottom-radius"]=(vr=(xr=(wt=n["--persona-components-scrollToBottom-borderRadius"])!=null?wt:n["--persona-button-radius"])!=null?xr:n["--persona-radius-full"])!=null?vr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(lr=(Dr=n["--persona-components-scrollToBottom-shadow"])!=null?Dr:n["--persona-palette-shadows-sm"])!=null?lr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(ut=n["--persona-components-scrollToBottom-padding"])!=null?ut:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Co=n["--persona-components-scrollToBottom-gap"])!=null?Co:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Ao=(wr=n["--persona-components-scrollToBottom-fontSize"])!=null?wr:n["--persona-palette-typography-fontSize-sm"])!=null?Ao:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Ln=n["--persona-components-scrollToBottom-iconSize"])!=null?Ln:"14px",n["--persona-tool-bubble-shadow"]=(Xo=n["--persona-components-toolBubble-shadow"])!=null?Xo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Qr=n["--persona-components-reasoningBubble-shadow"])!=null?Qr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Nr=n["--persona-components-composer-shadow"])!=null?Nr:"none",n["--persona-md-inline-code-bg"]=(Yr=n["--persona-components-markdown-inlineCode-background"])!=null?Yr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Zr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Zr:n["--persona-text"],n["--persona-md-link-color"]=(To=(So=n["--persona-components-markdown-link-foreground"])!=null?So:n["--persona-accent"])!=null?To:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(eo=n["--persona-components-markdown-codeBlock-background"])!=null?eo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(bt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?bt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Dn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Dn:"inherit",n["--persona-md-table-header-bg"]=(Nn=n["--persona-components-markdown-table-headerBackground"])!=null?Nn:n["--persona-container"],n["--persona-md-table-border-color"]=(An=n["--persona-components-markdown-table-borderColor"])!=null?An:n["--persona-border"],n["--persona-md-hr-color"]=(Ct=n["--persona-components-markdown-hr-color"])!=null?Ct:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Xn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Xn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Qn=n["--persona-components-markdown-blockquote-background"])!=null?Qn:"transparent",n["--persona-md-blockquote-text-color"]=(On=n["--persona-components-markdown-blockquote-textColor"])!=null?On:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(to=n["--persona-components-collapsibleWidget-container"])!=null?to:n["--persona-surface"],n["--cw-surface"]=(Or=n["--persona-components-collapsibleWidget-surface"])!=null?Or:n["--persona-surface"],n["--cw-border"]=(no=n["--persona-components-collapsibleWidget-border"])!=null?no:n["--persona-border"],n["--persona-message-border"]=(Fn=n["--persona-components-message-border"])!=null?Fn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let xe=v.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(Rt=n["--persona-dropdown-bg"])!=null?Rt:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(Sn=n["--persona-dropdown-border"])!=null?Sn:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(Yn=n["--persona-dropdown-shadow"])!=null?Yn:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ro=n["--persona-dropdown-radius"])!=null?ro:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Fr=n["--persona-dropdown-item-hover-bg"])!=null?Fr:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(v!=null&&v.tab){let xe=v.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(v!=null&&v.pane){let xe=v.pane;if(xe.toolbarBackground){let Pn=(oo=vs(e,xe.toolbarBackground))!=null?oo:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Pn}}return n}var gx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var fx={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"}}},Pm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ga=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},hx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ga()},Im=e=>hx(e),yx=e=>ra(e),bx=e=>{var n;let t=ra(void 0,{validate:!1});return ra({...e,palette:{...t.palette,colors:{...fx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},oa=e=>{let t=Im(e),n=Pm(e==null?void 0:e.theme),r=Pm(e==null?void 0:e.darkTheme);return t==="dark"?bx(na(n!=null?n:{},r!=null?r:{})):yx(n)},xx=e=>ll(e),qo=(e,t)=>{let n=oa(t),r=xx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},cl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ga())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ga());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as vx}from"idiomorph";var Ja=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;vx.morph(e,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:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Rm=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Xa={index:-1,draft:""};function Wm(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Xa}}}function Hm(e,t){var n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke,re,we,le,se,oe;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(E=(x=e.toolCall)==null?void 0:x.name)!=null?E:"",(k=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?k:0,(R=(C=(P=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(N=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?N:0,(Z=(de=(Ee=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?Z:0,(we=(re=(ke=(Ce=e.reasoning)==null?void 0:Ce.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:re.slice(-32))!=null?we:"",(se=(le=e.contentParts)==null?void 0:le.length)!=null?se:0,(oe=e.stopReason)!=null?oe:"",t].join("\0")}function Bm(){return new Map}function Dm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Nm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Om(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Qa(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Gr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function zo(e,t){return Gr(e)-e.scrollTop<=t}function Ya(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Za(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function Fm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function _m(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function $m(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var vn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,ho=wn+1;var sa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},wx=["pre","code","a","script","style"],ei=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:sa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:sa.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:sa.speed,duration:(o=e==null?void 0:e.duration)!=null?o:sa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:sa.buffer}},Um=[{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"}],aa=new Map;for(let e of Um)aa.set(e.name,e);var Cx=e=>{aa.set(e.name,e)},Ax=e=>{Um.some(t=>t.name===e)||aa.delete(e)},Sx=()=>Array.from(aa.keys()),ia=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=aa.get(e))!=null?r:null},ti=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
19
- `);return s<0?"":e.slice(0,s)}return e},Tx=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Ex=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},dl=/\s/,Mx=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},kx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(dl.test(s[i])){let l=i;for(;l<s.length&&dl.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!dl.test(s[p]);)l.appendChild(Tx(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Lx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Ex(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},la=(e,t,n,r)=>{var u,g;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:wx).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Mx(d,s)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?kx:Lx;for(let f of i)p(f,n,l);return o.innerHTML},ni=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ca=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},jm=new WeakMap,Px=(e,t)=>{var s;if(!e.styles)return;let n=jm.get(t);if(n||(n=new Set,jm.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},pl=new WeakMap,Ix=(e,t)=>{if(!e.onAttach)return;let n=pl.get(t);if(n||(n=new Map,pl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},qm=e=>{let t=pl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ul=(e,t)=>{Px(e,t),Ix(e,t)};function ml(e,t=wn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var da=0,yo=null;function gl(e=document){var n;if(da++,da===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;yo={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,da=Math.max(0,da-1),da===0&&yo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=yo.originalOverflow,o.style.position=yo.originalPosition,o.style.top=yo.originalTop,o.style.width=yo.originalWidth,s.scrollTo(0,yo.scrollY),yo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},cn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},bo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},ar=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:pa.side,width:(o=t==null?void 0:t.width)!=null?o:pa.width,animate:(s=t==null?void 0:t.animate)!=null?s:pa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:pa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:pa.maxHeight}};var hr={"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 Rx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ri=(e,t={})=>{var E,T,L,k,M,P;let{showClose:n=!0,wrapperClassName:r=Rx,buttonSize:o,iconSize:s="28px"}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),l=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0,u=(M=a.closeButtonIconName)!=null?M:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=St("button",{className:qs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Mn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=me(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),p&&l){let C=null,R=()=>{if(C)return;let j=v.ownerDocument,W=j.body;if(!W)return;C=Wr(j,"div","persona-clear-chat-tooltip"),C.textContent=l;let O=Wr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(ho),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",W.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",R),d.addEventListener("mouseleave",F),v.addEventListener("focus",R),v.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",R),d.removeEventListener("mouseleave",F),v.removeEventListener("focus",R),v.removeEventListener("blur",F)}}return{button:v,wrapper:d}},Wx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oi=(e,t={})=>{var C,R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke;let{wrapperClassName:n=Wx,buttonSize:r,iconSize:o="20px"}=t,a=(R=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?R:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",l=(W=a.iconColor)!=null?W:"",p=(O=a.backgroundColor)!=null?O:"",u=(N=a.borderWidth)!=null?N:"",g=(Y=a.borderColor)!=null?Y:"",f=(Ee=a.borderRadius)!=null?Ee:"",v=(de=a.paddingX)!=null?de:"",x=(Z=a.paddingY)!=null?Z:"",E=(Ce=a.tooltipText)!=null?Ce:"Clear chat",T=(ke=a.showTooltip)!=null?ke:!0,L=y("div",n),k=!!(u||g),M=St("button",{className:qs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:l||Mn.actionIconColor,backgroundColor:p||void 0,border:k?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),P=me(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),L.appendChild(M),T&&E){let re=null,we=()=>{if(re)return;let se=M.ownerDocument,oe=se.body;if(!oe)return;re=Wr(se,"div","persona-clear-chat-tooltip"),re.textContent=E;let be=Wr(se,"div");be.className="persona-clear-chat-tooltip-arrow",re.appendChild(be);let He=M.getBoundingClientRect();re.style.position="fixed",re.style.zIndex=String(ho),re.style.left=`${He.left+He.width/2}px`,re.style.top=`${He.top-8}px`,re.style.transform="translate(-50%, -100%)",oe.appendChild(re)},le=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};L.addEventListener("mouseenter",we),L.addEventListener("mouseleave",le),M.addEventListener("focus",we),M.addEventListener("blur",le),L._cleanupTooltip=()=>{le(),L.removeEventListener("mouseenter",we),L.removeEventListener("mouseleave",le),M.removeEventListener("focus",we),M.removeEventListener("blur",le)}}return{button:M,wrapper:L}};var Mn={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))"},xo=e=>{var P,C,R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke,re,we;let{config:t,showClose:n=!0}=e,r=St("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=t==null?void 0:t.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(R=o.closeButtonPlacement)!=null?R:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,l=St("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 le=parseFloat(s)||24,se=me(d,le*.6,"currentColor",1);se?l.replaceChildren(se):l.textContent=(W=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let le=y("img");le.src=t.launcher.iconUrl,le.alt="",le.className="persona-rounded-xl persona-object-cover",le.style.height=s,le.style.width=s,l.replaceChildren(le)}else l.textContent=(Y=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?Y:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=St("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:Mn.titleColor}}),g=St("span",{className:"persona-text-xs",text:(Ce=(Z=t==null?void 0:t.launcher)==null?void 0:Z.subtitle)!=null?Ce:"Here to help you get answers fast",style:{color:Mn.subtitleColor}});p.append(u,g),i?r.append(p):r.append(l,p);let f=(ke=o.clearChat)!=null?ke:{},v=(re=f.enabled)!=null?re:!0,x=(we=f.placement)!=null?we:"inline",E=null,T=null;if(v){let se=oi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=se.button,T=se.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let L=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:k,wrapper:M}=ri(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:k,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:T}},ws=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Vo(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,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(ho)):(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 f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let E=me(f.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),p(),n(f.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:g}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=me(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function si(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=me(t,s!=null?s:14,"currentColor",2);g&&p.appendChild(g)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function ai(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function fl(e){var f,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=me(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,E;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Vo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let E=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var zm=e=>{var r;let t=xo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Hx(e,t,n){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=me(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 l=Vo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Vm=e=>{var L,k,M,P,C,R,F,j,W;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},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,l,p;if(d)l=fl({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(M=l.querySelector(".persona-combo-btn-label"))!=null?M:l;else{if(l=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(p),Hx(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let N=o.onTitleClick;l.addEventListener("click",Y=>{Y.target.closest("button")||N()}),l.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),N())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(R=O.borderRadius)!=null?R:"10px",l.style.padding=(F=O.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var N,Y;l.style.backgroundColor=(N=O.background)!=null?N:"",l.style.borderColor=(Y=O.border)!=null?Y:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(j=a.closeButtonSize)!=null?j:"32px",g=y("div",""),f=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");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Mn.actionIconColor;let v=(W=a.closeButtonIconName)!=null?W:"x",x=me(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let E=y("div");E.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},hl={default:zm,minimal:Vm},Km=e=>{var t;return(t=hl[e])!=null?t:hl.default},ua=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),g=y("span"),f=y("button");f.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=Km(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig: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 ii=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.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 n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*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}},li=e=>{var P,C,R,F,j,W,O,N,Y,Ee,de,Z;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",o=t.iconName,s=(F=t.stopIconName)!=null?F:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(N=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?N:"Send",l=(Ee=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?Ee:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(Z=t.size)!=null?Z:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=St("button",{className:qs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&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}}),E=null,T=null;if(n){let Ce=parseFloat(u)||24,ke=(f==null?void 0:f.trim())||"currentColor";o?(E=me(o,Ce,ke,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,T=me(s,Ce,ke,2)}else x.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:Ce=>{if(Ce===k)return;k=Ce;let ke=Ce==="stop"?i:a;if(x.setAttribute("aria-label",ke),L&&(L.textContent=ke),n){if(E&&T){let re=Ce==="stop"?T:E;x.replaceChildren(re)}}else x.textContent=Ce==="stop"?l:d}}},ci=e=>{var L,k,M,P,C,R,F,j,W,O,N,Y;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(C=t.iconName)!=null?C:"mic",d=(R=t.iconSize)!=null?R:a,l=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,u=(O=t.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor,g=y("div","persona-send-button-wrapper"),f=St("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:u||"var(--persona-text, #111827)",backgroundColor:p||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=me(i,l,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",g.appendChild(f);let E=(N=t.tooltipText)!=null?N:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&E){let Ee=y("div","persona-send-button-tooltip");Ee.textContent=E,g.appendChild(Ee)}return{button:f,wrapper:g}},di=e=>{var v,x,E,T,L,k,M,P;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(E=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?E:"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=((T=t.allowedTypes)!=null?T:Kr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=t.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),l=y("div","persona-send-button-wrapper"),p=St("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":(M=t.buttonTooltipText)!=null?M:"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"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=me(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),l.appendChild(p);let g=(P=t.buttonTooltipText)!=null?P:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,l.appendChild(f),{button:p,wrapper:l,input:o,previewsContainer:r}},pi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},ui=()=>St("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ma=e=>{var v,x,E,T,L,k;let{config:t}=e,n=St("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=ui(),o=St("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}=ii(t);a();let i=li(t),d=ci(t),l=di(t),p=pi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=St("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(g,f),o.append(u),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,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:p,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var Gm=()=>{let e=St("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"),n=me("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=me("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},Jm=e=>{var v,x,E,T,L,k;let{config:t}=e,n=St("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ui();r.style.display="none";let o=pi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ii(t);s.style.maxHeight="100px",a();let i=li(t),d=ci(t),l=di(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=St("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,g),l&&n.append(l.previewsContainer),n.append(p,r,o);let f=p;return{footer:n,suggestions:r,composerForm:p,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:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Xm=e=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=cn(e);if(bo(e)){let O=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(v=O.expandedSize)!=null?v:"anchored",N.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:wn);let Y=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",N.appendChild(Y);let Ee=y("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",Ee.style.zIndex=String((k=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?k:wn),{wrapper:N,panel:Y,pillRoot:Ee}}if(n){let O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(N),{wrapper:O,panel:N}}if(!t){let O=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?P:"100%";return O.style.width=Y,N.style.width="100%",O.appendChild(N),{wrapper:O,panel:N}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&hr[o.position]?hr[o.position]:hr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?F:wn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Bx=(e,t)=>{var M,P,C,R,F,j,W,O,N;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=ri(e,{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=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Y=oi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Y.button,i=Y.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=St("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=St("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"}});l.style.setProperty("scrollbar-gutter","stable");let p=St("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),u=St("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),g=St("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((N=e==null?void 0:e.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(g,f);let E=St("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=Jm({config:e}),{root:L,textNode:k}=Gm();return n.append(d,o,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:f,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:k}},Qm=(e,t=!0)=>{var E,T,L,k,M,P,C,R,F;if(bo(e))return Bx(e,t);let n=St("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=(E=e==null?void 0:e.layout)==null?void 0:E.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?ua(e,r,{showClose:t}):xo({config:e,showClose:t}),a=St("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=St("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=St("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),l=St("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:cn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(l.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(l,p);let f=ma({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;o?ws(n,s,e):(s.header.style.display="none",ws(n,s,e)),n.append(a);let x=St("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||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle: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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var yl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
18
+ _Details: ${n.message}_`:r}var la=e=>({isError:!0,content:[{type:"text",text:e}]}),Dm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Nm=e=>Ko(e)||e===Or,ca=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 Ss(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,l,p,u;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(Ko(g.name)||g.name===Or&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&f&&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 g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,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 ws(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,l;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(l=(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)!=null?l:this.config.agentId;!n||!r||!this.config.clientToken||pl().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 Ja((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,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.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,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Yo.isSupported()?new Yo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(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)!=null?d:this.config.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(l&&p&&u)return pl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:v})=>{let x=new f({host:l,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&n?new v(x,n,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):x});if(g&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Qo(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,l;(l=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||l.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,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(d=this.callbacks).onVoiceStatusChanged)==null||l.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 n,r,o,s,a,i,d,l,p,u,g,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(l=(d=t.runtype)==null?void 0:d.host)!=null?l:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.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,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.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 n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}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,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!wy(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new ws(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:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,f={id:a!=null?a:n==="user"?sa():n==="assistant"?Cs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=r,x={id:d!=null?d:o==="user"?sa():o==="assistant"?Cs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,u,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=sa(),s=Cs(),a={id:o,role:"user",content:r||Va,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=Bm(v,this.config.errorMessage);if(E){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Cs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=Bm(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}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 n={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-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){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:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,g,f,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let E=null;if(x instanceof Response){if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((g=T==null?void 0:T.error)!=null?g:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(f=this.callbacks).onError)==null||v.call(f,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,g,f,v,x,E,T,L,k,M,P;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!o||!s){(v=(f=this.callbacks).onError)==null||v.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(x=t.toolCall)==null?void 0:x.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let F=typeof((E=R[0])==null?void 0:E.question)=="string"?R[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,F])=>`${R}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};l.forEach((R,F)=>{let j=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!j)return;let H=C[j],O=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((k=R==null?void 0:R.error)!=null?k:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(P=(M=this.callbacks).onError)==null||P.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.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)!==Or)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,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:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var P,C,R,F,j,H,O;let f=(P=g.toolCall)==null?void 0:P.name,v=(C=g.toolCall)==null?void 0:C.id;if(!f||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(g),T=(F=(R=g.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?F:f;if(f===Or)return{dedupeKey:x,resumeKey:T,output:el(),toolMessage:g,startedAt:E,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let k=this.client.executeWebMcpToolCall(f,(j=g.toolCall)==null?void 0:j.args,L.signal),M;if(!k)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await k}catch(N){let Y=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return Y||(O=(H=this.callbacks).onError)==null||O.call(H,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(g,la(Y?"Aborted by cancel()":Dm(N)),E),this.webMcpInflightKeys.delete(x),null}return L.signal.aborted?(this.markWebMcpToolComplete(g,la("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:T,output:M,toolMessage:g,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let f=await this.client.resumeFlow(t,g,{signal:s.signal});if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${f.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((l=v.toolMessage.toolCall)==null?void 0:l.name)===Or?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,la("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,E,T,L,k,M,P,C,R,F,j;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(E=t.toolCall)==null?void 0:E.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let H=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(H)||this.webMcpResolvedKeys.has(H))return;this.webMcpInflightKeys.add(H);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(H)}catch(O){(M=(k=this.callbacks).onError)==null||M.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(H)}return}let s=`${n}:${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 l=r===Or,p=(P=t.toolCall)==null?void 0:P.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let H;if(l?H=el():u?H=await u:H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,la("Aborted by cancel()"),a);return}let O=(R=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?R:r;g="resume",await this.resumeWithToolOutput(n,O,H,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,H,a,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(H){let O=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));(g==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,la(O||d.aborted?"Aborted by cancel()":Dm(H)),a),O||(j=(F=this.callbacks).onError)==null||j.call(F,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let 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 n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,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:(n=t.component)!=null?n:"",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 n;(n=this.abortController)==null||n.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,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=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=dl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=dl(n.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 n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,H=n.approval;a.approval={...j,...H,executionId:H.executionId||j.executionId,toolName:H.toolName||j.toolName,description:H.description||j.description,toolType:(f=H.toolType)!=null?f:j.toolType,reason:(v=H.reason)!=null?v:j.reason,parameters:(x=H.parameters)!=null?x:j.parameters}}let i=(E=n.toolCall)==null?void 0:E.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,l=(L=n.toolCall)==null?void 0:L.id;if(i&&Nm(i)&&d&&l&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let j=`${d}:${l}`,H=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),N=(M=o.toolCall)==null?void 0:M.name,Y=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===l&&N!==void 0&&Nm(N)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(H||O||Y)&&(a.agentMetadata={...(F=a.agentMetadata)!=null?F:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as Cy,ArrowDown as Ay,ArrowUp as Sy,ArrowUpRight as Ty,Bot as Ey,ChevronDown as My,ChevronUp as ky,ChevronRight as Ly,ChevronLeft as Py,Check as Iy,Clipboard as Ry,ClipboardCopy as Wy,Copy as Hy,File as By,FileCode as Dy,FileSpreadsheet as Ny,FileText as Oy,ImagePlus as Fy,Loader as _y,LoaderCircle as $y,Mic as jy,Paperclip as Uy,RefreshCw as qy,Search as zy,Send as Vy,ShieldAlert as Ky,ShieldCheck as Gy,ShieldX as Jy,Square as Xy,ThumbsDown as Qy,ThumbsUp as Yy,Upload as Zy,Volume2 as eb,X as tb,User as nb,Mail as rb,Phone as ob,Calendar as sb,Clock as ab,Building as ib,MapPin as lb,Lock as cb,Key as db,CreditCard as pb,AtSign as ub,Hash as mb,Globe as gb,Link as fb,CircleCheck as hb,CircleX as yb,TriangleAlert as bb,Info as xb,Ban as vb,Shield as wb,ArrowLeft as Cb,ArrowRight as Ab,ExternalLink as Sb,Ellipsis as Tb,EllipsisVertical as Eb,Menu as Mb,House as kb,Plus as Lb,Minus as Pb,Pencil as Ib,Trash as Rb,Trash2 as Wb,Save as Hb,Download as Bb,Share as Db,Funnel as Nb,Settings as Ob,RotateCw as Fb,Maximize as _b,Minimize as $b,ShoppingCart as jb,ShoppingBag as Ub,Package as qb,Truck as zb,Tag as Vb,Gift as Kb,Receipt as Gb,Wallet as Jb,Store as Xb,DollarSign as Qb,Percent as Yb,Play as Zb,Pause as ex,VolumeX as tx,Camera as nx,Image as rx,Film as ox,Headphones as sx,MessageCircle as ax,MessageSquare as ix,Bell as lx,Heart as cx,Star as dx,Eye as px,EyeOff as ux,Bookmark as mx,CalendarDays as gx,History as fx,Timer as hx,Folder as yx,FolderOpen as bx,Files as xx,Sparkles as vx,Zap as wx,Sun as Cx,Moon as Ax,Flag as Sx,Monitor as Tx,Smartphone as Ex}from"lucide";var Mx={activity:Cy,"arrow-down":Ay,"arrow-up":Sy,"arrow-up-right":Ty,bot:Ey,"chevron-down":My,"chevron-up":ky,"chevron-right":Ly,"chevron-left":Py,check:Iy,clipboard:Ry,"clipboard-copy":Wy,copy:Hy,file:By,"file-code":Dy,"file-spreadsheet":Ny,"file-text":Oy,"image-plus":Fy,loader:_y,"loader-circle":$y,mic:jy,paperclip:Uy,"refresh-cw":qy,search:zy,send:Vy,"shield-alert":Ky,"shield-check":Gy,"shield-x":Jy,square:Xy,"thumbs-down":Qy,"thumbs-up":Yy,upload:Zy,"volume-2":eb,x:tb,user:nb,mail:rb,phone:ob,calendar:sb,clock:ab,building:ib,"map-pin":lb,lock:cb,key:db,"credit-card":pb,"at-sign":ub,hash:mb,globe:gb,link:fb,"circle-check":hb,"circle-x":yb,"triangle-alert":bb,info:xb,ban:vb,shield:wb,"arrow-left":Cb,"arrow-right":Ab,"external-link":Sb,ellipsis:Tb,"ellipsis-vertical":Eb,menu:Mb,house:kb,plus:Lb,minus:Pb,pencil:Ib,trash:Rb,"trash-2":Wb,save:Hb,download:Bb,share:Db,funnel:Nb,settings:Ob,"rotate-cw":Fb,maximize:_b,minimize:$b,"shopping-cart":jb,"shopping-bag":Ub,package:qb,truck:zb,tag:Vb,gift:Kb,receipt:Gb,wallet:Jb,store:Xb,"dollar-sign":Qb,percent:Yb,play:Zb,pause:ex,"volume-x":tx,camera:nx,image:rx,film:ox,headphones:sx,"message-circle":ax,"message-square":ix,bell:lx,heart:cx,star:dx,eye:px,"eye-off":ux,bookmark:mx,"calendar-days":gx,history:fx,timer:hx,folder:yx,"folder-open":bx,files:xx,sparkles:vx,zap:wx,sun:Cx,moon:Ax,flag:Sx,monitor:Tx,smartphone:Ex},ge=(e,t=24,n="currentColor",r=2)=>{let o=Mx[e];return o?kx(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function kx(e,t,n,r){if(!Array.isArray(e))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",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.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(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var Ya={allowedTypes:Zr,maxFileSize:10*1024*1024,maxFiles:4};function Lx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Px(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ts=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ya.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ya.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:Ya.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 n,r,o,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Em(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Tm(l),g=Ga(l)?URL.createObjectURL(l):null,f={id:Lx(),file:l,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(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",n&&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=Px(t.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=Mm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),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=ge("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,n){return new e({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:n})}};var Om=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function da(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Om(s)&&Om(o)?n[r]=da(s,o):n[r]=o}return n}var nr="min(440px, calc(100vw - 24px))",ul="440px",Ix={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:nr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Dt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ix,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,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 Fm(e,t){if(!(!e&&!t))return e?t?da(e,t):e:t}function ml(e){var t,n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P;return e?{...Dt,...e,theme:Fm(Dt.theme,e.theme),darkTheme:Fm(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var se,ie,ae,xe,Be,V,X,He,K,ue;let C=(se=Dt.features)==null?void 0:se.artifacts,R=(ie=e.features)==null?void 0:ie.artifacts,F=(ae=Dt.features)==null?void 0:ae.scrollToBottom,j=(xe=e.features)==null?void 0:xe.scrollToBottom,H=(Be=Dt.features)==null?void 0:Be.scrollBehavior,O=(V=e.features)==null?void 0:V.scrollBehavior,N=(X=Dt.features)==null?void 0:X.streamAnimation,Y=(He=e.features)==null?void 0:He.streamAnimation,ke=(K=Dt.features)==null?void 0:K.askUserQuestion,pe=(ue=e.features)==null?void 0:ue.askUserQuestion,Z=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},Te=F===void 0&&j===void 0?void 0:{...F,...j},Le=H===void 0&&O===void 0?void 0:{...H,...O},oe=N===void 0&&Y===void 0?void 0:{...N,...Y},Ae=ke===void 0&&pe===void 0?void 0:{...ke,...pe,styles:{...ke==null?void 0:ke.styles,...pe==null?void 0:pe.styles}};return{...Dt.features,...e.features,...Te!==void 0?{scrollToBottom:Te}:{},...Le!==void 0?{scrollBehavior:Le}:{},...Z!==void 0?{artifacts:Z}:{},...oe!==void 0?{streamAnimation:oe}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(x=(v=Dt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(E=e.layout)==null?void 0:E.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(M=Dt.markdown)==null?void 0:M.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var _m={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"}},$m={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"}},jm={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:nr,maxWidth:ul,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Es(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Es(e,r):r}function gl(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Es(e,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&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Um(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function qm(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=qm(s,o):n[r]=o}return n}function Rx(e,t){return t?qm(e,t):e}function pa(e,t={}){var o,s,a,i,d,l,p,u,g,f,v,x,E;let n={palette:_m,semantic:$m,components:jm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Rx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=Um(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function fl(e){var x,E,T,L,k,M,P,C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae,se,ie,ae,xe,Be,V,X,He,K,ue,$e,fe,Ve,et,Ot,Xe,ye,J,dt,qe,Se,ve,nt,Lt,ee,je,wn,bt,fn,xr,vr,A,te,Me,Ne,Ie,Oe,Ge,at,Pt,ce,B,be,_e,xt,Ye,Rt,St,ht,kt,Xt,Ft,en,wr,$r,sr,ar,to,qt,ir,jr,In,kn,Rn,lr,Cr,no,qn,ro,vt,Ar,Sr,Ur,cr,ut,Io,Tr,Ro,Ln,os,oo,qr,so,ao,Wo,Ho,io,yt,Wn,Hn,Cn,wt,zn,Vn,Bn,lo;let t=gl(e),n={};for(let[Ce,zr]of Object.entries(t)){let Kn=Ce.replace(/\./g,"-");n[`--persona-${Kn}`]=zr.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(M=n["--persona-semantic-colors-container"])!=null?M:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(N=n["--persona-components-voice-processing-icon"])!=null?N:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Y=n["--persona-components-voice-speaking-icon"])!=null?Y:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ke=n["--persona-components-approval-requested-background"])!=null?ke:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(Z=n["--persona-components-approval-requested-text"])!=null?Z:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Te=n["--persona-components-approval-requested-shadow"])!=null?Te:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=(Le=n["--persona-components-approval-approve-background"])!=null?Le:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(oe=n["--persona-components-approval-deny-background"])!=null?oe:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(se=n["--persona-components-attachment-image-border"])!=null?se:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ie=n["--persona-semantic-typography-fontFamily"])!=null?ie:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(xe=n["--persona-semantic-typography-fontWeight"])!=null?xe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Be=n["--persona-semantic-typography-lineHeight"])!=null?Be:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(X=n["--persona-palette-radius-md"])!=null?X:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(K=n["--persona-palette-radius-xl"])!=null?K:"0.75rem",n["--persona-radius-full"]=(ue=n["--persona-palette-radius-full"])!=null?ue:"9999px",n["--persona-launcher-radius"]=(fe=($e=n["--persona-components-launcher-borderRadius"])!=null?$e:n["--persona-palette-radius-full"])!=null?fe:"9999px",n["--persona-launcher-bg"]=(Ve=n["--persona-components-launcher-background"])!=null?Ve:n["--persona-primary"],n["--persona-launcher-fg"]=(et=n["--persona-components-launcher-foreground"])!=null?et:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ot=n["--persona-components-launcher-border"])!=null?Ot:n["--persona-border"],n["--persona-button-primary-bg"]=(Xe=n["--persona-components-button-primary-background"])!=null?Xe:n["--persona-primary"],n["--persona-button-primary-fg"]=(ye=n["--persona-components-button-primary-foreground"])!=null?ye:n["--persona-text-inverse"],n["--persona-button-radius"]=(dt=(J=n["--persona-components-button-primary-borderRadius"])!=null?J:n["--persona-palette-radius-full"])!=null?dt:"9999px",n["--persona-panel-radius"]=(Se=(qe=n["--persona-components-panel-borderRadius"])!=null?qe:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(ve=n["--persona-components-panel-border"])!=null?ve:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Lt=(nt=n["--persona-components-panel-shadow"])!=null?nt:n["--persona-palette-shadows-xl"])!=null?Lt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(ee=n["--persona-components-launcher-shadow"])!=null?ee:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(wn=(je=n["--persona-components-input-borderRadius"])!=null?je:n["--persona-radius-lg"])!=null?wn:"0.5rem",n["--persona-message-user-radius"]=(fn=(bt=n["--persona-components-message-user-borderRadius"])!=null?bt:n["--persona-radius-lg"])!=null?fn:"0.5rem",n["--persona-message-assistant-radius"]=(vr=(xr=n["--persona-components-message-assistant-borderRadius"])!=null?xr:n["--persona-radius-lg"])!=null?vr:"0.5rem",n["--persona-header-bg"]=(A=n["--persona-components-header-background"])!=null?A:n["--persona-surface"],n["--persona-header-border"]=(te=n["--persona-components-header-border"])!=null?te:n["--persona-divider"],n["--persona-header-icon-bg"]=(Me=n["--persona-components-header-iconBackground"])!=null?Me:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ne=n["--persona-components-header-iconForeground"])!=null?Ne:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Ie=n["--persona-components-header-titleForeground"])!=null?Ie:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Oe=n["--persona-components-header-subtitleForeground"])!=null?Oe:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ge=n["--persona-components-header-actionIconForeground"])!=null?Ge:n["--persona-muted"];let r=(at=e.components)==null?void 0:at.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(Pt=e.components)==null?void 0:Pt.introCard;n["--persona-intro-card-bg"]=(ce=n["--persona-components-introCard-background"])!=null?ce:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(be=n["--persona-components-introCard-padding"])!=null?be:"1.5rem",n["--persona-intro-card-shadow"]=(xt=(_e=o==null?void 0:o.shadow)!=null?_e:n["--persona-components-introCard-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ye=n["--persona-components-input-background"])!=null?Ye:n["--persona-surface"],n["--persona-input-placeholder"]=(Rt=n["--persona-components-input-placeholder"])!=null?Rt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(St=n["--persona-components-message-user-background"])!=null?St:n["--persona-accent"],n["--persona-message-user-text"]=(ht=n["--persona-components-message-user-text"])!=null?ht:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(kt=n["--persona-components-message-user-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ft=n["--persona-components-message-assistant-text"])!=null?Ft:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(wr=n["--persona-components-message-assistant-shadow"])!=null?wr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(sr=($r=n["--persona-components-scrollToBottom-background"])!=null?$r:n["--persona-button-primary-bg"])!=null?sr:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(to=(ar=n["--persona-components-scrollToBottom-foreground"])!=null?ar:n["--persona-button-primary-fg"])!=null?to:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(qt=n["--persona-components-scrollToBottom-border"])!=null?qt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ir=n["--persona-components-scrollToBottom-size"])!=null?ir:"40px",n["--persona-scroll-to-bottom-radius"]=(kn=(In=(jr=n["--persona-components-scrollToBottom-borderRadius"])!=null?jr:n["--persona-button-radius"])!=null?In:n["--persona-radius-full"])!=null?kn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(lr=(Rn=n["--persona-components-scrollToBottom-shadow"])!=null?Rn:n["--persona-palette-shadows-sm"])!=null?lr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Cr=n["--persona-components-scrollToBottom-padding"])!=null?Cr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(no=n["--persona-components-scrollToBottom-gap"])!=null?no:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(ro=(qn=n["--persona-components-scrollToBottom-fontSize"])!=null?qn:n["--persona-palette-typography-fontSize-sm"])!=null?ro:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(vt=n["--persona-components-scrollToBottom-iconSize"])!=null?vt:"14px",n["--persona-tool-bubble-shadow"]=(Ar=n["--persona-components-toolBubble-shadow"])!=null?Ar:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Sr=n["--persona-components-reasoningBubble-shadow"])!=null?Sr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Ur=n["--persona-components-composer-shadow"])!=null?Ur:"none",n["--persona-md-inline-code-bg"]=(cr=n["--persona-components-markdown-inlineCode-background"])!=null?cr:n["--persona-container"],n["--persona-md-inline-code-color"]=(ut=n["--persona-components-markdown-inlineCode-foreground"])!=null?ut:n["--persona-text"],n["--persona-md-link-color"]=(Tr=(Io=n["--persona-components-markdown-link-foreground"])!=null?Io:n["--persona-accent"])!=null?Tr:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Ro=n["--persona-components-markdown-codeBlock-background"])!=null?Ro:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Ln=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-code-block-text-color"]=(os=n["--persona-components-markdown-codeBlock-textColor"])!=null?os:"inherit",n["--persona-md-table-header-bg"]=(oo=n["--persona-components-markdown-table-headerBackground"])!=null?oo:n["--persona-container"],n["--persona-md-table-border-color"]=(qr=n["--persona-components-markdown-table-borderColor"])!=null?qr:n["--persona-border"],n["--persona-md-hr-color"]=(so=n["--persona-components-markdown-hr-color"])!=null?so:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(ao=n["--persona-components-markdown-blockquote-borderColor"])!=null?ao:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Wo=n["--persona-components-markdown-blockquote-background"])!=null?Wo:"transparent",n["--persona-md-blockquote-text-color"]=(Ho=n["--persona-components-markdown-blockquote-textColor"])!=null?Ho:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(io=n["--persona-components-collapsibleWidget-container"])!=null?io:n["--persona-surface"],n["--cw-surface"]=(yt=n["--persona-components-collapsibleWidget-surface"])!=null?yt:n["--persona-surface"],n["--cw-border"]=(Wn=n["--persona-components-collapsibleWidget-border"])!=null?Wn:n["--persona-border"],n["--persona-message-border"]=(Hn=n["--persona-components-message-border"])!=null?Hn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let Ce=v.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(Cn=n["--persona-dropdown-bg"])!=null?Cn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(wt=n["--persona-dropdown-border"])!=null?wt:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(zn=n["--persona-dropdown-shadow"])!=null?zn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Vn=n["--persona-dropdown-radius"])!=null?Vn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Bn=n["--persona-dropdown-item-hover-bg"])!=null?Bn:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(v!=null&&v.tab){let Ce=v.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(v!=null&&v.pane){let Ce=v.pane;if(Ce.toolbarBackground){let zr=(lo=Es(e,Ce.toolbarBackground))!=null?lo:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zr}}return n}var Wx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Hx={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"}}},zm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Za=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Bx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Za()},Vm=e=>Bx(e),Dx=e=>pa(e),Nx=e=>{var n;let t=pa(void 0,{validate:!1});return pa({...e,palette:{...t.palette,colors:{...Hx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ua=e=>{let t=Vm(e),n=zm(e==null?void 0:e.theme),r=zm(e==null?void 0:e.darkTheme);return t==="dark"?Nx(da(n!=null?n:{},r!=null?r:{})):Dx(n)},Ox=e=>fl(e),Zo=(e,t)=>{let n=ua(t),r=Ox(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},hl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Za())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Za());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Fx}from"idiomorph";var ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Fx.morph(e,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:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Km=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ti={index:-1,draft:""};function Gm(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ti}}}function Jm(e,t){var n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae,se,ie,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(E=(x=e.toolCall)==null?void 0:x.name)!=null?E:"",(k=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?k:0,(R=(C=(P=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(N=(O=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:O.length)!=null?N:0,(Z=(pe=(ke=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?Z:0,(Ae=(oe=(Le=(Te=e.reasoning)==null?void 0:Te.chunks)==null?void 0:Le[e.reasoning.chunks.length-1])==null?void 0:oe.slice(-32))!=null?Ae:"",(ie=(se=e.contentParts)==null?void 0:se.length)!=null?ie:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function Xm(){return new Map}function Qm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Ym(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Zm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ni(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function So(e,t){return Fr(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function oi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function eg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function tg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function ng(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},vn=1e5,To=vn+1;var ma={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},_x=["pre","code","a","script","style"],si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ma.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ma.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ma.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ma.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ma.buffer}},og=[{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"}],ga=new Map;for(let e of og)ga.set(e.name,e);var $x=e=>{ga.set(e.name,e)},jx=e=>{og.some(t=>t.name===e)||ga.delete(e)},Ux=()=>Array.from(ga.keys()),fa=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=ga.get(e))!=null?r:null},ai=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
19
+ `);return s<0?"":e.slice(0,s)}return e},qx=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},zx=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},yl=/\s/,Vx=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Kx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(yl.test(s[i])){let l=i;for(;l<s.length&&yl.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!yl.test(s[p]);)l.appendChild(qx(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Gx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(zx(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},ha=(e,t,n,r)=>{var u,g;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:_x).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Vx(d,s)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Kx:Gx;for(let f of i)p(f,n,l);return o.innerHTML},ii=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ya=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},rg=new WeakMap,Jx=(e,t)=>{var s;if(!e.styles)return;let n=rg.get(t);if(n||(n=new Set,rg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},bl=new WeakMap,Xx=(e,t)=>{if(!e.onAttach)return;let n=bl.get(t);if(n||(n=new Map,bl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},sg=e=>{let t=bl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},xl=(e,t)=>{Jx(e,t),Xx(e,t)};function vl(e,t=vn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var ba=0,Eo=null;function wl(e=document){var n;if(ba++,ba===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Eo={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,ba=Math.max(0,ba-1),ba===0&&Eo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Eo.originalOverflow,o.style.position=Eo.originalPosition,o.style.top=Eo.originalTop,o.style.width=Eo.originalWidth,s.scrollTo(0,Eo.scrollY),Eo=null}}}var xa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},dn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Mo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},rr=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:xa.side,width:(o=t==null?void 0:t.width)!=null?o:xa.width,animate:(s=t==null?void 0:t.animate)!=null?s:xa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:xa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:xa.maxHeight}};var br={"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 Qx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",li=(e,t={})=>{var E,T,L,k,M,P;let{showClose:n=!0,wrapperClassName:r=Qx,buttonSize:o,iconSize:s="28px"}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),l=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0,u=(M=a.closeButtonIconName)!=null?M:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=At("button",{className:Ys("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Mn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=ge(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),p&&l){let C=null,R=()=>{if(C)return;let j=v.ownerDocument,H=j.body;if(!H)return;C=Nr(j,"div","persona-clear-chat-tooltip"),C.textContent=l;let O=Nr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(To),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",H.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",R),d.addEventListener("mouseleave",F),v.addEventListener("focus",R),v.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",R),d.removeEventListener("mouseleave",F),v.removeEventListener("focus",R),v.removeEventListener("blur",F)}}return{button:v,wrapper:d}},Yx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ci=(e,t={})=>{var C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le;let{wrapperClassName:n=Yx,buttonSize:r,iconSize:o="20px"}=t,a=(R=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?R:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",l=(H=a.iconColor)!=null?H:"",p=(O=a.backgroundColor)!=null?O:"",u=(N=a.borderWidth)!=null?N:"",g=(Y=a.borderColor)!=null?Y:"",f=(ke=a.borderRadius)!=null?ke:"",v=(pe=a.paddingX)!=null?pe:"",x=(Z=a.paddingY)!=null?Z:"",E=(Te=a.tooltipText)!=null?Te:"Clear chat",T=(Le=a.showTooltip)!=null?Le:!0,L=y("div",n),k=!!(u||g),M=At("button",{className:Ys("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:l||Mn.actionIconColor,backgroundColor:p||void 0,border:k?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),P=ge(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),L.appendChild(M),T&&E){let oe=null,Ae=()=>{if(oe)return;let ie=M.ownerDocument,ae=ie.body;if(!ae)return;oe=Nr(ie,"div","persona-clear-chat-tooltip"),oe.textContent=E;let xe=Nr(ie,"div");xe.className="persona-clear-chat-tooltip-arrow",oe.appendChild(xe);let Be=M.getBoundingClientRect();oe.style.position="fixed",oe.style.zIndex=String(To),oe.style.left=`${Be.left+Be.width/2}px`,oe.style.top=`${Be.top-8}px`,oe.style.transform="translate(-50%, -100%)",ae.appendChild(oe)},se=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};L.addEventListener("mouseenter",Ae),L.addEventListener("mouseleave",se),M.addEventListener("focus",Ae),M.addEventListener("blur",se),L._cleanupTooltip=()=>{se(),L.removeEventListener("mouseenter",Ae),L.removeEventListener("mouseleave",se),M.removeEventListener("focus",Ae),M.removeEventListener("blur",se)}}return{button:M,wrapper:L}};var Mn={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))"},ko=e=>{var P,C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae;let{config:t,showClose:n=!0}=e,r=At("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=t==null?void 0:t.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(R=o.closeButtonPlacement)!=null?R:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,l=At("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 se=parseFloat(s)||24,ie=ge(d,se*.6,"currentColor",1);ie?l.replaceChildren(ie):l.textContent=(H=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?H:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let se=y("img");se.src=t.launcher.iconUrl,se.alt="",se.className="persona-rounded-xl persona-object-cover",se.style.height=s,se.style.width=s,l.replaceChildren(se)}else l.textContent=(Y=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?Y:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=At("span",{className:"persona-text-base persona-font-semibold",text:(pe=(ke=t==null?void 0:t.launcher)==null?void 0:ke.title)!=null?pe:"Chat Assistant",style:{color:Mn.titleColor}}),g=At("span",{className:"persona-text-xs",text:(Te=(Z=t==null?void 0:t.launcher)==null?void 0:Z.subtitle)!=null?Te:"Here to help you get answers fast",style:{color:Mn.subtitleColor}});p.append(u,g),i?r.append(p):r.append(l,p);let f=(Le=o.clearChat)!=null?Le:{},v=(oe=f.enabled)!=null?oe:!0,x=(Ae=f.placement)!=null?Ae:"inline",E=null,T=null;if(v){let ie=ci(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=ie.button,T=ie.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let L=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:k,wrapper:M}=li(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:k,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:T}},Ms=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function es(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,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(To)):(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 f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let E=ge(f.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),p(),n(f.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:g}}function Kt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=ge(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function di(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=ge(t,s!=null?s:14,"currentColor",2);g&&p.appendChild(g)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function pi(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Kt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Cl(e){var f,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=ge(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,E;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=es({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let E=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var ag=e=>{var r;let t=ko({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Zx(e,t,n){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=ge(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 l=es({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ig=e=>{var L,k,M,P,C,R,F,j,H;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},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,l,p;if(d)l=Cl({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(M=l.querySelector(".persona-combo-btn-label"))!=null?M:l;else{if(l=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(p),Zx(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let N=o.onTitleClick;l.addEventListener("click",Y=>{Y.target.closest("button")||N()}),l.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),N())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(R=O.borderRadius)!=null?R:"10px",l.style.padding=(F=O.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var N,Y;l.style.backgroundColor=(N=O.background)!=null?N:"",l.style.borderColor=(Y=O.border)!=null?Y:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(j=a.closeButtonSize)!=null?j:"32px",g=y("div",""),f=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");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Mn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=ge(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let E=y("div");E.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Al={default:ag,minimal:ig},lg=e=>{var t;return(t=Al[e])!=null?t:Al.default},va=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),g=y("span"),f=y("button");f.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=lg(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig: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 ui=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.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 n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*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}},mi=e=>{var P,C,R,F,j,H,O,N,Y,ke,pe,Z;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",o=t.iconName,s=(F=t.stopIconName)!=null?F:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(H=t.stopTooltipText)!=null?H:"Stop generating",d=(N=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?N:"Send",l=(ke=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?ke:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(Z=t.size)!=null?Z:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=At("button",{className:Ys("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&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}}),E=null,T=null;if(n){let Te=parseFloat(u)||24,Le=(f==null?void 0:f.trim())||"currentColor";o?(E=ge(o,Te,Le,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,T=ge(s,Te,Le,2)}else x.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:Te=>{if(Te===k)return;k=Te;let Le=Te==="stop"?i:a;if(x.setAttribute("aria-label",Le),L&&(L.textContent=Le),n){if(E&&T){let oe=Te==="stop"?T:E;x.replaceChildren(oe)}}else x.textContent=Te==="stop"?l:d}}},gi=e=>{var L,k,M,P,C,R,F,j,H,O,N,Y;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(C=t.iconName)!=null?C:"mic",d=(R=t.iconSize)!=null?R:a,l=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,u=(O=t.iconColor)!=null?O:(H=e==null?void 0:e.sendButton)==null?void 0:H.textColor,g=y("div","persona-send-button-wrapper"),f=At("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:u||"var(--persona-text, #111827)",backgroundColor:p||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=ge(i,l,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",g.appendChild(f);let E=(N=t.tooltipText)!=null?N:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&E){let ke=y("div","persona-send-button-tooltip");ke.textContent=E,g.appendChild(ke)}return{button:f,wrapper:g}},fi=e=>{var v,x,E,T,L,k,M,P;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(E=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?E:"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=((T=t.allowedTypes)!=null?T:Zr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=t.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),l=y("div","persona-send-button-wrapper"),p=At("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":(M=t.buttonTooltipText)!=null?M:"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"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ge(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),l.appendChild(p);let g=(P=t.buttonTooltipText)!=null?P:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,l.appendChild(f),{button:p,wrapper:l,input:o,previewsContainer:r}},hi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},yi=()=>At("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var wa=e=>{var v,x,E,T,L,k;let{config:t}=e,n=At("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=At("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(t);a();let i=mi(t),d=gi(t),l=fi(t),p=hi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=At("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(g,f),o.append(u),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,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:p,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var cg=()=>{let e=At("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"),n=ge("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=ge("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},dg=e=>{var v,x,E,T,L,k;let{config:t}=e,n=At("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=yi();r.style.display="none";let o=hi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ui(t);s.style.maxHeight="100px",a();let i=mi(t),d=gi(t),l=fi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=At("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,g),l&&n.append(l.previewsContainer),n.append(p,r,o);let f=p;return{footer:n,suggestions:r,composerForm:p,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:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var pg=e=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,H;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=dn(e);if(Mo(e)){let O=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(v=O.expandedSize)!=null?v:"anchored",N.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:vn);let Y=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",N.appendChild(Y);let ke=y("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",ke.style.zIndex=String((k=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?k:vn),{wrapper:N,panel:Y,pillRoot:ke}}if(n){let O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(N),{wrapper:O,panel:N}}if(!t){let O=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?P:"100%";return O.style.width=Y,N.style.width="100%",O.appendChild(N),{wrapper:O,panel:N}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&br[o.position]?br[o.position]:br["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?F:vn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:nr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},ev=(e,t)=>{var M,P,C,R,F,j,H,O,N;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=li(e,{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=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Y=ci(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Y.button,i=Y.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=At("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=At("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"}});l.style.setProperty("scrollbar-gutter","stable");let p=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),u=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),g=At("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((N=e==null?void 0:e.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(g,f);let E=At("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=dg({config:e}),{root:L,textNode:k}=cg();return n.append(d,o,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:f,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:k}},ug=(e,t=!0)=>{var E,T,L,k,M,P,C,R,F;if(Mo(e))return ev(e,t);let n=At("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=(E=e==null?void 0:e.layout)==null?void 0:E.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?va(e,r,{showClose:t}):ko({config:e,showClose:t}),a=At("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=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),l=At("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:dn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(l.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(l,p);let f=wa({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;o?Ms(n,s,e):(s.header.style.display="none",Ms(n,s,e)),n.append(a);let x=At("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||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle: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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Sl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
20
20
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
21
21
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
22
22
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -24,14 +24,14 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
24
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
25
25
  </span>
26
26
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
27
- `,n.addEventListener("click",t);let r=s=>{var k,M,P,C,R,F,j,W,O,N,Y,Ee,de;let a=(k=s.launcher)!=null?k:{},i=cn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let Z=(M=a.title)!=null?M:"Chat Assistant";d.textContent=Z,d.setAttribute("title",Z)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Z=(P=a.subtitle)!=null?P:"Here to help you get answers fast";l.textContent=Z,l.setAttribute("title",Z)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let Z=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=Z,u.style.width=Z,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let Ce=parseFloat(Z)||24,ke=me(a.agentIconName,Ce*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(u.appendChild(ke),u.style.display=""):(u.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let Z=(j=a.agentIconSize)!=null?j:"40px";g.style.height=Z,g.style.width=Z,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let Z=(W=a.callToActionIconSize)!=null?W:"32px";f.style.height=Z,f.style.width=Z,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Ce=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ce=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let ke=parseFloat(Z)||24,re=Math.max(ke-Ce,8),we=me(a.callToActionIconName,re,"currentColor",2);we?f.appendChild(we):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let v=a.position&&hr[a.position]?hr[a.position]:hr["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",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${x} ${v}`,i||(n.style.zIndex=String((Y=a.zIndex)!=null?Y:wn));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Ee=a.border)!=null?Ee:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(de=a.collapsedMaxWidth)!=null?de:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Ym=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Xm(e),s=Qm(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},l={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:l,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{l.footer.replaceWith(g),l.footer=g}}},bl=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>yl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=yl(e,n);return{instance:o,element:o.element}};var Dx=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Nx=(e,t)=>{if(!e)return null;let n=Dx(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Ox=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Fx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},xl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},vl=320,eg=320,_x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),jx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ux=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),qx=(e,t,n)=>{if(e.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(),n==null||n())};return e.forEach((i,d)=>{var u;let l=y("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${vl}px`,l.style.maxHeight=`${eg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),Fx(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},zx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!xl(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=`${vl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Vx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!xl(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=`${vl}px`,o.style.maxHeight=`${eg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Kx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!xl(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),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Cs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let 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",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},tg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Cs};if(t){let o=t(r);if(o!==null)return o}return Cs()},Gx=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.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",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Zm=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Jx=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},ng=(e,t,n)=>{var v,x,E,T,L,k,M;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(E=t.showDownvote)!=null?E:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let i=(L=t.visibility)!=null?L:"hover",d=(k=t.align)!=null?k:"right",l=(M=t.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(P,C,R)=>{let F=Gt({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",R),F};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},ga=(e,t,n,r,o,s)=>{var le,se,oe,be,He,V,X,We,K,pe,$e,ge,Ve,et,$t,Xe,fe;let a=n!=null?n:{},i=(le=a.layout)!=null?le:"bubble",d=a.avatar,l=a.timestamp,p=(se=d==null?void 0:d.show)!=null?se:!1,u=(oe=l==null?void 0:l.show)!=null?oe:!1,g=(be=d==null?void 0:d.position)!=null?be:"left",f=(He=l==null?void 0:l.position)!=null?He:"below",v=Jx(e.role,i),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.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 E=_x(e),T=(X=(V=e.content)==null?void 0:V.trim())!=null?X:"",k=E.length>0&&T===$a,M=ei((K=(We=s==null?void 0:s.widgetConfig)==null?void 0:We.features)==null?void 0:K.streamAnimation),P=(ge=($e=(pe=s==null?void 0:s.widgetConfig)==null?void 0:pe.features)==null?void 0:$e.streamAnimation)==null?void 0:ge.plugins,C=e.role==="assistant"&&M.type!=="none"?ia(M.type,P):null,R=e.role==="assistant"&&((Ve=C==null?void 0:C.isAnimating)==null?void 0:Ve.call(C,e))===!0,F=e.role==="assistant"&&C!==null&&(!!e.streaming||R);F&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&j.classList.add(C.containerClass),j.style.setProperty("--persona-stream-step",`${M.speed}ms`),j.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let W=F?ti((et=e.content)!=null?et:"",M.buffer,C,e,!!e.streaming):($t=e.content)!=null?$t:"",O=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),N=O;F&&(C==null?void 0:C.wrap)==="char"?N=la(O,"char",e.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=la(O,"word",e.id,{skipTags:C.skipTags}));let Y=null;if(k?(Y=document.createElement("div"),Y.innerHTML=N,Y.style.display="none",j.appendChild(Y)):j.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&T){let J=ni(),dt=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=dt[dt.length-1];if(qe!=null&&qe.parentNode)qe.parentNode.insertBefore(J,qe.nextSibling);else{let Ae=j.lastElementChild;Ae?Ae.appendChild(J):j.appendChild(J)}}if(u&&f==="inline"&&e.createdAt){let J=Zm(e,l,"span");J.classList.add("persona-timestamp-inline");let dt=j.lastElementChild;dt?dt.appendChild(J):j.appendChild(J)}if(E.length>0){let J=qx(E,!k&&!!T,()=>{k&&Y&&(Y.style.display="")});J?x.appendChild(J):k&&Y&&(Y.style.display="")}let Ee=$x(e);if(Ee.length>0){let J=zx(Ee);J&&x.appendChild(J)}let de=jx(e);if(de.length>0){let J=Vx(de);J&&x.appendChild(J)}let Z=Ux(e);if(Z.length>0){let J=Kx(Z);J&&x.appendChild(J)}if(x.appendChild(j),u&&f==="below"&&e.createdAt){let J=Zm(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ce=e.role==="assistant"?Nx(e.stopReason,(fe=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(W&&W.trim()),dt=M.placeholder==="skeleton",qe=dt&&M.buffer==="line"&&J;if(J)qe&&x.appendChild(ca());else if(dt)x.appendChild(ca());else{let Ae=tg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ae&&x.appendChild(Ae)}}if(Ce&&e.stopReason&&!e.streaming&&(T||(j.style.display="none"),x.appendChild(Ox(e.stopReason,Ce))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=ng(e,r,o);x.appendChild(J)}if(!p||e.role==="system")return x;let re=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),we=Gx(d,e.role);return g==="right"||g==="left"&&e.role==="user"?re.append(x,we):re.append(we,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),re},Xx=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ga(e,t,n,r,o,s)};var As=new Set,Qx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Yx=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
- `):""},rg=(e,t)=>{let n=As.has(e),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",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=me(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},wl=(e,t)=>{var de,Z,Ce,ke,re,we,le,se,oe,be,He;let n=e.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-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(Z=(de=t==null?void 0:t.features)==null?void 0:de.reasoningDisplay)!=null?Z:{},s=o.expandable!==!1,a=s&&As.has(e.id),i=n.status!=="complete",d=Yx(e,(Ce=o.previewMaxLines)!=null?Ce:3),l=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");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(ke=t==null?void 0:t.reasoning)!=null?ke:{},v=String((re=n.startedAt)!=null?re:Date.now()),x=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=Oa(n),V},E=(we=f.renderCollapsedSummary)==null?void 0:we.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Oa(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(u.textContent=E,p.appendChild(u)):E instanceof HTMLElement?p.appendChild(E):(u.textContent=g,p.appendChild(u));let T=y("span","persona-text-xs persona-text-persona-primary");T.textContent=sm(n),p.appendChild(T);let L=(le=o.loadingAnimation)!=null?le:"none",k=f.activeTextTemplate,M=f.completeTextTemplate,P=i?k:M,C=E instanceof HTMLElement,R=(V,X,We)=>{let K=We;for(let pe of X){let $e=y("span","persona-tool-char");$e.style.setProperty("--char-index",String(K)),$e.textContent=pe===" "?"\xA0":pe,V.appendChild($e),K++}return K},F=(V,X)=>{u.textContent="";let We=Fa(V,""),K=0;for(let pe of We){let $e=pe.styles.length>0?(()=>{let ge=y("span",pe.styles.map(Ve=>`persona-tool-text-${Ve}`).join(" "));return u.appendChild(ge),ge})():u;if(pe.isDuration&&i)$e.appendChild(x());else{let ge=pe.isDuration?Oa(n):pe.text;X?K=R($e,ge,K):$e.appendChild(document.createTextNode(ge))}}};if(!C&&P)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(se=f.loadingAnimationDuration)!=null?se:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),F(P,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),F(P,!0))}else F(P,!1);else if(!C&&i&&L!=="none"){u.style.display="";let V=(oe=f.loadingAnimationDuration)!=null?oe:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let X=u.textContent||g;u.textContent="",R(u,X,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=y("div","persona-flex persona-items-center");let X=me(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show";let We=y("div","persona-flex persona-items-center persona-ml-auto");We.append(j),l.append(p,We)}else l.append(p);let W=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(He=(be=t==null?void 0:t.reasoning)==null?void 0:be.renderCollapsedPreview)==null?void 0:He.call(be,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Qx(W,V)||(W.textContent=d),W.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,W),r;let O=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let N=n.chunks.join(""),Y=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Y),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let X=me(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(l,W,O),r};var Ss=new Set,Zx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ev=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
- `);let o=fo(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
- `):""},Cl=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},tv=(e,t)=>{var p,u,g,f,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=ev(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?am(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Ji(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ji(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},og=(e,t,n)=>{var p;let r=Ss.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},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"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=me(r?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Al=(e,t)=>{var N,Y,Ee,de,Z,Ce,ke,re,we;let n=e.toolCall,r=(N=t==null?void 0:t.toolCall)!=null?N:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Ee=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&Ss.has(e.id),{summary:d,previewText:l,isActive:p}=tv(e,t),u=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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let v=String((de=n.startedAt)!=null?de:Date.now()),x=()=>{let le=y("span","");return le.setAttribute("data-tool-elapsed",v),le.textContent=Js(n),le},E=(Ce=r.renderCollapsedSummary)==null?void 0:Ce.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Z=s.collapsedMode)!=null?Z:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Js(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=d,g.appendChild(f));let T=(ke=s.loadingAnimation)!=null?ke:"none",L=r.activeTextTemplate,k=r.completeTextTemplate,M=p?L:k,P=E instanceof HTMLElement,C=(le,se,oe)=>{let be=oe;for(let He of se){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(be)),V.textContent=He===" "?"\xA0":He,le.appendChild(V),be++}return be},R=(le,se)=>{var V;f.textContent="";let oe=((V=n.name)==null?void 0:V.trim())||"tool",be=Fa(le,oe),He=0;for(let X of be){let We=X.styles.length>0?(()=>{let K=y("span",X.styles.map(pe=>`persona-tool-text-${pe}`).join(" "));return f.appendChild(K),K})():f;if(X.isDuration&&p)We.appendChild(x());else{let K=X.isDuration?Js(n):X.text;se?He=C(We,K,He):We.appendChild(document.createTextNode(K))}}};if(!P)if(p&&T!=="none"){let le=(re=r.loadingAnimationDuration)!=null?re:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${le}ms`),M&&R(M,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${le}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)R(M,!0);else{let se=f.textContent||d;f.textContent="",C(f,se,0)}}else M&&R(M,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let le=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=me(i?"chevron-up":"chevron-down",16,le,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show";let oe=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");oe.append(F),u.append(g,oe)}else u.append(g);let j=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let le=(we=r.renderCollapsedPreview)==null?void 0:we.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Zx(j,le)||(j.textContent=l),j.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,j),o;let W=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),n.name){let le=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?le.style.color=r.contentTextColor:r.headerTextColor&&(le.style.color=r.headerTextColor),le.textContent=n.name,W.appendChild(le)}if(n.args!==void 0){let le=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Arguments";let oe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",Cl(oe,r),oe.textContent=fo(n.args),le.append(se,oe),W.appendChild(le)}if(n.chunks&&n.chunks.length){let le=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Activity";let oe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",Cl(oe,r),oe.textContent=n.chunks.join(""),le.append(se,oe),W.appendChild(le)}if(n.status==="complete"&&n.result!==void 0){let le=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Result";let oe=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",Cl(oe,r),oe.textContent=fo(n.result),le.append(se,oe),W.appendChild(le)}if(n.status==="complete"&&typeof n.duration=="number"){let le=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(le.style.color=r.contentTextColor),le.textContent=`Duration: ${n.duration}ms`,W.appendChild(le)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let le=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=me(i?"chevron-up":"chevron-down",16,le,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(u,j,W),o};var Ko=new Map,mi=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},sg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,ag=(e,t)=>{var r,o,s;let n=(o=(r=sg(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ko.get(e))!=null?s:n==="expanded"},ig=(e,t,n)=>{var a,i;let r=sg(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.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=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=me(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},lg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=ag(e,n);ig(r,s,n),o.style.display=s?"":"none"};var gi=(e,t)=>{var R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke,re,we,le;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(R=r==null?void 0:r.backgroundColor)!=null?R:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(F=r==null?void 0:r.borderColor)!=null?F:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(j=r==null?void 0:r.titleColor)!=null?j:"currentColor",p=me(d,20,l,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(W=r==null?void 0:r.title)!=null?W:"Approval Required",g.appendChild(f),!o){let se=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",n.status),n.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):n.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):n.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),g.appendChild(se)}u.appendChild(g);let x=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Us(n.toolName):void 0,E=(O=r==null?void 0:r.formatDescription)==null?void 0:O.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=E||(T?n.description:`The assistant wants to use \u201C${x!=null?x:mi(n.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=L,u.appendChild(k),n.reason){let se=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?se.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let oe=y("span","persona-font-medium");oe.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,se.appendChild(oe),se.appendChild(document.createTextNode(n.reason)),u.appendChild(se)}let M=(Y=r==null?void 0:r.detailsDisplay)!=null?Y:"collapsed",P=!!n.description&&!T,C=P||!!n.parameters;if(M!=="hidden"&&C){let se=ag(e.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 be=y("span");be.setAttribute("data-approval-details-label","true");let He=y("span","persona-inline-flex persona-items-center");He.setAttribute("data-approval-details-chevron","true"),oe.append(be,He),ig(oe,se,t),u.appendChild(oe);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"none",P){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor),X.textContent=n.description,V.appendChild(X)}if(n.parameters){let X=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&&(X.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(X.style.color=r.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=fo(n.parameters),V.appendChild(X)}u.appendChild(V)}if(o){let se=y("div","persona-flex persona-gap-2 persona-mt-2");se.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=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",oe.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",oe.setAttribute("data-approval-action","approve");let be=me("shield-check",14,(Z=r==null?void 0:r.approveButtonTextColor)!=null?Z:"#ffffff",2);be&&(be.style.marginRight="4px",oe.appendChild(be));let He=document.createTextNode((Ce=r==null?void 0:r.approveLabel)!=null?Ce:"Approve");oe.appendChild(He);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=(ke=r==null?void 0:r.denyButtonColor)!=null?ke:"transparent",V.style.color=(re=r==null?void 0:r.denyButtonTextColor)!=null?re:"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 X=me("shield-x",14,(we=r==null?void 0:r.denyButtonTextColor)!=null?we:"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",V.appendChild(X));let We=document.createTextNode((le=r==null?void 0:r.denyLabel)!=null?le:"Deny");V.appendChild(We),se.append(oe,V),u.appendChild(se)}return a.append(i,u),s.appendChild(a),s};function nv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function cg(e){var x;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,l=(x=e.container)!=null?x:nv(t),p=!1,u=null,g=()=>{if(!p)return;let E=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`);let T=r==="top-start"||r==="top-end"?E.top-o-n.getBoundingClientRect().height:E.bottom+o,L=r==="bottom-end"||r==="top-end"?E.right-n.getBoundingClientRect().width:E.left;n.style.top=`${T}px`,n.style.left=`${L}px`},f=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},v=()=>{var P,C,R;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),l.appendChild(n),g();let E=(C=((P=t.ownerDocument)!=null?P:document).defaultView)!=null?C:window,T=(R=t.ownerDocument)!=null?R:document,L=()=>{if(!t.isConnected){f(),d==null||d("anchor-removed");return}g()},k=F=>{let j=typeof F.composedPath=="function"?F.composedPath():[];j.includes(n)||j.includes(t)||(f(),d==null||d("outside"))},M=E.setTimeout(()=>{T.addEventListener("pointerdown",k,!0)},0);E.addEventListener("scroll",L,!0),E.addEventListener("resize",L),u=()=>{E.clearTimeout(M),T.removeEventListener("pointerdown",k,!0),E.removeEventListener("scroll",L,!0),E.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:v,close:f,toggle:()=>p?f():v(),reposition:g,destroy:f}}function dg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var rv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),pg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},Go=(e,t)=>{pg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},ov=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,sv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=Ko.get(e))!=null?o:n==="expanded"},Sl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},av=(e,t)=>{var l,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Rr)?Us(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:mi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},iv=e=>{let t=y("div","persona-approval-resolved"),n=me("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?mi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},lv=(e,t,n,r,o,s,a)=>{var F,j,W,O,N,Y,Ee;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(F=r==null?void 0:r.detailsDisplay)!=null?F:"collapsed",l=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=l||p,g=u&&sv(t.id,r),f=(j=r==null?void 0:r.showDetailsLabel)!=null?j:"Show details",v=(W=r==null?void 0:r.hideDetailsLabel)!=null?W:"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",g?"true":"false"),x.setAttribute("aria-label",g?v:f)):x.setAttribute("data-static","true");let E=y("span","persona-approval-logo"),T=me("shield-check",16,"currentColor",2);T&&E.appendChild(T),x.appendChild(E);let L=av(n,r);if(u){let de=y("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let Z=me("chevron-down",14,"currentColor",2);Z&&de.appendChild(Z),L.append(" "),L.appendChild(de)}x.appendChild(L),i.appendChild(x);let k=y("div","persona-approval-body");if(u){let de=y("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!g,l){let Z=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(Z.style.color=r.descriptionColor),Z.textContent=n.description,de.appendChild(Z)}if(p){let Z=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(Z.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Z.style.color=r.parameterTextColor),Z.textContent=fo(n.parameters),de.appendChild(Z)}k.appendChild(de)}if(n.reason){let de=y("p","persona-approval-reason");r!=null&&r.reasonColor?de.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let Z=y("span","persona-approval-reason-label");Z.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,de.append(Z,document.createTextNode(n.reason)),k.appendChild(de)}let M=y("div","persona-approval-actions"),P=null,C=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.style.color=r.approveButtonTextColor)},R=y("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(R.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(R.style.color=r.denyButtonTextColor),R.append((N=r==null?void 0:r.denyLabel)!=null?N:"Deny"),a){let de=y("div","persona-approval-split"),Z=y("button","persona-approval-primary");Z.type="button",Z.setAttribute("data-action","always"),C(Z),Z.append((Y=r==null?void 0:r.approveLabel)!=null?Y:"Always allow",Sl("\u23CE"));let Ce=y("button","persona-approval-caret");Ce.type="button",Ce.setAttribute("data-action","toggle-menu"),Ce.setAttribute("aria-label","More options"),C(Ce);let ke=me("chevron-down",15,"currentColor",2);ke&&Ce.appendChild(ke),de.append(Z,Ce),M.append(de,R),R.append(Sl("Esc"));let re=y("div","persona-approval-menu"),we=y("button","persona-approval-menu-item");we.type="button",we.append("Allow once",Sl("\u2318\u23CE")),re.appendChild(we),P=cg({anchor:de,content:re,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,P),we.addEventListener("click",()=>{Go(e,t.id),o()})}else{let de=y("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),C(de),de.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),M.append(de,R)}return k.appendChild(M),i.appendChild(k),i.addEventListener("click",de=>{let Z=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!Z)return;let Ce=Z.getAttribute("data-action");if(Ce==="toggle-params"){let ke=i.querySelector('[data-role="params"]');if(ke){let re=ke.hidden;ke.hidden=!re,x.setAttribute("aria-expanded",re?"true":"false"),x.setAttribute("aria-label",re?v:f),Ko.set(t.id,re)}return}if(Ce==="toggle-menu"){P==null||P.toggle();return}if(Ce==="always"){Go(e,t.id),o({remember:!0});return}if(Ce==="allow"){Go(e,t.id),o();return}if(Ce==="deny"){Go(e,t.id),s();return}}),i},ug=()=>{let e=rv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=ov(a);if(i.status!=="pending"){if(Go(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return iv(i)}pg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=lv(e,r,i,d,o,s,l);if(l){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{dg(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Go(e,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])Go(e,r);e.latestPendingApprovalId=null}}};var mg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=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=g,d!=null&&d.fontFamily&&(x.style.fontFamily=f(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="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(x),t.push(x)}),e.appendChild(u),p){let v=JSON.stringify(o);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var fa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;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),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){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 ha=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let 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=()=>{n(r.error)}}catch(r){n(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,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{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=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{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=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(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 cv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),dv=new Set(["step_start","execution_start"]),pv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),uv=new Set(["step_complete","agent_turn_complete"]),mv=new Set(["flow_complete","agent_complete"]),gg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),hg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Kn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Jo=(e,t)=>{let n=e[t];return hg(n)?n:void 0};function Tl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function gv(e,t){return typeof t.type=="string"?t.type:e}function fv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function hv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function fg(e){var r,o,s,a,i;let t=Jo(e,"result"),n=[Jo(e,"tokens"),Jo(e,"totalTokens"),t?Jo(t,"tokens"):void 0,Jo(e,"usage"),t?Jo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Kn(d.output))!=null?r:Kn(d.outputTokens))!=null?o:Kn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Kn(e.outputTokens))!=null?s:Kn(e.completionTokens))!=null?i:t?(a=Kn(t.outputTokens))!=null?a:Kn(t.completionTokens):void 0}function yv(e){var n,r,o,s,a;let t=Jo(e,"result");return(a=(o=(r=(n=Kn(e.executionTime))!=null?n:Kn(e.executionTimeMs))!=null?r:Kn(e.execution_time))!=null?o:Kn(e.duration))!=null?a:t?(s=Kn(t.executionTime))!=null?s:Kn(t.executionTimeMs):void 0}function bv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ya=class{constructor(t=bv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:fi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!hg(n)){gg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=gv(t,n),o=this.now();if(cv.has(r)){this.startRun(o);return}if(dv.has(r)){this.run||this.startRun(o);return}if(pv.has(r)){if(!hv(r,n))return;let a=fv(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Tl(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:fi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(uv.has(r)){if(!this.run)return;let a=this.run,i=fg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Tl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:fi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(mv.has(r)){if(!this.run)return;let a=this.run,i=fg(n),d=i!=null?i:a.exactOutputTokens+Tl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:fi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(gg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=yv(n);return s!=null?s:r-t.startedAt}};function Ts(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var xv={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)"}},vv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},wv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Cv=100;function Av(e,t){let n={...xv,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return vv}function Sv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Tv(e){let t=new Date(e),n=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`${n}:${r}:${o}.${s}`}function Ev(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Mv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function kv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Lv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Pv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Iv(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function El(e,t,n,r,o,s,a,i){var g;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ts(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var N,Y;let f=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",e.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"),E=me(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(N=r.timestampFormat)!=null?N:"relative";T.textContent=L==="relative"?Sv(e.timestamp,n):Tv(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let M=Av(e.type,r.badgeColors),P=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=M.bg,P.style.color=M.text,P.style.borderColor=M.text+"50",P.textContent=e.type;let C=(Y=r.descriptionFields)!=null?Y:wv,R=Ev(e.payload,C),F=null;R&&(F=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=R);let j=y("div","persona-flex-1 persona-min-w-0"),W=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"),O=me("clipboard","12px","currentColor",1.5);return O&&W.appendChild(O),W.addEventListener("click",async Ee=>{Ee.stopPropagation(),await Mv(kv(e)),W.innerHTML="";let de=me("check","12px","currentColor",1.5);de&&W.appendChild(de),setTimeout(()=>{W.innerHTML="";let Z=me("clipboard","12px","currentColor",1.5);Z&&W.appendChild(Z)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(P),F&&v.appendChild(F),v.appendChild(j),v.appendChild(W),f.appendChild(v),d&&f.appendChild(Iv(e,a,i)),f}}function yg(e){var v,x,E,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},g=s.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let k=g.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=u.classNames,M=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ts(M,k==null?void 0:k.panel);let P=[],C="",R="",F=null,j=[],W={},O=0,N=Qa(),Y=0,Ee=0,de=!1,Z=null,Ce=!1,ke=0,re=new Set,we=new Map,le="",se="",oe=null,be,He,V,X,We=null,K=null,pe=null;function $e(){let ce=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),H=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");if(Ts(H,k==null?void 0:k.headerBar),a){K=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),K.style.cursor="help",We=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"),We.textContent="-- tok/s",pe=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"),pe.style.display="none",pe.style.pointerEvents="none";let Ft=K,Hn=pe,jt=()=>{if(!Hn.textContent)return;let Gn=Ft.getBoundingClientRect(),yn=ce.getBoundingClientRect();Hn.style.left=`${Gn.left-yn.left}px`,Hn.style.top=`${Gn.bottom-yn.top+4}px`,Hn.style.display="block"},Bn=()=>{Hn.style.display="none"};K.addEventListener("mouseenter",jt),K.addEventListener("mouseleave",Bn),K.appendChild(We)}let he=y("div","persona-flex-1");be=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 Fe=y("option","");Fe.value="",Fe.textContent="All events (0)",be.appendChild(Fe),He=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"),He.type="button",He.title="Copy All";let Ye=me("clipboard-copy","12px","currentColor",1.5);Ye&&He.appendChild(Ye);let Ht=y("span","persona-event-copy-all persona-text-xs");Ht.textContent="Copy All",He.appendChild(Ht),K&&H.appendChild(K),H.appendChild(he),H.appendChild(be),H.appendChild(He);let Tt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ts(Tt,k==null?void 0:k.searchBar);let ht=me("search","14px","var(--persona-muted, #9ca3af)",1.5),Lt=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");ht&&Lt.appendChild(ht),V=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"),Ts(V,k==null?void 0:k.searchInput),V.type="text",V.placeholder="Search event payloads...",X=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"),X.type="button",X.style.display="none";let Qt=me("x","12px","currentColor",2);return Qt&&X.appendChild(Qt),Tt.appendChild(Lt),Tt.appendChild(V),Tt.appendChild(X),ce.appendChild(H),ce.appendChild(Tt),pe&&ce.appendChild(pe),ce}let ge,Ve=s.find(ce=>ce.renderEventStreamToolbar);if(Ve!=null&&Ve.renderEventStreamToolbar&&o){let ce=Ve.renderEventStreamToolbar({config:o,defaultRenderer:()=>$e(),eventCount:t.getSize(),filteredCount:0,onFilterChange:H=>{C=H,ee(),xt()},onSearchChange:H=>{R=H,ee(),xt()}});ge=ce!=null?ce:$e()}else ge=$e();let et=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");et.style.display="none";function $t(){if(!a||!We||!K)return;let ce=a(),H=Lv(ce);We.textContent=H;let he=Pv(ce);pe&&(pe.textContent=he,he||(pe.style.display="none")),K.setAttribute("aria-label",he?`Throughput: ${H}, ${he}`:`Throughput: ${H}`)}let Xe=y("div","persona-flex-1 persona-min-h-0 persona-relative"),fe=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");fe.style.height="100%";let J=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");Ts(J,k==null?void 0:k.scrollIndicator),J.style.display="none",J.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let dt=me(l,"14px","currentColor",2);dt&&J.appendChild(dt);let qe=y("span","");qe.textContent=p,J.appendChild(qe);let Ae=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ae.style.display="none",Xe.appendChild(fe),Xe.appendChild(Ae),Xe.appendChild(J),M.setAttribute("tabindex","0"),M.appendChild(ge),M.appendChild(et),M.appendChild(Xe);function Me(){let ce=t.getAll(),H={};for(let Tt of ce)H[Tt.type]=(H[Tt.type]||0)+1;let he=Object.keys(H).sort(),Fe=he.length!==j.length||!he.every((Tt,ht)=>Tt===j[ht]),vt=!Fe&&he.some(Tt=>H[Tt]!==W[Tt]),Ye=ce.length!==Object.values(W).reduce((Tt,ht)=>Tt+ht,0);if(!Fe&&!vt&&!Ye||(j=he,W=H,!be))return;let Ht=be.value;if(be.options[0].textContent=`All events (${ce.length})`,Fe){for(;be.options.length>1;)be.remove(1);for(let Tt of he){let ht=y("option","");ht.value=Tt,ht.textContent=`${Tt} (${H[Tt]||0})`,be.appendChild(ht)}Ht&&he.includes(Ht)?be.value=Ht:Ht&&(be.value="",C="")}else for(let Tt=1;Tt<be.options.length;Tt++){let ht=be.options[Tt];ht.textContent=`${ht.value} (${H[ht.value]||0})`}}function nt(){let ce=t.getAll();if(C&&(ce=ce.filter(H=>H.type===C)),R){let H=R.toLowerCase();ce=ce.filter(he=>he.type.toLowerCase().includes(H)||he.payload.toLowerCase().includes(H))}return ce}function Pt(){return C!==""||R!==""}function ee(){O=0,Y=0,N.resume(),J.style.display="none"}function je(ce){re.has(ce)?re.delete(ce):re.add(ce),oe=ce;let H=fe.scrollTop,he=N.isFollowing();Ce=!0,N.pause(),xt(),fe.scrollTop=H,he&&N.resume(),Ce=!1}function Cn(){return zo(fe,50)}function xt(){Ee=Date.now(),de=!1,$t(),Me();let ce=t.getEvictedCount();ce>0?(et.textContent=`${ce.toLocaleString()} older events truncated`,et.style.display=""):et.style.display="none",P=nt();let H=P.length,he=t.getSize()>0;H===0&&he&&Pt()?(Ae.textContent=R?`No events matching '${R}'`:"No events matching filter",Ae.style.display="",fe.style.display="none"):(Ae.style.display="none",fe.style.display=""),He&&(He.title=Pt()?`Copy Filtered (${H})`:"Copy All"),d&&!N.isFollowing()&&H>O&&(Y+=H-O,qe.textContent=p?`${p}${Y>0?` (${Y})`:""}`:"",J.style.display=""),O=H;let Fe=t.getAll(),vt=Fe.length>0?Fe[0].timestamp:0,Ye=new Set(P.map(ht=>ht.id));for(let ht of re)Ye.has(ht)||re.delete(ht);let Ht=C!==le||R!==se,Tt=we.size===0&&P.length>0;if(Ht||Tt||P.length===0){fe.innerHTML="",we.clear();let ht=document.createDocumentFragment();for(let Lt=0;Lt<P.length;Lt++){let Qt=El(P[Lt],Lt,vt,u,re,je,s,o);we.set(P[Lt].id,Qt),ht.appendChild(Qt)}fe.appendChild(ht),le=C,se=R,oe=null}else{if(oe!==null){let Lt=we.get(oe);if(Lt&&Lt.parentNode===fe){let Qt=P.findIndex(Ft=>Ft.id===oe);if(Qt>=0){let Ft=El(P[Qt],Qt,vt,u,re,je,s,o);fe.insertBefore(Ft,Lt),Lt.remove(),we.set(oe,Ft)}}oe=null}let ht=new Set(P.map(Lt=>Lt.id));for(let[Lt,Qt]of we)ht.has(Lt)||(Qt.remove(),we.delete(Lt));for(let Lt=0;Lt<P.length;Lt++){let Qt=P[Lt];if(!we.has(Qt.id)){let Ft=El(Qt,Lt,vt,u,re,je,s,o);we.set(Qt.id,Ft),fe.appendChild(Ft)}}}N.isFollowing()&&(fe.scrollTop=fe.scrollHeight)}function hn(){if(Date.now()-Ee>=Cv){Z!==null&&(cancelAnimationFrame(Z),Z=null),xt();return}de||(de=!0,Z=requestAnimationFrame(()=>{Z=null,xt()}))}let yr=(ce,H)=>{if(!He)return;He.innerHTML="";let he=me(ce,"12px","currentColor",1.5);he&&He.appendChild(he);let Fe=y("span","persona-text-xs");Fe.textContent="Copy All",He.appendChild(Fe),setTimeout(()=>{He.innerHTML="";let vt=me("clipboard-copy","12px","currentColor",1.5);vt&&He.appendChild(vt);let Ye=y("span","persona-text-xs");Ye.textContent="Copy All",He.appendChild(Ye),He.disabled=!1},H)},br=async()=>{if(He){He.disabled=!0;try{let ce;Pt()?ce=P:n?(ce=await n(),ce.length===0&&(ce=t.getAll())):ce=t.getAll();let H=ce.map(he=>{try{return JSON.parse(he.payload)}catch{return he.payload}});await navigator.clipboard.writeText(JSON.stringify(H,null,2)),yr("check",1500)}catch{yr("x",1500)}}},A=()=>{be&&(C=be.value,ee(),xt())},te=()=>{!V||!X||(X.style.display=V.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{R=V.value,ee(),xt()},150))},Te=()=>{!V||!X||(V.value="",R="",X.style.display="none",F&&clearTimeout(F),ee(),xt())},De=()=>{if(Ce)return;let ce=fe.scrollTop,{action:H,nextLastScrollTop:he}=Ya({following:N.isFollowing(),currentScrollTop:ce,lastScrollTop:ke,nearBottom:Cn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ke=he,H==="resume"?(N.resume(),Y=0,J.style.display="none"):H==="pause"&&(N.pause(),d&&(qe.textContent=p,J.style.display=""))},Pe=ce=>{let H=Za({following:N.isFollowing(),deltaY:ce.deltaY,nearBottom:Cn(),resumeWhenNearBottom:!0});H==="pause"?(N.pause(),d&&(qe.textContent=p,J.style.display="")):H==="resume"&&(N.resume(),Y=0,J.style.display="none")},Ne=()=>{d&&(fe.scrollTop=fe.scrollHeight,N.resume(),Y=0,J.style.display="none")},Ge=ce=>{let H=ce.target;if(!H||H.closest("button"))return;let he=H.closest("[data-event-id]");if(!he)return;let Fe=he.getAttribute("data-event-id");Fe&&je(Fe)},it=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),V==null||V.focus(),V==null||V.select();return}ce.key==="Escape"&&(V&&document.activeElement===V?(Te(),V.blur(),M.focus()):r&&r())};He&&He.addEventListener("click",br),be&&be.addEventListener("change",A),V&&V.addEventListener("input",te),X&&X.addEventListener("click",Te),fe.addEventListener("scroll",De),fe.addEventListener("wheel",Pe,{passive:!0}),fe.addEventListener("click",Ge),J.addEventListener("click",Ne),M.addEventListener("keydown",it);function It(){F&&clearTimeout(F),Z!==null&&(cancelAnimationFrame(Z),Z=null),de=!1,we.clear(),He&&He.removeEventListener("click",br),be&&be.removeEventListener("change",A),V&&V.removeEventListener("input",te),X&&X.removeEventListener("click",Te),fe.removeEventListener("scroll",De),fe.removeEventListener("wheel",Pe),fe.removeEventListener("click",Ge),J.removeEventListener("click",Ne),M.removeEventListener("keydown",it)}return{element:M,update:hn,destroy:It}}}function bg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(f)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var xg=(e,t)=>{var r,o,s;let n=(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(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>bg(e,t)});if(p)return p}return bg(e,t)};var Ml=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}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(([n,r])=>{this.register(n,r)})}},vo=new Ml;vo.register("PersonaArtifactCard",xg);function Rv(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.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=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function vg(e,t){var He,V,X,We;let n=(V=(He=e.features)==null?void 0:He.artifacts)==null?void 0:V.layout,o=((X=n==null?void 0:n.toolbarPreset)!=null?X:"default")==="document",s=(We=n==null?void 0:n.panePadding)==null?void 0:We.trim(),a=e.markdown?us(e.markdown):null,i=$s(e.sanitize),d=K=>{let pe=a?a(K):Vr(K);return i?i(pe):pe},l=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,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let u=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");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let g=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.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 K;p(),(K=t.onDismiss)==null||K.call(t)});let x="rendered",E=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),L=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,R=!!(P&&C&&C.length>0),F=null,j,W=null,O=null;if(o&&(M||P)&&!R){if(j=M?si({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let K=me("chevron-down",14,"currentColor",2);K&&j.appendChild(K)}}else o&&R?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=M?si({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=Gt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append(j,W)):o?j=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Gt({icon:"copy",label:"Copy"});let N=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Y=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Ee=()=>{var Ve,et,$t;let K=(Ve=we.find(Xe=>Xe.id===le))!=null?Ve:we[we.length-1],pe=(et=K==null?void 0:K.id)!=null?et:null,$e=(K==null?void 0:K.artifactType)==="markdown"&&($t=K.markdown)!=null?$t:"",ge=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:$e,jsonPayload:ge,id:pe}},de=async()=>{var Ve;let{markdown:K,jsonPayload:pe}=Ee(),$e=(Ve=we.find(et=>et.id===le))!=null?Ve:we[we.length-1],ge=($e==null?void 0:$e.artifactType)==="markdown"?K:$e?pe:"";try{await navigator.clipboard.writeText(ge)}catch{}};if(j.addEventListener("click",async()=>{let K=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(K&&R){let{markdown:pe,jsonPayload:$e,id:ge}=Ee();try{await K({actionId:"primary",artifactId:ge,markdown:pe,jsonPayload:$e})}catch{}return}await de()}),W&&(C!=null&&C.length)){let K=()=>{var $e;return($e=u.closest("[data-persona-root]"))!=null?$e:document.body},pe=()=>{O=Vo({items:C.map($e=>({id:$e.id,label:$e.label})),onSelect:async $e=>{let{markdown:ge,jsonPayload:Ve,id:et}=Ee(),$t=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{$t?await $t({actionId:$e,artifactId:et,markdown:ge,jsonPayload:Ve}):$e==="markdown"||$e==="md"?await navigator.clipboard.writeText(ge):$e==="json"||$e==="source"?await navigator.clipboard.writeText(Ve):await navigator.clipboard.writeText(ge||Ve)}catch{}},anchor:F!=null?F:W,position:"bottom-right",portal:K()})};u.isConnected?pe():requestAnimationFrame(pe),W.addEventListener("click",$e=>{$e.stopPropagation(),O==null||O.toggle()})}N.addEventListener("click",async()=>{var K;try{await((K=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:K.call(n))}catch{}oe()}),Y.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let Z=()=>{o&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Z(),oe()}),L.addEventListener("click",()=>{x="source",Z(),oe()});let Ce=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),E.append(T,L),F?k.append(F,N,Y):k.append(j,N,Y),g.append(E,Ce,k),Z()):(g.appendChild(f),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let ke=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"),re=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ke.style.paddingLeft=s,ke.style.paddingRight=s,re.style.padding=s),u.appendChild(g),u.appendChild(ke),u.appendChild(re);let we=[],le=null,se=!1,oe=()=>{var ge,Ve,et,$t;let K=o&&we.length<=1;ke.classList.toggle("persona-hidden",K),ke.replaceChildren();for(let Xe of we){let fe=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");fe.type="button",fe.textContent=Xe.title||Xe.id.slice(0,8),Xe.id===le&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(Xe.id)),ke.appendChild(fe)}re.replaceChildren();let pe=le&&we.find(Xe=>Xe.id===le)||we[we.length-1];if(!pe)return;if(o){let Xe=pe.artifactType==="markdown"?"MD":(ge=pe.component)!=null?ge:"Component",J=(pe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ce.textContent=`${J} \xB7 ${Xe}`}else f.textContent="Artifacts";if(pe.artifactType==="markdown"){if(o&&x==="source"){let fe=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(Ve=pe.markdown)!=null?Ve:"",re.appendChild(fe);return}let Xe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((et=pe.markdown)!=null?et:""),re.appendChild(Xe);return}let $e=pe.component?vo.get(pe.component):void 0;if($e){let fe={message:{id:pe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=$e(($t=pe.props)!=null?$t:{},fe);if(J){re.appendChild(J);return}}catch{}}re.appendChild(Rv(pe))},be=()=>{var pe;let K=we.length>0;if(u.classList.toggle("persona-hidden",!K),l){let $e=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ve=((pe=$e==null?void 0:$e.classList.contains("persona-artifact-narrow-host"))!=null?pe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&Ve&&se?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(K){var pe,$e,ge;we=K.artifacts,le=(ge=($e=K.selectedId)!=null?$e:(pe=K.artifacts[K.artifacts.length-1])==null?void 0:pe.id)!=null?ge:null,we.length>0&&(se=!0),oe(),be()},setMobileOpen(K){se=K,!K&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):be()}}}function ir(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function wg(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ir(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Wv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function hi(e,t){var d,l,p,u,g,f,v,x,E,T;if(!ir(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Wv(e),wg(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),wg(e,t)}var Cg=["panel","seamless"];function yi(e,t){var i,d,l,p,u,g;for(let f of Cg)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ir(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",o=Cg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Ag(e,t){var n,r,o;return!t||!ir(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Hv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Bv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Dv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Nv(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Sg(e,t){var a;let r=(a=(t.getComputedStyle(e).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 Tg(e,t,n,r,o,s){let a=Hv(o,200),i=Nv(t,n,r,200);i=Math.max(a,i);let d=Bv(s);return d!==null&&(i=Math.min(i,d)),Dv(e,a,i)}var Eg={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"}},kl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Eg[a])!=null?x:Eg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=y("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,R;let L=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,L.appendChild(k);let M=(C=T.type)!=null?C:"text",P;M==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=M),P.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",P.id=`${t.id}-${a}-${T.name}`,P.name=T.name,P.placeholder=(R=T.placeholder)!=null?R:"",T.required&&(P.required=!0),L.appendChild(P),p.appendChild(L)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=(E=i.submitLabel)!=null?E:"Submit",u.appendChild(g),u.appendChild(f),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var P,C;T.preventDefault();let L=(P=n.formEndpoint)!=null?P:"/form",k=new FormData(p),M={};k.forEach((R,F)=>{M[F]=R}),M.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let R=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let F=await R.json();g.textContent=(C=F.message)!=null?C:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(R){g.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ll=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.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 n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},bi=new Ll;var Mg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ov=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Fv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},xi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Ov(e),n=Fv(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Pl=e=>typeof e=="string"?e:e==null?"":String(e),Es={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Pl(n.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:Pl(n.text)}}},kg=e=>Array.isArray(e)?e.map(t=>String(t)):[],vi=e=>{let t=new Set(kg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(kg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.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?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({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};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var _v=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},$v=e=>e.map(t=>({...t,streaming:!1})),jv=e=>e.map(t=>({...t,status:"complete"})),Il=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?_v(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?$v(n.messages):void 0,artifacts:n.artifacts?jv(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as Uv,STR as qv,OBJ as zv}from"partial-json";function Vv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Kv(e,t){if(!Vv(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Rl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=Uv(n,qv|zv),s=Kv(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Gv(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Wl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=vo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Jv(){let e=Rl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Lg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Hl(e){let t=Lg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Bl(e){let t=Lg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Xv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Dl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Xv}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,f.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,f.appendChild(x),g.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let C=1;C<=5;C++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${l[C-1]}`),R.title=l[C-1],R.dataset.rating=String(C),R.innerHTML=`
27
+ `,n.addEventListener("click",t);let r=s=>{var k,M,P,C,R,F,j,H,O,N,Y,ke,pe;let a=(k=s.launcher)!=null?k:{},i=dn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let Z=(M=a.title)!=null?M:"Chat Assistant";d.textContent=Z,d.setAttribute("title",Z)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Z=(P=a.subtitle)!=null?P:"Here to help you get answers fast";l.textContent=Z,l.setAttribute("title",Z)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let Z=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=Z,u.style.width=Z,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let Te=parseFloat(Z)||24,Le=ge(a.agentIconName,Te*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(u.appendChild(Le),u.style.display=""):(u.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let Z=(j=a.agentIconSize)!=null?j:"40px";g.style.height=Z,g.style.width=Z,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let Z=(H=a.callToActionIconSize)!=null?H:"32px";f.style.height=Z,f.style.width=Z,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let Te=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Te=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Le=parseFloat(Z)||24,oe=Math.max(Le-Te,8),Ae=ge(a.callToActionIconName,oe,"currentColor",2);Ae?f.appendChild(Ae):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let v=a.position&&br[a.position]?br[a.position]:br["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",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${x} ${v}`,i||(n.style.zIndex=String((Y=a.zIndex)!=null?Y:vn));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ke=a.border)!=null?ke:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var mg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=pg(e),s=ug(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},l={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:l,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{l.footer.replaceWith(g),l.footer=g}}},Tl=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>Sl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=Sl(e,n);return{instance:o,element:o.element}};var tv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},nv=(e,t)=>{if(!e)return null;let n=tv(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},rv=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},ov=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},El=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ml=320,fg=320,sv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),av=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),iv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),lv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),cv=(e,t,n)=>{if(e.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(),n==null||n())};return e.forEach((i,d)=>{var u;let l=y("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ml}px`,l.style.maxHeight=`${fg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),ov(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},dv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!El(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=`${Ml}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},pv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!El(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=`${Ml}px`,o.style.maxHeight=`${fg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},uv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!El(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),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ks=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let 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",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},hg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ks};if(t){let o=t(r);if(o!==null)return o}return ks()},mv=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.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",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},gg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},gv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},yg=(e,t,n)=>{var v,x,E,T,L,k,M;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(E=t.showDownvote)!=null?E:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let i=(L=t.visibility)!=null?L:"hover",d=(k=t.align)!=null?k:"right",l=(M=t.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(P,C,R)=>{let F=Kt({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",R),F};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Ca=(e,t,n,r,o,s)=>{var se,ie,ae,xe,Be,V,X,He,K,ue,$e,fe,Ve,et,Ot,Xe,ye;let a=n!=null?n:{},i=(se=a.layout)!=null?se:"bubble",d=a.avatar,l=a.timestamp,p=(ie=d==null?void 0:d.show)!=null?ie:!1,u=(ae=l==null?void 0:l.show)!=null?ae:!1,g=(xe=d==null?void 0:d.position)!=null?xe:"left",f=(Be=l==null?void 0:l.position)!=null?Be:"below",v=gv(e.role,i),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.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 E=sv(e),T=(X=(V=e.content)==null?void 0:V.trim())!=null?X:"",k=E.length>0&&T===Va,M=si((K=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.features)==null?void 0:K.streamAnimation),P=(fe=($e=(ue=s==null?void 0:s.widgetConfig)==null?void 0:ue.features)==null?void 0:$e.streamAnimation)==null?void 0:fe.plugins,C=e.role==="assistant"&&M.type!=="none"?fa(M.type,P):null,R=e.role==="assistant"&&((Ve=C==null?void 0:C.isAnimating)==null?void 0:Ve.call(C,e))===!0,F=e.role==="assistant"&&C!==null&&(!!e.streaming||R);F&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&j.classList.add(C.containerClass),j.style.setProperty("--persona-stream-step",`${M.speed}ms`),j.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let H=F?ai((et=e.content)!=null?et:"",M.buffer,C,e,!!e.streaming):(Ot=e.content)!=null?Ot:"",O=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),N=O;F&&(C==null?void 0:C.wrap)==="char"?N=ha(O,"char",e.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=ha(O,"word",e.id,{skipTags:C.skipTags}));let Y=null;if(k?(Y=document.createElement("div"),Y.innerHTML=N,Y.style.display="none",j.appendChild(Y)):j.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&T){let J=ii(),dt=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=dt[dt.length-1];if(qe!=null&&qe.parentNode)qe.parentNode.insertBefore(J,qe.nextSibling);else{let Se=j.lastElementChild;Se?Se.appendChild(J):j.appendChild(J)}}if(u&&f==="inline"&&e.createdAt){let J=gg(e,l,"span");J.classList.add("persona-timestamp-inline");let dt=j.lastElementChild;dt?dt.appendChild(J):j.appendChild(J)}if(E.length>0){let J=cv(E,!k&&!!T,()=>{k&&Y&&(Y.style.display="")});J?x.appendChild(J):k&&Y&&(Y.style.display="")}let ke=av(e);if(ke.length>0){let J=dv(ke);J&&x.appendChild(J)}let pe=iv(e);if(pe.length>0){let J=pv(pe);J&&x.appendChild(J)}let Z=lv(e);if(Z.length>0){let J=uv(Z);J&&x.appendChild(J)}if(x.appendChild(j),u&&f==="below"&&e.createdAt){let J=gg(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let Te=e.role==="assistant"?nv(e.stopReason,(ye=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:ye.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(H&&H.trim()),dt=M.placeholder==="skeleton",qe=dt&&M.buffer==="line"&&J;if(J)qe&&x.appendChild(ya());else if(dt)x.appendChild(ya());else{let Se=hg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Se&&x.appendChild(Se)}}if(Te&&e.stopReason&&!e.streaming&&(T||(j.style.display="none"),x.appendChild(rv(e.stopReason,Te))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=yg(e,r,o);x.appendChild(J)}if(!p||e.role==="system")return x;let oe=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=mv(d,e.role);return g==="right"||g==="left"&&e.role==="user"?oe.append(x,Ae):oe.append(Ae,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),oe},fv=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ca(e,t,n,r,o,s)};var Ls=new Set,hv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),yv=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
+ `):""},bg=(e,t)=>{let n=Ls.has(e),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",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},kl=(e,t)=>{var pe,Z,Te,Le,oe,Ae,se,ie,ae,xe,Be;let n=e.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-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(Z=(pe=t==null?void 0:t.features)==null?void 0:pe.reasoningDisplay)!=null?Z:{},s=o.expandable!==!1,a=s&&Ls.has(e.id),i=n.status!=="complete",d=yv(e,(Te=o.previewMaxLines)!=null?Te:3),l=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");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(Le=t==null?void 0:t.reasoning)!=null?Le:{},v=String((oe=n.startedAt)!=null?oe:Date.now()),x=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=Ua(n),V},E=(Ae=f.renderCollapsedSummary)==null?void 0:Ae.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ua(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(u.textContent=E,p.appendChild(u)):E instanceof HTMLElement?p.appendChild(E):(u.textContent=g,p.appendChild(u));let T=y("span","persona-text-xs persona-text-persona-primary");T.textContent=vm(n),p.appendChild(T);let L=(se=o.loadingAnimation)!=null?se:"none",k=f.activeTextTemplate,M=f.completeTextTemplate,P=i?k:M,C=E instanceof HTMLElement,R=(V,X,He)=>{let K=He;for(let ue of X){let $e=y("span","persona-tool-char");$e.style.setProperty("--char-index",String(K)),$e.textContent=ue===" "?"\xA0":ue,V.appendChild($e),K++}return K},F=(V,X)=>{u.textContent="";let He=qa(V,""),K=0;for(let ue of He){let $e=ue.styles.length>0?(()=>{let fe=y("span",ue.styles.map(Ve=>`persona-tool-text-${Ve}`).join(" "));return u.appendChild(fe),fe})():u;if(ue.isDuration&&i)$e.appendChild(x());else{let fe=ue.isDuration?Ua(n):ue.text;X?K=R($e,fe,K):$e.appendChild(document.createTextNode(fe))}}};if(!C&&P)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(ie=f.loadingAnimationDuration)!=null?ie:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),F(P,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),F(P,!0))}else F(P,!1);else if(!C&&i&&L!=="none"){u.style.display="";let V=(ae=f.loadingAnimationDuration)!=null?ae:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let X=u.textContent||g;u.textContent="",R(u,X,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=y("div","persona-flex persona-items-center");let X=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show";let He=y("div","persona-flex persona-items-center persona-ml-auto");He.append(j),l.append(p,He)}else l.append(p);let H=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","reasoning"),H.style.display="none",H.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(Be=(xe=t==null?void 0:t.reasoning)==null?void 0:xe.renderCollapsedPreview)==null?void 0:Be.call(xe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});hv(H,V)||(H.textContent=d),H.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,H),r;let O=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let N=n.chunks.join(""),Y=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Y),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let X=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(l,H,O),r};var Ps=new Set,bv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),xv=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
+ `);let o=Ao(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
+ `):""},Ll=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},vv=(e,t)=>{var p,u,g,f,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=xv(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?wm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=nl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=nl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},xg=(e,t,n)=>{var p;let r=Ps.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},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"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=ge(r?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Pl=(e,t)=>{var N,Y,ke,pe,Z,Te,Le,oe,Ae;let n=e.toolCall,r=(N=t==null?void 0:t.toolCall)!=null?N:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(ke=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?ke:{},a=s.expandable!==!1,i=a&&Ps.has(e.id),{summary:d,previewText:l,isActive:p}=vv(e,t),u=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");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let v=String((pe=n.startedAt)!=null?pe:Date.now()),x=()=>{let se=y("span","");return se.setAttribute("data-tool-elapsed",v),se.textContent=ra(n),se},E=(Te=r.renderCollapsedSummary)==null?void 0:Te.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Z=s.collapsedMode)!=null?Z:"tool-call",isActive:p,config:t!=null?t:{},elapsed:ra(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=d,g.appendChild(f));let T=(Le=s.loadingAnimation)!=null?Le:"none",L=r.activeTextTemplate,k=r.completeTextTemplate,M=p?L:k,P=E instanceof HTMLElement,C=(se,ie,ae)=>{let xe=ae;for(let Be of ie){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(xe)),V.textContent=Be===" "?"\xA0":Be,se.appendChild(V),xe++}return xe},R=(se,ie)=>{var V;f.textContent="";let ae=((V=n.name)==null?void 0:V.trim())||"tool",xe=qa(se,ae),Be=0;for(let X of xe){let He=X.styles.length>0?(()=>{let K=y("span",X.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return f.appendChild(K),K})():f;if(X.isDuration&&p)He.appendChild(x());else{let K=X.isDuration?ra(n):X.text;ie?Be=C(He,K,Be):He.appendChild(document.createTextNode(K))}}};if(!P)if(p&&T!=="none"){let se=(oe=r.loadingAnimationDuration)!=null?oe:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${se}ms`),M&&R(M,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${se}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)R(M,!0);else{let ie=f.textContent||d;f.textContent="",C(f,ie,0)}}else M&&R(M,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let se=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ie=ge(i?"chevron-up":"chevron-down",16,se,2);ie?F.appendChild(ie):F.textContent=i?"Hide":"Show";let ae=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(F),u.append(g,ae)}else u.append(g);let j=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let se=(Ae=r.renderCollapsedPreview)==null?void 0:Ae.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});bv(j,se)||(j.textContent=l),j.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,j),o;let H=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),n.name){let se=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?se.style.color=r.contentTextColor:r.headerTextColor&&(se.style.color=r.headerTextColor),se.textContent=n.name,H.appendChild(se)}if(n.args!==void 0){let se=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Arguments";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Ll(ae,r),ae.textContent=Ao(n.args),se.append(ie,ae),H.appendChild(se)}if(n.chunks&&n.chunks.length){let se=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Activity";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Ll(ae,r),ae.textContent=n.chunks.join(""),se.append(ie,ae),H.appendChild(se)}if(n.status==="complete"&&n.result!==void 0){let se=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Result";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Ll(ae,r),ae.textContent=Ao(n.result),se.append(ie,ae),H.appendChild(se)}if(n.status==="complete"&&typeof n.duration=="number"){let se=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(se.style.color=r.contentTextColor),se.textContent=`Duration: ${n.duration}ms`,H.appendChild(se)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let se=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ie=ge(i?"chevron-up":"chevron-down",16,se,2);ie?F.appendChild(ie):F.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(u,j,H),o};var ts=new Map,bi=e=>{let n=(e.startsWith(Dr)?e.slice(Dr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},vg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,wg=(e,t)=>{var r,o,s;let n=(o=(r=vg(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=ts.get(e))!=null?s:n==="expanded"},Cg=(e,t,n)=>{var a,i;let r=vg(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.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=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ge(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Ag=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=wg(e,n);Cg(r,s,n),o.style.display=s?"":"none"};var xi=(e,t)=>{var R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae,se;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(R=r==null?void 0:r.backgroundColor)!=null?R:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(F=r==null?void 0:r.borderColor)!=null?F:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(j=r==null?void 0:r.titleColor)!=null?j:"currentColor",p=ge(d,20,l,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(f),!o){let ie=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ie.setAttribute("data-approval-status",n.status),n.status==="approved"?(ie.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ie.style.color="var(--persona-palette-colors-success-700, #15803d)",ie.textContent="Approved"):n.status==="denied"?(ie.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ie.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ie.textContent="Denied"):n.status==="timeout"&&(ie.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ie.style.color="var(--persona-palette-colors-warning-700, #b45309)",ie.textContent="Timeout"),g.appendChild(ie)}u.appendChild(g);let x=n.toolType==="webmcp"||n.toolName.startsWith(Dr)?Qs(n.toolName):void 0,E=(O=r==null?void 0:r.formatDescription)==null?void 0:O.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=E||(T?n.description:`The assistant wants to use \u201C${x!=null?x:bi(n.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=L,u.appendChild(k),n.reason){let ie=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ie.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?ie.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let ae=y("span","persona-font-medium");ae.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,ie.appendChild(ae),ie.appendChild(document.createTextNode(n.reason)),u.appendChild(ie)}let M=(Y=r==null?void 0:r.detailsDisplay)!=null?Y:"collapsed",P=!!n.description&&!T,C=P||!!n.parameters;if(M!=="hidden"&&C){let ie=wg(e.id,t),ae=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");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let xe=y("span");xe.setAttribute("data-approval-details-label","true");let Be=y("span","persona-inline-flex persona-items-center");Be.setAttribute("data-approval-details-chevron","true"),ae.append(xe,Be),Cg(ae,ie,t),u.appendChild(ae);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=ie?"":"none",P){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor),X.textContent=n.description,V.appendChild(X)}if(n.parameters){let X=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&&(X.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(X.style.color=r.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=Ao(n.parameters),V.appendChild(X)}u.appendChild(V)}if(o){let ie=y("div","persona-flex persona-gap-2 persona-mt-2");ie.setAttribute("data-approval-buttons","true");let ae=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");ae.type="button",ae.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",ae.setAttribute("data-approval-action","approve");let xe=ge("shield-check",14,(Z=r==null?void 0:r.approveButtonTextColor)!=null?Z:"#ffffff",2);xe&&(xe.style.marginRight="4px",ae.appendChild(xe));let Be=document.createTextNode((Te=r==null?void 0:r.approveLabel)!=null?Te:"Approve");ae.appendChild(Be);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=(Le=r==null?void 0:r.denyButtonColor)!=null?Le:"transparent",V.style.color=(oe=r==null?void 0:r.denyButtonTextColor)!=null?oe:"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 X=ge("shield-x",14,(Ae=r==null?void 0:r.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",V.appendChild(X));let He=document.createTextNode((se=r==null?void 0:r.denyLabel)!=null?se:"Deny");V.appendChild(He),ie.append(ae,V),u.appendChild(ie)}return a.append(i,u),s.appendChild(a),s};function wv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function Sg(e){var x;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,l=(x=e.container)!=null?x:wv(t),p=!1,u=null,g=()=>{if(!p)return;let E=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`);let T=r==="top-start"||r==="top-end"?E.top-o-n.getBoundingClientRect().height:E.bottom+o,L=r==="bottom-end"||r==="top-end"?E.right-n.getBoundingClientRect().width:E.left;n.style.top=`${T}px`,n.style.left=`${L}px`},f=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},v=()=>{var P,C,R;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),l.appendChild(n),g();let E=(C=((P=t.ownerDocument)!=null?P:document).defaultView)!=null?C:window,T=(R=t.ownerDocument)!=null?R:document,L=()=>{if(!t.isConnected){f(),d==null||d("anchor-removed");return}g()},k=F=>{let j=typeof F.composedPath=="function"?F.composedPath():[];j.includes(n)||j.includes(t)||(f(),d==null||d("outside"))},M=E.setTimeout(()=>{T.addEventListener("pointerdown",k,!0)},0);E.addEventListener("scroll",L,!0),E.addEventListener("resize",L),u=()=>{E.clearTimeout(M),T.removeEventListener("pointerdown",k,!0),E.removeEventListener("scroll",L,!0),E.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:v,close:f,toggle:()=>p?f():v(),reposition:g,destroy:f}}function Tg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Cv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Eg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},ns=(e,t)=>{Eg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Av=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Sv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=ts.get(e))!=null?o:n==="expanded"},Il=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},Tv=(e,t)=>{var l,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Dr)?Qs(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:bi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},Ev=e=>{let t=y("div","persona-approval-resolved"),n=ge("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?bi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Mv=(e,t,n,r,o,s,a)=>{var F,j,H,O,N,Y,ke;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(F=r==null?void 0:r.detailsDisplay)!=null?F:"collapsed",l=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=l||p,g=u&&Sv(t.id,r),f=(j=r==null?void 0:r.showDetailsLabel)!=null?j:"Show details",v=(H=r==null?void 0:r.hideDetailsLabel)!=null?H:"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",g?"true":"false"),x.setAttribute("aria-label",g?v:f)):x.setAttribute("data-static","true");let E=y("span","persona-approval-logo"),T=ge("shield-check",16,"currentColor",2);T&&E.appendChild(T),x.appendChild(E);let L=Tv(n,r);if(u){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let Z=ge("chevron-down",14,"currentColor",2);Z&&pe.appendChild(Z),L.append(" "),L.appendChild(pe)}x.appendChild(L),i.appendChild(x);let k=y("div","persona-approval-body");if(u){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,l){let Z=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(Z.style.color=r.descriptionColor),Z.textContent=n.description,pe.appendChild(Z)}if(p){let Z=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(Z.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Z.style.color=r.parameterTextColor),Z.textContent=Ao(n.parameters),pe.appendChild(Z)}k.appendChild(pe)}if(n.reason){let pe=y("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let Z=y("span","persona-approval-reason-label");Z.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,pe.append(Z,document.createTextNode(n.reason)),k.appendChild(pe)}let M=y("div","persona-approval-actions"),P=null,C=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},R=y("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(R.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(R.style.color=r.denyButtonTextColor),R.append((N=r==null?void 0:r.denyLabel)!=null?N:"Deny"),a){let pe=y("div","persona-approval-split"),Z=y("button","persona-approval-primary");Z.type="button",Z.setAttribute("data-action","always"),C(Z),Z.append((Y=r==null?void 0:r.approveLabel)!=null?Y:"Always allow",Il("\u23CE"));let Te=y("button","persona-approval-caret");Te.type="button",Te.setAttribute("data-action","toggle-menu"),Te.setAttribute("aria-label","More options"),C(Te);let Le=ge("chevron-down",15,"currentColor",2);Le&&Te.appendChild(Le),pe.append(Z,Te),M.append(pe,R),R.append(Il("Esc"));let oe=y("div","persona-approval-menu"),Ae=y("button","persona-approval-menu-item");Ae.type="button",Ae.append("Allow once",Il("\u2318\u23CE")),oe.appendChild(Ae),P=Sg({anchor:pe,content:oe,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,P),Ae.addEventListener("click",()=>{ns(e,t.id),o()})}else{let pe=y("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),C(pe),pe.append((ke=r==null?void 0:r.approveLabel)!=null?ke:"Allow"),M.append(pe,R)}return k.appendChild(M),i.appendChild(k),i.addEventListener("click",pe=>{let Z=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!Z)return;let Te=Z.getAttribute("data-action");if(Te==="toggle-params"){let Le=i.querySelector('[data-role="params"]');if(Le){let oe=Le.hidden;Le.hidden=!oe,x.setAttribute("aria-expanded",oe?"true":"false"),x.setAttribute("aria-label",oe?v:f),ts.set(t.id,oe)}return}if(Te==="toggle-menu"){P==null||P.toggle();return}if(Te==="always"){ns(e,t.id),o({remember:!0});return}if(Te==="allow"){ns(e,t.id),o();return}if(Te==="deny"){ns(e,t.id),s();return}}),i},Mg=()=>{let e=Cv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Av(a);if(i.status!=="pending"){if(ns(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Ev(i)}Eg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=Mv(e,r,i,d,o,s,l);if(l){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{Tg(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),ns(e,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])ns(e,r);e.latestPendingApprovalId=null}}};var kg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=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=g,d!=null&&d.fontFamily&&(x.style.fontFamily=f(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="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(x),t.push(x)}),e.appendChild(u),p){let v=JSON.stringify(o);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Aa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;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),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){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 Sa=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let 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=()=>{n(r.error)}}catch(r){n(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,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{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=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{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=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(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 kv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Lv=new Set(["step_start","execution_start"]),Pv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Iv=new Set(["step_complete","agent_turn_complete"]),Rv=new Set(["flow_complete","agent_complete"]),Lg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ig=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Un=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,rs=(e,t)=>{let n=e[t];return Ig(n)?n:void 0};function Rl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function vi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Wv(e,t){return typeof t.type=="string"?t.type:e}function Hv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Bv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Pg(e){var r,o,s,a,i;let t=rs(e,"result"),n=[rs(e,"tokens"),rs(e,"totalTokens"),t?rs(t,"tokens"):void 0,rs(e,"usage"),t?rs(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Un(d.output))!=null?r:Un(d.outputTokens))!=null?o:Un(d.completionTokens);if(l!==void 0)return l}return(i=(s=Un(e.outputTokens))!=null?s:Un(e.completionTokens))!=null?i:t?(a=Un(t.outputTokens))!=null?a:Un(t.completionTokens):void 0}function Dv(e){var n,r,o,s,a;let t=rs(e,"result");return(a=(o=(r=(n=Un(e.executionTime))!=null?n:Un(e.executionTimeMs))!=null?r:Un(e.execution_time))!=null?o:Un(e.duration))!=null?a:t?(s=Un(t.executionTime))!=null?s:Un(t.executionTimeMs):void 0}function Nv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ta=class{constructor(t=Nv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:vi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!Ig(n)){Lg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Wv(t,n),o=this.now();if(kv.has(r)){this.startRun(o);return}if(Lv.has(r)){this.run||this.startRun(o);return}if(Pv.has(r)){if(!Bv(r,n))return;let a=Hv(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Rl(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:vi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Iv.has(r)){if(!this.run)return;let a=this.run,i=Pg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Rl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:vi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Rv.has(r)){if(!this.run)return;let a=this.run,i=Pg(n),d=i!=null?i:a.exactOutputTokens+Rl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:vi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Lg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Dv(n);return s!=null?s:r-t.startedAt}};function Is(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Ov={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)"}},Fv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},_v=["flowName","stepName","reasoningText","text","name","tool","toolName"],$v=100;function jv(e,t){let n={...Ov,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Fv}function Uv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function qv(e){let t=new Date(e),n=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`${n}:${r}:${o}.${s}`}function zv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Vv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function Kv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Gv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Jv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Xv(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Wl(e,t,n,r,o,s,a,i){var g;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Is(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var N,Y;let f=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",e.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"),E=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(N=r.timestampFormat)!=null?N:"relative";T.textContent=L==="relative"?Uv(e.timestamp,n):qv(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let M=jv(e.type,r.badgeColors),P=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=M.bg,P.style.color=M.text,P.style.borderColor=M.text+"50",P.textContent=e.type;let C=(Y=r.descriptionFields)!=null?Y:_v,R=zv(e.payload,C),F=null;R&&(F=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=R);let j=y("div","persona-flex-1 persona-min-w-0"),H=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"),O=ge("clipboard","12px","currentColor",1.5);return O&&H.appendChild(O),H.addEventListener("click",async ke=>{ke.stopPropagation(),await Vv(Kv(e)),H.innerHTML="";let pe=ge("check","12px","currentColor",1.5);pe&&H.appendChild(pe),setTimeout(()=>{H.innerHTML="";let Z=ge("clipboard","12px","currentColor",1.5);Z&&H.appendChild(Z)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(P),F&&v.appendChild(F),v.appendChild(j),v.appendChild(H),f.appendChild(v),d&&f.appendChild(Xv(e,a,i)),f}}function Rg(e){var v,x,E,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},g=s.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let k=g.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=u.classNames,M=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Is(M,k==null?void 0:k.panel);let P=[],C="",R="",F=null,j=[],H={},O=0,N=ni(),Y=0,ke=0,pe=!1,Z=null,Te=!1,Le=0,oe=new Set,Ae=new Map,se="",ie="",ae=null,xe,Be,V,X,He=null,K=null,ue=null;function $e(){let ce=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),B=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");if(Is(B,k==null?void 0:k.headerBar),a){K=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),K.style.cursor="help",He=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"),He.textContent="-- tok/s",ue=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"),ue.style.display="none",ue.style.pointerEvents="none";let Ft=K,en=ue,wr=()=>{if(!en.textContent)return;let sr=Ft.getBoundingClientRect(),ar=ce.getBoundingClientRect();en.style.left=`${sr.left-ar.left}px`,en.style.top=`${sr.bottom-ar.top+4}px`,en.style.display="block"},$r=()=>{en.style.display="none"};K.addEventListener("mouseenter",wr),K.addEventListener("mouseleave",$r),K.appendChild(He)}let be=y("div","persona-flex-1");xe=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 _e=y("option","");_e.value="",_e.textContent="All events (0)",xe.appendChild(_e),Be=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"),Be.type="button",Be.title="Copy All";let Ye=ge("clipboard-copy","12px","currentColor",1.5);Ye&&Be.appendChild(Ye);let Rt=y("span","persona-event-copy-all persona-text-xs");Rt.textContent="Copy All",Be.appendChild(Rt),K&&B.appendChild(K),B.appendChild(be),B.appendChild(xe),B.appendChild(Be);let St=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Is(St,k==null?void 0:k.searchBar);let ht=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),kt=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");ht&&kt.appendChild(ht),V=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"),Is(V,k==null?void 0:k.searchInput),V.type="text",V.placeholder="Search event payloads...",X=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"),X.type="button",X.style.display="none";let Xt=ge("x","12px","currentColor",2);return Xt&&X.appendChild(Xt),St.appendChild(kt),St.appendChild(V),St.appendChild(X),ce.appendChild(B),ce.appendChild(St),ue&&ce.appendChild(ue),ce}let fe,Ve=s.find(ce=>ce.renderEventStreamToolbar);if(Ve!=null&&Ve.renderEventStreamToolbar&&o){let ce=Ve.renderEventStreamToolbar({config:o,defaultRenderer:()=>$e(),eventCount:t.getSize(),filteredCount:0,onFilterChange:B=>{C=B,ee(),bt()},onSearchChange:B=>{R=B,ee(),bt()}});fe=ce!=null?ce:$e()}else fe=$e();let et=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");et.style.display="none";function Ot(){if(!a||!He||!K)return;let ce=a(),B=Gv(ce);He.textContent=B;let be=Jv(ce);ue&&(ue.textContent=be,be||(ue.style.display="none")),K.setAttribute("aria-label",be?`Throughput: ${B}, ${be}`:`Throughput: ${B}`)}let Xe=y("div","persona-flex-1 persona-min-h-0 persona-relative"),ye=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ye.style.height="100%";let J=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");Is(J,k==null?void 0:k.scrollIndicator),J.style.display="none",J.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let dt=ge(l,"14px","currentColor",2);dt&&J.appendChild(dt);let qe=y("span","");qe.textContent=p,J.appendChild(qe);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",Xe.appendChild(ye),Xe.appendChild(Se),Xe.appendChild(J),M.setAttribute("tabindex","0"),M.appendChild(fe),M.appendChild(et),M.appendChild(Xe);function ve(){let ce=t.getAll(),B={};for(let St of ce)B[St.type]=(B[St.type]||0)+1;let be=Object.keys(B).sort(),_e=be.length!==j.length||!be.every((St,ht)=>St===j[ht]),xt=!_e&&be.some(St=>B[St]!==H[St]),Ye=ce.length!==Object.values(H).reduce((St,ht)=>St+ht,0);if(!_e&&!xt&&!Ye||(j=be,H=B,!xe))return;let Rt=xe.value;if(xe.options[0].textContent=`All events (${ce.length})`,_e){for(;xe.options.length>1;)xe.remove(1);for(let St of be){let ht=y("option","");ht.value=St,ht.textContent=`${St} (${B[St]||0})`,xe.appendChild(ht)}Rt&&be.includes(Rt)?xe.value=Rt:Rt&&(xe.value="",C="")}else for(let St=1;St<xe.options.length;St++){let ht=xe.options[St];ht.textContent=`${ht.value} (${B[ht.value]||0})`}}function nt(){let ce=t.getAll();if(C&&(ce=ce.filter(B=>B.type===C)),R){let B=R.toLowerCase();ce=ce.filter(be=>be.type.toLowerCase().includes(B)||be.payload.toLowerCase().includes(B))}return ce}function Lt(){return C!==""||R!==""}function ee(){O=0,Y=0,N.resume(),J.style.display="none"}function je(ce){oe.has(ce)?oe.delete(ce):oe.add(ce),ae=ce;let B=ye.scrollTop,be=N.isFollowing();Te=!0,N.pause(),bt(),ye.scrollTop=B,be&&N.resume(),Te=!1}function wn(){return So(ye,50)}function bt(){ke=Date.now(),pe=!1,Ot(),ve();let ce=t.getEvictedCount();ce>0?(et.textContent=`${ce.toLocaleString()} older events truncated`,et.style.display=""):et.style.display="none",P=nt();let B=P.length,be=t.getSize()>0;B===0&&be&&Lt()?(Se.textContent=R?`No events matching '${R}'`:"No events matching filter",Se.style.display="",ye.style.display="none"):(Se.style.display="none",ye.style.display=""),Be&&(Be.title=Lt()?`Copy Filtered (${B})`:"Copy All"),d&&!N.isFollowing()&&B>O&&(Y+=B-O,qe.textContent=p?`${p}${Y>0?` (${Y})`:""}`:"",J.style.display=""),O=B;let _e=t.getAll(),xt=_e.length>0?_e[0].timestamp:0,Ye=new Set(P.map(ht=>ht.id));for(let ht of oe)Ye.has(ht)||oe.delete(ht);let Rt=C!==se||R!==ie,St=Ae.size===0&&P.length>0;if(Rt||St||P.length===0){ye.innerHTML="",Ae.clear();let ht=document.createDocumentFragment();for(let kt=0;kt<P.length;kt++){let Xt=Wl(P[kt],kt,xt,u,oe,je,s,o);Ae.set(P[kt].id,Xt),ht.appendChild(Xt)}ye.appendChild(ht),se=C,ie=R,ae=null}else{if(ae!==null){let kt=Ae.get(ae);if(kt&&kt.parentNode===ye){let Xt=P.findIndex(Ft=>Ft.id===ae);if(Xt>=0){let Ft=Wl(P[Xt],Xt,xt,u,oe,je,s,o);ye.insertBefore(Ft,kt),kt.remove(),Ae.set(ae,Ft)}}ae=null}let ht=new Set(P.map(kt=>kt.id));for(let[kt,Xt]of Ae)ht.has(kt)||(Xt.remove(),Ae.delete(kt));for(let kt=0;kt<P.length;kt++){let Xt=P[kt];if(!Ae.has(Xt.id)){let Ft=Wl(Xt,kt,xt,u,oe,je,s,o);Ae.set(Xt.id,Ft),ye.appendChild(Ft)}}}N.isFollowing()&&(ye.scrollTop=ye.scrollHeight)}function fn(){if(Date.now()-ke>=$v){Z!==null&&(cancelAnimationFrame(Z),Z=null),bt();return}pe||(pe=!0,Z=requestAnimationFrame(()=>{Z=null,bt()}))}let xr=(ce,B)=>{if(!Be)return;Be.innerHTML="";let be=ge(ce,"12px","currentColor",1.5);be&&Be.appendChild(be);let _e=y("span","persona-text-xs");_e.textContent="Copy All",Be.appendChild(_e),setTimeout(()=>{Be.innerHTML="";let xt=ge("clipboard-copy","12px","currentColor",1.5);xt&&Be.appendChild(xt);let Ye=y("span","persona-text-xs");Ye.textContent="Copy All",Be.appendChild(Ye),Be.disabled=!1},B)},vr=async()=>{if(Be){Be.disabled=!0;try{let ce;Lt()?ce=P:n?(ce=await n(),ce.length===0&&(ce=t.getAll())):ce=t.getAll();let B=ce.map(be=>{try{return JSON.parse(be.payload)}catch{return be.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),xr("check",1500)}catch{xr("x",1500)}}},A=()=>{xe&&(C=xe.value,ee(),bt())},te=()=>{!V||!X||(X.style.display=V.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{R=V.value,ee(),bt()},150))},Me=()=>{!V||!X||(V.value="",R="",X.style.display="none",F&&clearTimeout(F),ee(),bt())},Ne=()=>{if(Te)return;let ce=ye.scrollTop,{action:B,nextLastScrollTop:be}=ri({following:N.isFollowing(),currentScrollTop:ce,lastScrollTop:Le,nearBottom:wn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Le=be,B==="resume"?(N.resume(),Y=0,J.style.display="none"):B==="pause"&&(N.pause(),d&&(qe.textContent=p,J.style.display=""))},Ie=ce=>{let B=oi({following:N.isFollowing(),deltaY:ce.deltaY,nearBottom:wn(),resumeWhenNearBottom:!0});B==="pause"?(N.pause(),d&&(qe.textContent=p,J.style.display="")):B==="resume"&&(N.resume(),Y=0,J.style.display="none")},Oe=()=>{d&&(ye.scrollTop=ye.scrollHeight,N.resume(),Y=0,J.style.display="none")},Ge=ce=>{let B=ce.target;if(!B||B.closest("button"))return;let be=B.closest("[data-event-id]");if(!be)return;let _e=be.getAttribute("data-event-id");_e&&je(_e)},at=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),V==null||V.focus(),V==null||V.select();return}ce.key==="Escape"&&(V&&document.activeElement===V?(Me(),V.blur(),M.focus()):r&&r())};Be&&Be.addEventListener("click",vr),xe&&xe.addEventListener("change",A),V&&V.addEventListener("input",te),X&&X.addEventListener("click",Me),ye.addEventListener("scroll",Ne),ye.addEventListener("wheel",Ie,{passive:!0}),ye.addEventListener("click",Ge),J.addEventListener("click",Oe),M.addEventListener("keydown",at);function Pt(){F&&clearTimeout(F),Z!==null&&(cancelAnimationFrame(Z),Z=null),pe=!1,Ae.clear(),Be&&Be.removeEventListener("click",vr),xe&&xe.removeEventListener("change",A),V&&V.removeEventListener("input",te),X&&X.removeEventListener("click",Me),ye.removeEventListener("scroll",Ne),ye.removeEventListener("wheel",Ie),ye.removeEventListener("click",Ge),J.removeEventListener("click",Oe),M.removeEventListener("keydown",at)}return{element:M,update:fn,destroy:Pt}}}function Wg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(f)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Hg=(e,t)=>{var r,o,s;let n=(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(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Wg(e,t)});if(p)return p}return Wg(e,t)};var Hl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}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(([n,r])=>{this.register(n,r)})}},Lo=new Hl;Lo.register("PersonaArtifactCard",Hg);function Qv(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.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=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Bg(e,t){var Be,V,X,He;let n=(V=(Be=e.features)==null?void 0:Be.artifacts)==null?void 0:V.layout,o=((X=n==null?void 0:n.toolbarPreset)!=null?X:"default")==="document",s=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?bs(e.markdown):null,i=Js(e.sanitize),d=K=>{let ue=a?a(K):Yr(K);return i?i(ue):ue},l=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,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let u=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");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let g=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.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 K;p(),(K=t.onDismiss)==null||K.call(t)});let x="rendered",E=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Kt({icon:"eye",label:"Rendered view"}),L=o?Kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Kt({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,R=!!(P&&C&&C.length>0),F=null,j,H=null,O=null;if(o&&(M||P)&&!R){if(j=M?di({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let K=ge("chevron-down",14,"currentColor",2);K&&j.appendChild(K)}}else o&&R?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=M?di({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=Kt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append(j,H)):o?j=Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Kt({icon:"copy",label:"Copy"});let N=o?Kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"refresh-cw",label:"Refresh"}),Y=o?Kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"x",label:"Close"}),ke=()=>{var Ve,et,Ot;let K=(Ve=Ae.find(Xe=>Xe.id===se))!=null?Ve:Ae[Ae.length-1],ue=(et=K==null?void 0:K.id)!=null?et:null,$e=(K==null?void 0:K.artifactType)==="markdown"&&(Ot=K.markdown)!=null?Ot:"",fe=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:$e,jsonPayload:fe,id:ue}},pe=async()=>{var Ve;let{markdown:K,jsonPayload:ue}=ke(),$e=(Ve=Ae.find(et=>et.id===se))!=null?Ve:Ae[Ae.length-1],fe=($e==null?void 0:$e.artifactType)==="markdown"?K:$e?ue:"";try{await navigator.clipboard.writeText(fe)}catch{}};if(j.addEventListener("click",async()=>{let K=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(K&&R){let{markdown:ue,jsonPayload:$e,id:fe}=ke();try{await K({actionId:"primary",artifactId:fe,markdown:ue,jsonPayload:$e})}catch{}return}await pe()}),H&&(C!=null&&C.length)){let K=()=>{var $e;return($e=u.closest("[data-persona-root]"))!=null?$e:document.body},ue=()=>{O=es({items:C.map($e=>({id:$e.id,label:$e.label})),onSelect:async $e=>{let{markdown:fe,jsonPayload:Ve,id:et}=ke(),Ot=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ot?await Ot({actionId:$e,artifactId:et,markdown:fe,jsonPayload:Ve}):$e==="markdown"||$e==="md"?await navigator.clipboard.writeText(fe):$e==="json"||$e==="source"?await navigator.clipboard.writeText(Ve):await navigator.clipboard.writeText(fe||Ve)}catch{}},anchor:F!=null?F:H,position:"bottom-right",portal:K()})};u.isConnected?ue():requestAnimationFrame(ue),H.addEventListener("click",$e=>{$e.stopPropagation(),O==null||O.toggle()})}N.addEventListener("click",async()=>{var K;try{await((K=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:K.call(n))}catch{}ae()}),Y.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let Z=()=>{o&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Z(),ae()}),L.addEventListener("click",()=>{x="source",Z(),ae()});let Te=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),E.append(T,L),F?k.append(F,N,Y):k.append(j,N,Y),g.append(E,Te,k),Z()):(g.appendChild(f),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Le=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"),oe=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Le.style.paddingLeft=s,Le.style.paddingRight=s,oe.style.padding=s),u.appendChild(g),u.appendChild(Le),u.appendChild(oe);let Ae=[],se=null,ie=!1,ae=()=>{var fe,Ve,et,Ot;let K=o&&Ae.length<=1;Le.classList.toggle("persona-hidden",K),Le.replaceChildren();for(let Xe of Ae){let ye=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");ye.type="button",ye.textContent=Xe.title||Xe.id.slice(0,8),Xe.id===se&&ye.classList.add("persona-bg-persona-container","persona-border-persona-border"),ye.addEventListener("click",()=>t.onSelect(Xe.id)),Le.appendChild(ye)}oe.replaceChildren();let ue=se&&Ae.find(Xe=>Xe.id===se)||Ae[Ae.length-1];if(!ue)return;if(o){let Xe=ue.artifactType==="markdown"?"MD":(fe=ue.component)!=null?fe:"Component",J=(ue.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Te.textContent=`${J} \xB7 ${Xe}`}else f.textContent="Artifacts";if(ue.artifactType==="markdown"){if(o&&x==="source"){let ye=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ye.textContent=(Ve=ue.markdown)!=null?Ve:"",oe.appendChild(ye);return}let Xe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((et=ue.markdown)!=null?et:""),oe.appendChild(Xe);return}let $e=ue.component?Lo.get(ue.component):void 0;if($e){let ye={message:{id:ue.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=$e((Ot=ue.props)!=null?Ot:{},ye);if(J){oe.appendChild(J);return}}catch{}}oe.appendChild(Qv(ue))},xe=()=>{var ue;let K=Ae.length>0;if(u.classList.toggle("persona-hidden",!K),l){let $e=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ve=((ue=$e==null?void 0:$e.classList.contains("persona-artifact-narrow-host"))!=null?ue:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&Ve&&ie?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(K){var ue,$e,fe;Ae=K.artifacts,se=(fe=($e=K.selectedId)!=null?$e:(ue=K.artifacts[K.artifacts.length-1])==null?void 0:ue.id)!=null?fe:null,Ae.length>0&&(ie=!0),ae(),xe()},setMobileOpen(K){ie=K,!K&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):xe()}}}function or(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Dg(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!or(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Yv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function wi(e,t){var d,l,p,u,g,f,v,x,E,T;if(!or(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Yv(e),Dg(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Dg(e,t)}var Ng=["panel","seamless"];function Ci(e,t){var i,d,l,p,u,g;for(let f of Ng)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!or(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",o=Ng.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Og(e,t){var n,r,o;return!t||!or(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Zv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function ew(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function tw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function nw(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Fg(e,t){var a;let r=(a=(t.getComputedStyle(e).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 _g(e,t,n,r,o,s){let a=Zv(o,200),i=nw(t,n,r,200);i=Math.max(a,i);let d=ew(s);return d!==null&&(i=Math.min(i,d)),tw(e,a,i)}var $g={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"}},Bl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=$g[a])!=null?x:$g.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=y("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,R;let L=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,L.appendChild(k);let M=(C=T.type)!=null?C:"text",P;M==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=M),P.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",P.id=`${t.id}-${a}-${T.name}`,P.name=T.name,P.placeholder=(R=T.placeholder)!=null?R:"",T.required&&(P.required=!0),L.appendChild(P),p.appendChild(L)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=(E=i.submitLabel)!=null?E:"Submit",u.appendChild(g),u.appendChild(f),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var P,C;T.preventDefault();let L=(P=n.formEndpoint)!=null?P:"/form",k=new FormData(p),M={};k.forEach((R,F)=>{M[F]=R}),M.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let R=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let F=await R.json();g.textContent=(C=F.message)!=null?C:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(R){g.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Dl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.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 n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Ai=new Dl;var jg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var rw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ow=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Si=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=rw(e),n=ow(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Nl=e=>typeof e=="string"?e:e==null?"":String(e),Rs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Nl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Nl(n.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:Nl(n.text)}}},Ug=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ti=e=>{let t=new Set(Ug(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Ug(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.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?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({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};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var sw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},aw=e=>e.map(t=>({...t,streaming:!1})),iw=e=>e.map(t=>({...t,status:"complete"})),Ol=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?sw(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?aw(n.messages):void 0,artifacts:n.artifacts?iw(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as lw,STR as cw,OBJ as dw}from"partial-json";function pw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function uw(e,t){if(!pw(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Fl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=lw(n,cw|dw),s=uw(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function mw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _l(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Lo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function gw(){let e=Fl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function qg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function $l(e){let t=qg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function jl(e){let t=qg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var fw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ul(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=fw}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,f.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,f.appendChild(x),g.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let C=1;C<=5;C++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${l[C-1]}`),R.title=l[C-1],R.dataset.rating=String(C),R.innerHTML=`
31
31
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
32
32
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
33
33
  </svg>
34
- `,R.addEventListener("click",()=>{u=C,T.forEach((F,j)=>{let W=j<C;F.classList.toggle("selected",W),F.setAttribute("aria-checked",j===C-1?"true":"false")})}),T.push(R),E.appendChild(R)}g.appendChild(E);let L=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),C.appendChild(L),g.appendChild(C)}let k=document.createElement("div");k.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{n==null||n(),p.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let C=(L==null?void 0:L.value.trim())||void 0;await t(u,C),p.remove()}catch(C){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),k.appendChild(M),k.appendChild(P),g.appendChild(k),p.appendChild(g),p}function Nl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.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 E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,v.appendChild(E),f.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=p,L.appendChild(k),L.appendChild(M);let P=document.createElement("div");P.className="persona-feedback-numbers";let C=[];for(let O=0;O<=10;O++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${O} out of 10`),N.textContent=String(O),N.dataset.rating=String(O),O<=6?N.classList.add("persona-feedback-detractor"):O<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{g=O,C.forEach((Y,Ee)=>{Y.classList.toggle("selected",Ee===O),Y.setAttribute("aria-checked",Ee===O?"true":"false")})}),C.push(N),P.appendChild(N)}T.appendChild(L),T.appendChild(P),f.appendChild(T);let R=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),O.appendChild(R),f.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=i,j.addEventListener("click",()=>{n==null||n(),u.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(g===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let O=(R==null?void 0:R.value.trim())||void 0;await t(g,O),u.remove()}catch(O){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),F.appendChild(j),F.appendChild(W),f.appendChild(F),u.appendChild(f),u}var Ms="persona-chat-history",Qv=30*1e3,Yv={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Zv(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Yv[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=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function wi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function ew(e){var t,n,r,o,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function tw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ol=e=>!e||typeof e!="object"?{}:{...e},Pg=e=>e.map(t=>({...t,streaming:!1})),Ig=(e,t,n)=>{let r=e!=null&&e.markdown?us(e.markdown):null,o=$s(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var p,u,g;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d=No()!==null,l;if(e!=null&&e.postprocessMessage){let f=e.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});l=o?o(f):f}else if(r){let f=s.streaming?Ru(a):a,v=r(f);l=o&&d?o(v):v}else l=Vr(a);return l}};function Rg(e){var i,d,l,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=me(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Fl=(e,t,n)=>{var Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Rc,Wc,Hc,Bc,Dc,Nc,Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Gc,Jc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=al(t),o=bi.getForInstance(r.plugins),{plugin:s,teardown:a}=ug();r.components&&vo.registerAll(r.components);let i=Mg(),l=r.persistState===!1?null:(Ac=r.storageAdapter)!=null?Ac:Il(),p={},u=null,g=!1,f=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:b}=m;return b&&(g=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(l!=null&&l.load)try{let c=l.load();if(c&&typeof c.then=="function")u=c.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return f(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=f(m);h.metadata&&(p=Ol(h.metadata)),(Sc=h.messages)!=null&&Sc.length&&(r={...r,initialMessages:h.messages}),(Tc=h.artifacts)!=null&&Tc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Ec=h.selectedArtifactId)!=null?Ec:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=f({messages:[],metadata:{}});(Mc=c.messages)!=null&&Mc.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let v=()=>p,x=c=>{var h;p=(h=c({...p}))!=null?h:{},tt()},E=r.actionParsers&&r.actionParsers.length?r.actionParsers:[xi],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Es.message,Es.messageAndClick],L=vi({parsers:E,handlers:T,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let k=(Lc=(kc=r.launcher)==null?void 0:kc.enabled)!=null?Lc:!0,M=(Ic=(Pc=r.launcher)==null?void 0:Pc.autoExpand)!=null?Ic:!1,P=(Rc=r.autoFocusInput)!=null?Rc:!1,C=M,R=k,F=(Hc=(Wc=r.layout)==null?void 0:Wc.header)==null?void 0:Hc.layout,j=!1,W=()=>bo(r),O=()=>k||W(),N=W()?!1:k?M:!0,Y=!1,Ee=null,de=()=>{Y=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},Z=Ig(r,L,de),Ce=(Dc=(Bc=r.features)==null?void 0:Bc.showReasoning)!=null?Dc:!0,ke=(Oc=(Nc=r.features)==null?void 0:Nc.showToolCalls)!=null?Oc:!0,re=(_c=(Fc=r.features)==null?void 0:Fc.showEventStreamToggle)!=null?_c:!1,we=(jc=($c=r.features)==null?void 0:$c.scrollToBottom)!=null?jc:{},le=(qc=(Uc=r.features)==null?void 0:Uc.scrollBehavior)!=null?qc:{},oe=`${(Vc=typeof r.persistState=="object"?(zc=r.persistState)==null?void 0:zc.keyPrefix:void 0)!=null?Vc:"persona-"}event-stream`,be=re?new ha(oe):null,He=(Jc=(Gc=(Kc=r.features)==null?void 0:Kc.eventStream)==null?void 0:Gc.maxEvents)!=null?Jc:2e3,V=re?new fa(He,be):null,X=re?new ya:null,We=null,K=!1,pe=null,$e=0;be==null||be.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ge={onCopy:c=>{var m,h;i.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,c)},onFeedback:c=>{var m,h;i.emit("message:feedback",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,c)}},Ve=(Xc=r.statusIndicator)!=null?Xc:{},et=c=>{var m,h,b,S;return c==="idle"?(m=Ve.idleText)!=null?m:vn.idle:c==="connecting"?(h=Ve.connectingText)!=null?h:vn.connecting:c==="connected"?(b=Ve.connectedText)!=null?b:vn.connected:c==="error"?(S=Ve.errorText)!=null?S:vn.error:vn[c]};function $t(c,m,h,b){if(b==="idle"&&h.idleLink){c.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=m,S.style.color="inherit",S.style.textDecoration="none",c.appendChild(S)}else c.textContent=m}let Xe=Ym({config:r,showClose:O()}),{wrapper:fe,panel:J,pillRoot:dt}=Xe.shell,qe=Xe.panelElements,{container:Ae,body:Me,messagesWrapper:nt,suggestions:Pt,textarea:ee,sendButton:je,sendButtonWrapper:Cn,composerForm:xt,statusText:hn,introTitle:yr,introSubtitle:br,closeButton:A,iconHolder:te,headerTitle:Te,headerSubtitle:De,header:Pe,footer:Ne,actionsRow:Ge,leftActions:it,rightActions:It}=qe,ce=qe.setSendButtonMode,H=qe.micButton,he=qe.micButtonWrapper,Fe=qe.attachmentButton,vt=qe.attachmentButtonWrapper,Ye=qe.attachmentInput,Ht=qe.attachmentPreviewsContainer;Ae.classList.add("persona-relative"),Me.classList.add("persona-relative");let Tt=12,ht=()=>{var c;return(c=we.label)!=null?c:""},Lt=()=>{var c;return(c=we.iconName)!=null?c:"arrow-down"},Qt=()=>we.enabled!==!1,Ft=()=>{var c;return(c=le.mode)!=null?c:"follow"},Hn=()=>{var c;return(c=le.anchorTopOffset)!=null?c:16},jt=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");jt.type="button",jt.style.display="none",jt.setAttribute("data-persona-scroll-to-bottom","true");let Bn=y("span","persona-flex persona-items-center"),Gn=y("span",""),yn=y("span","");yn.setAttribute("data-persona-scroll-to-bottom-count",""),yn.style.display="none",jt.append(Bn,Gn,yn),Ae.appendChild(jt);let kn=y("div","persona-stream-anchor-spacer");kn.setAttribute("aria-hidden","true"),kn.setAttribute("data-persona-anchor-spacer",""),kn.style.flexShrink="0",kn.style.pointerEvents="none",kn.style.height="0px",Me.appendChild(kn);let Jn=()=>{let m=Ne.style.display==="none"?0:Ne.offsetHeight;jt.style.bottom=`${m+Tt}px`};Jn();let Xr=()=>{let c=!!ht();jt.setAttribute("aria-label",ht()||"Jump to latest"),jt.title=ht(),jt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Bn.innerHTML="";let m=me(Lt(),"14px","currentColor",2);m?(Bn.appendChild(m),Bn.style.display=""):Bn.style.display="none",Gn.textContent=ht(),Gn.style.display=c?"":"none"};Xr();let wt=null,xr=null,vr=o.find(c=>c.renderHeader);if(vr!=null&&vr.renderHeader){let c=vr.renderHeader({config:r,defaultRenderer:()=>{let m=xo({config:r,showClose:O()});return ws(Ae,m,r),m.header},onClose:()=>Ut(!1,"user")});if(c){let m=Ae.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Pe=c,Xe.header.element=c)}}let Dr=()=>{var m,h,b,S;if(!V)return;if(K=!0,!We&&V&&(We=yg({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>lr(),config:r,plugins:o,getThroughput:()=>{var B;return(B=X==null?void 0:X.getMetric())!=null?B:{status:"idle"}}})),We&&(Me.style.display="none",(m=Ne.parentNode)==null||m.insertBefore(We.element,Ne),We.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let B=(S=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;B&&B.split(/\s+/).forEach(q=>q&&ut.classList.add(q))}let c=()=>{if(!K)return;let B=Date.now();B-$e>=200&&(We==null||We.update(),$e=B),pe=requestAnimationFrame(c)};$e=0,pe=requestAnimationFrame(c),st(),i.emit("eventStream:opened",{timestamp:Date.now()})},lr=()=>{var c,m,h;if(K){if(K=!1,We&&We.element.remove(),Me.style.display="",ut){ut.style.boxShadow="";let b=(h=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(S=>S&&ut.classList.remove(S))}pe!==null&&(cancelAnimationFrame(pe),pe=null),st(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(re){let c=(Yc=(Qc=r.features)==null?void 0:Qc.eventStream)==null?void 0:Yc.classNames,m="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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=y("button",m),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=me("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let b=qe.clearChatButtonWrapper,S=qe.closeButtonWrapper,B=b||S;B&&B.parentNode===Pe?Pe.insertBefore(ut,B):Pe.appendChild(ut),ut.addEventListener("click",()=>{K?lr():Dr()})}let Co=c=>{var S,B,q,_,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(S=c.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:c.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ae=c.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):c.insertBefore(h,c.firstChild)}if(!((B=c.querySelector("[data-persona-composer-attachment-input]"))!=null?B:c.querySelector('input[type="file"]'))){let ae=y("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=((q=m.allowedTypes)!=null?q:Kr).join(","),ae.multiple=((_=m.maxFiles)!=null?_:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(ae)}},wr=o.find(c=>c.renderComposer);if(wr!=null&&wr.renderComposer){let c=r.composer,m=wr.renderComposer({config:r,defaultRenderer:()=>ma({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;ec();let B;S&&(B=[],B.push(...wt.getContentParts()),b&&B.push(ja(b))),$.sendMessage(b,{contentParts:B}),S&&wt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Zc=r.voiceRecognition)==null?void 0:Zc.enabled)===!0?()=>{xr==null||xr()}:void 0});m&&(Xe.replaceComposer(m),Ne=Xe.composer.footer)}let Ao=c=>{let m=(...ie)=>{for(let Q of ie){let ve=c.querySelector(Q);if(ve)return ve}return null},h=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),S=c.querySelector("[data-persona-composer-submit]"),B=c.querySelector("[data-persona-composer-mic]"),q=c.querySelector("[data-persona-composer-status]");h&&(xt=h),b&&(ee=b),S&&(je=S),B&&(H=B,he=B.parentElement),q&&(hn=q);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Pt=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(Fe=D,vt=D.parentElement),Ye=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ht=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Ge=ae)};Co(Ne),Ao(Ne);let Ln=(od=(ed=r.layout)==null?void 0:ed.contentMaxWidth)!=null?od:W()?(rd=(nd=(td=r.launcher)==null?void 0:td.composerBar)==null?void 0:nd.contentMaxWidth)!=null?rd:"720px":void 0;if(Ln&&(nt.style.maxWidth=Ln,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),Ln&&xt&&!W()&&(xt.style.maxWidth=Ln,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Ln&&Pt&&!W()&&(Pt.style.maxWidth=Ln,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Ln&&Ht&&!W()&&(Ht.style.maxWidth=Ln,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),(sd=r.attachments)!=null&&sd.enabled&&Ye&&Ht){wt=xs.fromConfig(r.attachments),wt.setPreviewsContainer(Ht),Ye.addEventListener("change",h=>{let b=h.target;wt==null||wt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=Rg(c);Ae.appendChild(m)}(()=>{var b,S;let c=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},m=B=>{switch(B){case"body-top":return Ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return Pt;case"composer":return xt;case"footer-bottom":return hn;default:return null}},h=(B,q)=>{var _;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")Pe.insertBefore(q,Pe.firstChild);else if(B==="header-right")Pe.appendChild(q);else{let D=Pe.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(q,D.nextSibling):Pe.appendChild(q)}break;case"body-top":{let D=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(q):Me.insertBefore(q,Me.firstChild);break}case"body-bottom":Me.appendChild(q);break;case"footer-top":Pt.replaceWith(q);break;case"footer-bottom":hn.replaceWith(q);break;default:break}};for(let[B,q]of Object.entries(c))if(q)try{let _=q({config:r,defaultContent:()=>m(B)});_&&h(B,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,_)}})();let Qr=c=>{var q,_;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-bubble-type");if(B==="reasoning")As.has(S)?As.delete(S):As.add(S),rg(S,b);else if(B==="tool")Ss.has(S)?Ss.delete(S):Ss.add(S),og(S,b,r);else if(B==="approval"){let D=r.approval!==!1?r.approval:void 0,ae=((q=D==null?void 0:D.detailsDisplay)!=null?q:"collapsed")==="expanded",ie=(_=Ko.get(S))!=null?_:ae;Ko.set(S,!ie),lg(S,b,r)}Er.delete(S)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qr(c))}),nt.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qr(c))}),nt.addEventListener("copy",c=>{let{clipboardData:m}=c;if(!m)return;let h=nt.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),B=Rm(S);!B||B===S||(m.setData("text/plain",B),c.preventDefault())});let Nr=new Map,Yr=null,Zr="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(c,m)=>{let{icon:h,label:b}=So[m];c.setAttribute("aria-label",b),c.title=b,c.setAttribute("aria-pressed",m==="idle"?"false":"true"),c.classList.toggle("persona-message-action-active",m!=="idle"),c.classList.toggle("persona-message-action-loading",m==="loading");let S=me(h,14,"currentColor",2);S&&(c.innerHTML="",c.appendChild(S))},eo=()=>{nt.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var B;let h=m.closest("[data-actions-for]"),b=(B=h==null?void 0:h.getAttribute("data-actions-for"))!=null?B:null;To(m,b&&b===Yr?Zr:"idle")})};nt.addEventListener("click",c=>{var q;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let B=h.getAttribute("data-action");if(B==="copy"){let D=$.getMessages().find(ae=>ae.id===S);if(D&&ge.onCopy){let ae=D.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let ie=me("check",14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=me("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(ie=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ie)}),ge.onCopy(D)}}else if(B==="read-aloud")$.toggleReadAloud(S);else if(B==="upvote"||B==="downvote"){let D=((q=Nr.get(S))!=null?q:null)===B,ae=B==="upvote"?"thumbs-up":"thumbs-down";if(D){Nr.delete(S),h.classList.remove("persona-message-action-active");let ie=me(ae,14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie))}else{let ie=B==="upvote"?"downvote":"upvote",Q=b.querySelector(`[data-action="${ie}"]`);if(Q){Q.classList.remove("persona-message-action-active");let Ue=me(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(Q.innerHTML="",Q.appendChild(Ue))}Nr.set(S,B),h.classList.add("persona-message-action-active");let ve=me(ae,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 Se=$.getMessages().find(Ze=>Ze.id===S);Se&&ge.onFeedback&&ge.onFeedback({type:B,messageId:Se.id,message:Se})}}}),nt.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-approval-action");if(!B)return;let q=B==="approve"?"approved":"denied",D=$.getMessages().find(ie=>ie.id===S);if(!(D!=null&&D.approval))return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Q=>{Q.disabled=!0,Q.style.opacity="0.5",Q.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?$.resolveWebMcpApproval(S,q):$.resolveApproval(D.approval,q)});let bt=null,Dn=null,Nn={artifacts:[],selectedId:null},An=!1,Ct={current:null};nt.addEventListener("click",c=>{var Q,ve,Oe,Se,Ze;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Oe=(ve=(Q=r.features)==null?void 0:Q.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Oe.call(ve,{type:"download",artifactId:b}))===!0)return;let B=$.getArtifactById(b),q=B==null?void 0:B.markdown,_=(B==null?void 0:B.title)||"artifact";if(!q){let Ue=h.closest("[data-open-artifact]"),ct=Ue==null?void 0:Ue.closest("[data-message-id]"),rt=ct==null?void 0:ct.getAttribute("data-message-id");if(rt){let Le=$.getMessages().find(ze=>ze.id===rt);if(Le!=null&&Le.rawContent)try{let ze=JSON.parse(Le.rawContent);q=(Se=ze==null?void 0:ze.props)==null?void 0:Se.markdown,_=((Ze=ze==null?void 0:ze.props)==null?void 0:Ze.title)||_}catch{}}}if(!q)return;let D=new Blob([q],{type:"text/markdown"}),ae=URL.createObjectURL(D),ie=document.createElement("a");ie.href=ae,ie.download=`${_}.md`,ie.click(),URL.revokeObjectURL(ae)}),nt.addEventListener("click",c=>{var B,q,_;let h=c.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(q=(B=r.features)==null?void 0:B.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:_.call(q,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),An=!1,$.selectArtifact(b),Pn())}),nt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let Xn=qe.composerOverlay,Qn=(c,m,h)=>{var _,D,ae,ie;let b=m.trim();if(!b||!Ct.current)return;let S=(_=c.getAttribute("data-tool-call-id"))!=null?_:"",B=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?b.split(", "):[b],isFreeText:B,source:h.source},bubbles:!0,composed:!0})),_o(Xn,S);let q=Ct.current.getMessages().find(Q=>{var ve;return((ve=Q.toolCall)==null?void 0:ve.id)===S});(ae=q==null?void 0:q.agentMetadata)!=null&&ae.awaitingLocalTool?Ct.current.resolveAskUserQuestion(q,(ie=h.structured)!=null?ie:b):Ct.current.sendMessage(b)},On=c=>{var S;let m=Ct.current;if(!m)return;let h=(S=c.getAttribute("data-tool-call-id"))!=null?S:"",b=m.getMessages().find(B=>{var q;return((q=B.toolCall)==null?void 0:q.id)===h});b&&m.persistAskUserQuestionProgress(b,{answers:Ra(c,b),currentIndex:or(c)})},to=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Or=c=>{var S,B,q;if(((B=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let m=or(c),h=gs(c);if(m>=h-1)return;let b=(q=Ct.current)==null?void 0:q.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});b&&(Wa(c,b,r,m+1),On(c))};Xn.addEventListener("click",c=>{var B,q,_,D,ae,ie,Q,ve,Oe,Se,Ze,Ue,ct,rt;let h=c.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(c.preventDefault(),c.stopPropagation(),S==="dismiss"){let Ie=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),_o(Xn,Ie);let Le=(q=Ct.current)==null?void 0:q.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Ie});(_=Le==null?void 0:Le.agentMetadata)!=null&&_.awaitingLocalTool&&((D=Ct.current)==null||D.markAskUserQuestionResolved(Le),(ae=Ct.current)==null||ae.resolveAskUserQuestion(Le,"(dismissed)"));return}if(S==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Le=b.getAttribute("data-multi-select")==="true",ze=mo(b);if(ze&&Le){let Ke=Fo(b)[or(b)],ft=new Set(Array.isArray(Ke)?Ke:[]);ft.has(Ie)?ft.delete(Ie):ft.add(Ie),go(b,Array.from(ft)),On(b);return}if(ze){go(b,Ie),On(b),Or(b);return}if(Le){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let ft=b.querySelector('[data-ask-user-action="submit-multi"]');ft&&(ft.disabled=zi(b).length===0);return}Qn(b,Ie,{source:"pick",values:[Ie]});return}if(S==="submit-multi"){let Ie=zi(b);if(Ie.length===0)return;Qn(b,Ie.join(", "),{source:"multi",values:Ie});return}if(S==="open-free-text"){let Ie=b.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(S==="focus-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(S==="submit-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]'),Le=(ie=Ie==null?void 0:Ie.value)!=null?ie:"";if(!Le.trim())return;if(mo(b)){go(b,Le.trim()),On(b),Or(b);return}Qn(b,Le,{source:"free-text"});return}if(S==="next"||S==="back"){if(!Ct.current)return;let Ie=(Q=b.getAttribute("data-tool-call-id"))!=null?Q:"",Le=Ct.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Oe=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?Oe:"";if(Ke){let Be=Fo(b)[or(b)];(typeof Be!="string"||Be!==Ke)&&go(b,Ke)}let ft=S==="next"?1:-1,I=or(b)+ft;Wa(b,Le,r,I),On(b);return}if(S==="submit-all"){if(!Ct.current)return;let Ie=(Se=b.getAttribute("data-tool-call-id"))!=null?Se:"",Le=Ct.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ue=(Ze=ze==null?void 0:ze.value)==null?void 0:Ze.trim())!=null?Ue:"";Ke&&go(b,Ke);let ft=Ra(b,Le);Ct.current.persistAskUserQuestionProgress(Le,{answers:ft,currentIndex:or(b)});let I=to(ft);Qn(b,I||"(submitted)",{source:"submit-all",structured:ft});return}if(S==="skip"){if(!Ct.current)return;let Ie=(ct=b.getAttribute("data-tool-call-id"))!=null?ct:"",Le=Ct.current.getMessages().find(Re=>{var ue;return((ue=Re.toolCall)==null?void 0:ue.id)===Ie});if(!Le)return;let ze=mo(b),Ke=or(b),ft=gs(b),I=Ke>=ft-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),_o(Xn,Ie),(rt=Le.agentMetadata)!=null&&rt.awaitingLocalTool&&(Ct.current.markAskUserQuestionResolved(Le),Ct.current.resolveAskUserQuestion(Le,"(dismissed)"));return}go(b,"");let Be=b.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),I){let Re=Ra(b,Le),ue=to(Re);Qn(b,ue||"(skipped)",{source:"submit-all",structured:Re});return}Wa(b,Le,r,Ke+1),On(b);return}}),Xn.addEventListener("keydown",c=>{var B;if(c.key!=="Enter")return;let h=c.target;if(!((B=h.matches)!=null&&B.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let S=h.value;if(S.trim()){if(mo(b)){go(b,S.trim()),On(b),Or(b);return}Qn(b,S,{source:"free-text"})}});let no=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Xn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),B=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];B&&(c.preventDefault(),B.click())};document.addEventListener("keydown",no);let Fn=null,Rt=null,Sn=null,Yn=null,ro=()=>{};function Fr(){Yn==null||Yn(),Yn=null}let oo=()=>{var q;if(!Fn||!Rt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((q=e.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Rt.style.removeProperty("position"),Rt.style.removeProperty("left"),Rt.style.removeProperty("top"),Rt.style.removeProperty("bottom"),Rt.style.removeProperty("width"),Rt.style.removeProperty("z-index");return}let b=Fn.firstElementChild;if(!b||b===Rt)return;let S=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${S}px`,Rt.style.zIndex="5";let B=b.offsetWidth-S/2;Rt.style.left=`${Math.max(0,B)}px`},xe=()=>{},Pn=()=>{var h,b,S,B,q;if(!bt||!ir(r))return;hi(e,r),yi(e,r),xe();let c=(B=(S=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?B:520,m=J.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),bt.update(Nn),An?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(q=bt.backdrop)==null||q.classList.add("persona-hidden")):Nn.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),ro()};if(ir(r)){J.style.position="relative";let c=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(Ae),bt=vg(r,{onSelect:h=>{var b;return(b=Ct.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{An=!0,Pn()}}),bt.element.classList.add("persona-hidden"),Fn=m,m.appendChild(c),m.appendChild(bt.element),bt.backdrop&&J.appendChild(bt.backdrop),J.appendChild(m),ro=()=>{var b,S,B,q;if(!Fn||!bt)return;if(!(((B=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:B.resizable)===!0)){Sn==null||Sn(),Sn=null,Fr(),Rt&&(Rt.remove(),Rt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Rt){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let D=e.ownerDocument,ae=(q=D.defaultView)!=null?q:window,ie=Q=>{var ct,rt;if(!bt||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Q.preventDefault(),Fr();let ve=Q.clientX,Oe=bt.element.getBoundingClientRect().width,Se=(rt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:rt.layout,Ze=Ie=>{let Le=Fn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Sg(Fn,ae),ft=ze?0:_.getBoundingClientRect().width||6,I=Oe-(Ie.clientX-ve),Be=Tg(I,Le,Ke,ft,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);bt.element.style.width=`${Be}px`,bt.element.style.maxWidth="none",oo()},Ue=()=>{D.removeEventListener("pointermove",Ze),D.removeEventListener("pointerup",Ue),D.removeEventListener("pointercancel",Ue),Yn=null;try{_.releasePointerCapture(Q.pointerId)}catch{}};Yn=Ue,D.addEventListener("pointermove",Ze),D.addEventListener("pointerup",Ue),D.addEventListener("pointercancel",Ue);try{_.setPointerCapture(Q.pointerId)}catch{}};_.addEventListener("pointerdown",ie),Rt=_,Fn.insertBefore(_,bt.element),Sn=()=>{_.removeEventListener("pointerdown",ie)}}if(Rt){let _=Nn.artifacts.length>0&&!An;Rt.classList.toggle("persona-hidden",!_),oo()}},xe=()=>{var ae,ie,Q,ve,Oe,Se,Ze,Ue,ct,rt,Ie,Le,ze,Ke;if(!k||!bt||((ie=(ae=r.launcher)==null?void 0:ae.sidebarMode)!=null?ie:!1)||cn(r)&&ar(r).reveal==="emerge")return;let b=(Q=e.ownerDocument.defaultView)!=null?Q:window,S=(Oe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Oe:!0,B=(Ze=(Se=r.launcher)==null?void 0:Se.mobileBreakpoint)!=null?Ze:640;if(S&&b.innerWidth<=B||!Ag(r,k))return;let q=(rt=(ct=(Ue=r.launcher)==null?void 0:Ue.width)!=null?ct:r.launcherWidth)!=null?rt:sr,_=(Ke=(ze=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!An?(J.style.width=_,J.style.maxWidth=_):(J.style.width=q,J.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{Pn()}),Dn.observe(J))}else J.appendChild(Ae),W()&&dt&&(qe.peekBanner&&dt.appendChild(qe.peekBanner),dt.appendChild(Ne));e.appendChild(fe),dt&&e.appendChild(dt);let Cr=()=>{var Be,Re,ue,Bt,Wt,Kt,yt,qt,Un,en,Je,Et,nn,nr,qn,Io,Ro,ls,cs,Jt,Wo,io,lo,zr,Ho,ur,Pr,Qe;if(W()){J.style.width="100%",J.style.maxWidth="100%";let Dt=(Re=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?Re:{},Vt=fe.dataset.state==="expanded",Nt=(ue=Dt.expandedSize)!=null?ue:"anchored";if(!(Vt&&Nt!=="fullscreen")){Ae.style.background="",Ae.style.border="",Ae.style.borderRadius="",Ae.style.overflow="",Ae.style.boxShadow="";return}let Mt=(Wt=(Bt=r.theme)==null?void 0:Bt.components)==null?void 0:Wt.panel,_t=oa(r),un=(gn,rr)=>{var co;return gn==null||gn===""?rr:(co=vs(_t,gn))!=null?co:gn},zn="1px solid var(--persona-border)",Ir="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ae.style.background="var(--persona-surface, #ffffff)",Ae.style.border=un(Mt==null?void 0:Mt.border,zn),Ae.style.borderRadius=un(Mt==null?void 0:Mt.borderRadius,mn),Ae.style.boxShadow=un(Mt==null?void 0:Mt.shadow,Ir),Ae.style.overflow="hidden";return}let c=cn(r),m=(yt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?yt:!1,h=c||m||((Un=(qt=r.launcher)==null?void 0:qt.fullHeight)!=null?Un:!1),b=((en=r.launcher)==null?void 0:en.enabled)===!1,S=(Et=(Je=r.theme)==null?void 0:Je.components)==null?void 0:Et.panel,B=oa(r),q=(Dt,Vt)=>{var Nt;return Dt==null||Dt===""?Vt:(Nt=vs(B,Dt))!=null?Nt:Dt},_=(nn=e.ownerDocument.defaultView)!=null?nn:window,D=(qn=(nr=r.launcher)==null?void 0:nr.mobileFullscreen)!=null?qn:!0,ae=(Ro=(Io=r.launcher)==null?void 0:Io.mobileBreakpoint)!=null?Ro:640,ie=_.innerWidth<=ae,Q=D&&ie&&k,ve=(cs=(ls=r.launcher)==null?void 0:ls.position)!=null?cs:"bottom-left",Oe=ve==="bottom-left"||ve==="top-left",Se=(Wo=(Jt=r.launcher)==null?void 0:Jt.zIndex)!=null?Wo:wn,Ze=m||Q?"none":"1px solid var(--persona-border)",Ue=Q?"none":m?Oe?"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))";c&&!Q&&(Ue="none",Ze="none");let ct=m||Q?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=q(S==null?void 0:S.border,Ze),Ie=q(S==null?void 0:S.shadow,Ue),Le=q(S==null?void 0:S.borderRadius,ct),ze=Me.scrollTop;e.style.cssText="",fe.style.cssText="",J.style.cssText="",Ae.style.cssText="",Me.style.cssText="",Ne.style.cssText="",K&&(Me.style.display="none");let Ke=()=>{var Vt;if(ze<=0)return;((Vt=Me.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(Me.scrollTop===ze)return;let Nt=Me.scrollHeight-Me.clientHeight;Nt<=0||(Me.scrollTop=Math.min(ze,Nt))})};if(Q){fe.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"),fe.style.cssText=`
34
+ `,R.addEventListener("click",()=>{u=C,T.forEach((F,j)=>{let H=j<C;F.classList.toggle("selected",H),F.setAttribute("aria-checked",j===C-1?"true":"false")})}),T.push(R),E.appendChild(R)}g.appendChild(E);let L=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),C.appendChild(L),g.appendChild(C)}let k=document.createElement("div");k.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{n==null||n(),p.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let C=(L==null?void 0:L.value.trim())||void 0;await t(u,C),p.remove()}catch(C){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),k.appendChild(M),k.appendChild(P),g.appendChild(k),p.appendChild(g),p}function ql(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.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 E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,v.appendChild(E),f.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=p,L.appendChild(k),L.appendChild(M);let P=document.createElement("div");P.className="persona-feedback-numbers";let C=[];for(let O=0;O<=10;O++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${O} out of 10`),N.textContent=String(O),N.dataset.rating=String(O),O<=6?N.classList.add("persona-feedback-detractor"):O<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{g=O,C.forEach((Y,ke)=>{Y.classList.toggle("selected",ke===O),Y.setAttribute("aria-checked",ke===O?"true":"false")})}),C.push(N),P.appendChild(N)}T.appendChild(L),T.appendChild(P),f.appendChild(T);let R=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),O.appendChild(R),f.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=i,j.addEventListener("click",()=>{n==null||n(),u.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let O=(R==null?void 0:R.value.trim())||void 0;await t(g,O),u.remove()}catch(O){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),F.appendChild(j),F.appendChild(H),f.appendChild(F),u.appendChild(f),u}var Ws="persona-chat-history",hw=30*1e3,yw={"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 bw(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=yw[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=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Ei(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function xw(e){var t,n,r,o,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function vw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var zl=e=>!e||typeof e!="object"?{}:{...e},zg=e=>e.map(t=>({...t,streaming:!1})),Vg=(e,t,n)=>{let r=e!=null&&e.markdown?bs(e.markdown):null,o=Js(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var p,u,g;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d=Vo()!==null,l;if(e!=null&&e.postprocessMessage){let f=e.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});l=o?o(f):f}else if(r){let f=s.streaming?Ku(a):a,v=r(f);l=o&&d?o(v):v}else l=Yr(a);return l}};function Kg(e){var i,d,l,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ge(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Vl=(e,t,n)=>{var Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Gc,Jc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=ml(t),o=Ai.getForInstance(r.plugins),{plugin:s,teardown:a}=Mg();r.components&&Lo.registerAll(r.components);let i=jg(),l=r.persistState===!1?null:(Oc=r.storageAdapter)!=null?Oc:Ol(),p={},u=null,g=!1,f=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:b}=m;return b&&(g=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(l!=null&&l.load)try{let c=l.load();if(c&&typeof c.then=="function")u=c.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return f(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=f(m);h.metadata&&(p=zl(h.metadata)),(Fc=h.messages)!=null&&Fc.length&&(r={...r,initialMessages:h.messages}),(_c=h.artifacts)!=null&&_c.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:($c=h.selectedArtifactId)!=null?$c:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=f({messages:[],metadata:{}});(jc=c.messages)!=null&&jc.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let v=()=>p,x=c=>{var h;p=(h=c({...p}))!=null?h:{},sn()},E=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Si],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Rs.message,Rs.messageAndClick],L=Ti({parsers:E,handlers:T,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let k=(qc=(Uc=r.launcher)==null?void 0:Uc.enabled)!=null?qc:!0,M=(Vc=(zc=r.launcher)==null?void 0:zc.autoExpand)!=null?Vc:!1,P=(Kc=r.autoFocusInput)!=null?Kc:!1,C=M,R=k,F=(Jc=(Gc=r.layout)==null?void 0:Gc.header)==null?void 0:Jc.layout,j=!1,H=()=>Mo(r),O=()=>k||H(),N=H()?!1:k?M:!0,Y=!1,ke=null,pe=()=>{Y=!0,ke&&clearTimeout(ke),ke=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},Z=Vg(r,L,pe),Te=(Qc=(Xc=r.features)==null?void 0:Xc.showReasoning)!=null?Qc:!0,Le=(Zc=(Yc=r.features)==null?void 0:Yc.showToolCalls)!=null?Zc:!0,oe=(td=(ed=r.features)==null?void 0:ed.showEventStreamToggle)!=null?td:!1,Ae=(rd=(nd=r.features)==null?void 0:nd.scrollToBottom)!=null?rd:{},se=(sd=(od=r.features)==null?void 0:od.scrollBehavior)!=null?sd:{},ae=`${(id=typeof r.persistState=="object"?(ad=r.persistState)==null?void 0:ad.keyPrefix:void 0)!=null?id:"persona-"}event-stream`,xe=oe?new Sa(ae):null,Be=(dd=(cd=(ld=r.features)==null?void 0:ld.eventStream)==null?void 0:cd.maxEvents)!=null?dd:2e3,V=oe?new Aa(Be,xe):null,X=oe?new Ta:null,He=null,K=!1,ue=null,$e=0;xe==null||xe.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let fe={onCopy:c=>{var m,h;i.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,c)},onFeedback:c=>{var m,h;i.emit("message:feedback",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,c)}},Ve=(pd=r.statusIndicator)!=null?pd:{},et=c=>{var m,h,b,S;return c==="idle"?(m=Ve.idleText)!=null?m:xn.idle:c==="connecting"?(h=Ve.connectingText)!=null?h:xn.connecting:c==="connected"?(b=Ve.connectedText)!=null?b:xn.connected:c==="error"?(S=Ve.errorText)!=null?S:xn.error:xn[c]};function Ot(c,m,h,b){if(b==="idle"&&h.idleLink){c.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=m,S.style.color="inherit",S.style.textDecoration="none",c.appendChild(S)}else c.textContent=m}let Xe=mg({config:r,showClose:O()}),{wrapper:ye,panel:J,pillRoot:dt}=Xe.shell,qe=Xe.panelElements,{container:Se,body:ve,messagesWrapper:nt,suggestions:Lt,textarea:ee,sendButton:je,sendButtonWrapper:wn,composerForm:bt,statusText:fn,introTitle:xr,introSubtitle:vr,closeButton:A,iconHolder:te,headerTitle:Me,headerSubtitle:Ne,header:Ie,footer:Oe,actionsRow:Ge,leftActions:at,rightActions:Pt}=qe,ce=qe.setSendButtonMode,B=qe.micButton,be=qe.micButtonWrapper,_e=qe.attachmentButton,xt=qe.attachmentButtonWrapper,Ye=qe.attachmentInput,Rt=qe.attachmentPreviewsContainer;Se.classList.add("persona-relative"),ve.classList.add("persona-relative");let St=12,ht=()=>{var c;return(c=Ae.label)!=null?c:""},kt=()=>{var c;return(c=Ae.iconName)!=null?c:"arrow-down"},Xt=()=>Ae.enabled!==!1,Ft=()=>{var c;return(c=se.mode)!=null?c:"anchor-top"},en=()=>Ft()==="follow"||Ft()==="anchor-top"&&Rr,wr=()=>{var c;return(c=se.anchorTopOffset)!=null?c:16},$r=()=>{var c;return(c=se.restorePosition)!=null?c:"bottom"},sr=()=>se.pauseOnInteraction===!0,ar=()=>se.showActivityWhilePinned!==!1,to=()=>se.announce===!0,qt=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");qt.type="button",qt.style.display="none",qt.setAttribute("data-persona-scroll-to-bottom","true");let ir=y("span","persona-flex persona-items-center"),jr=y("span",""),In=y("span","");In.setAttribute("data-persona-scroll-to-bottom-count",""),In.style.display="none",qt.append(ir,jr,In),Se.appendChild(qt);let kn=y("div","persona-stream-anchor-spacer");kn.setAttribute("aria-hidden","true"),kn.setAttribute("data-persona-anchor-spacer",""),kn.style.flexShrink="0",kn.style.pointerEvents="none",kn.style.height="0px",ve.appendChild(kn);let Rn=y("div","persona-sr-only");Rn.setAttribute("aria-live","polite"),Rn.setAttribute("aria-atomic","true"),Rn.setAttribute("role","status"),Rn.setAttribute("data-persona-live-region",""),Object.assign(Rn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Se.appendChild(Rn);let lr=null,Cr=null,no=c=>{!to()||!c||(Cr=c,lr===null&&(lr=setTimeout(()=>{lr=null,Cr&&to()&&(Rn.textContent=Cr),Cr=null},400)))},qn=()=>{let m=Oe.style.display==="none"?0:Oe.offsetHeight;qt.style.bottom=`${m+St}px`};qn();let ro=()=>{let c=!!ht();qt.setAttribute("aria-label",ht()||"Jump to latest"),qt.title=ht(),qt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),ir.innerHTML="";let m=ge(kt(),"14px","currentColor",2);m?(ir.appendChild(m),ir.style.display=""):ir.style.display="none",jr.textContent=ht(),jr.style.display=c?"":"none"};ro();let vt=null,Ar=null,Sr=o.find(c=>c.renderHeader);if(Sr!=null&&Sr.renderHeader){let c=Sr.renderHeader({config:r,defaultRenderer:()=>{let m=ko({config:r,showClose:O()});return Ms(Se,m,r),m.header},onClose:()=>$t(!1,"user")});if(c){let m=Se.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Ie=c,Xe.header.element=c)}}let Ur=()=>{var m,h,b,S;if(!V)return;if(K=!0,!He&&V&&(He=Rg({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>cr(),config:r,plugins:o,getThroughput:()=>{var W;return(W=X==null?void 0:X.getMetric())!=null?W:{status:"idle"}}})),He&&(ve.style.display="none",(m=Oe.parentNode)==null||m.insertBefore(He.element,Oe),He.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let W=(S=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;W&&W.split(/\s+/).forEach(q=>q&&ut.classList.add(q))}let c=()=>{if(!K)return;let W=Date.now();W-$e>=200&&(He==null||He.update(),$e=W),ue=requestAnimationFrame(c)};$e=0,ue=requestAnimationFrame(c),On(),i.emit("eventStream:opened",{timestamp:Date.now()})},cr=()=>{var c,m,h;if(K){if(K=!1,He&&He.element.remove(),ve.style.display="",ut){ut.style.boxShadow="";let b=(h=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(S=>S&&ut.classList.remove(S))}ue!==null&&(cancelAnimationFrame(ue),ue=null),On(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(oe){let c=(md=(ud=r.features)==null?void 0:ud.eventStream)==null?void 0:md.classNames,m="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"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=y("button",m),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=ge("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let b=qe.clearChatButtonWrapper,S=qe.closeButtonWrapper,W=b||S;W&&W.parentNode===Ie?Ie.insertBefore(ut,W):Ie.appendChild(ut),ut.addEventListener("click",()=>{K?cr():Ur()})}let Io=c=>{var S,W,q,_,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(S=c.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:c.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 de=c.querySelector("[data-persona-composer-form]");de!=null&&de.parentNode?de.parentNode.insertBefore(h,de):c.insertBefore(h,c.firstChild)}if(!((W=c.querySelector("[data-persona-composer-attachment-input]"))!=null?W:c.querySelector('input[type="file"]'))){let de=y("input");de.type="file",de.setAttribute("data-persona-composer-attachment-input",""),de.accept=((q=m.allowedTypes)!=null?q:Zr).join(","),de.multiple=((_=m.maxFiles)!=null?_:4)>1,de.style.display="none",de.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(de)}},Tr=o.find(c=>c.renderComposer);if(Tr!=null&&Tr.renderComposer){let c=r.composer,m=Tr.renderComposer({config:r,defaultRenderer:()=>wa({config:r}).footer,onSubmit:h=>{var q;if(!$||$.isStreaming())return;let b=h.trim(),S=(q=vt==null?void 0:vt.hasAttachments())!=null?q:!1;if(!b&&!S)return;mc();let W;S&&(W=[],W.push(...vt.getContentParts()),b&&W.push(Ka(b))),$.sendMessage(b,{contentParts:W}),S&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((gd=r.voiceRecognition)==null?void 0:gd.enabled)===!0?()=>{Ar==null||Ar()}:void 0});m&&(Xe.replaceComposer(m),Oe=Xe.composer.footer)}let Ro=c=>{let m=(...le)=>{for(let Q of le){let we=c.querySelector(Q);if(we)return we}return null},h=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),S=c.querySelector("[data-persona-composer-submit]"),W=c.querySelector("[data-persona-composer-mic]"),q=c.querySelector("[data-persona-composer-status]");h&&(bt=h),b&&(ee=b),S&&(je=S),W&&(B=W,be=W.parentElement),q&&(fn=q);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Lt=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(_e=D,xt=D.parentElement),Ye=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Rt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let de=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");de&&(Ge=de)};Io(Oe),Ro(Oe);let Ln=(xd=(fd=r.layout)==null?void 0:fd.contentMaxWidth)!=null?xd:H()?(bd=(yd=(hd=r.launcher)==null?void 0:hd.composerBar)==null?void 0:yd.contentMaxWidth)!=null?bd:"720px":void 0;if(Ln&&(nt.style.maxWidth=Ln,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),Ln&&bt&&!H()&&(bt.style.maxWidth=Ln,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Ln&&Lt&&!H()&&(Lt.style.maxWidth=Ln,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),Ln&&Rt&&!H()&&(Rt.style.maxWidth=Ln,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),(vd=r.attachments)!=null&&vd.enabled&&Ye&&Rt){vt=Ts.fromConfig(r.attachments),vt.setPreviewsContainer(Rt),Ye.addEventListener("change",h=>{let b=h.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=Kg(c);Se.appendChild(m)}(()=>{var b,S;let c=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},m=W=>{switch(W){case"body-top":return Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return Lt;case"composer":return bt;case"footer-bottom":return fn;default:return null}},h=(W,q)=>{var _;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ie.insertBefore(q,Ie.firstChild);else if(W==="header-right")Ie.appendChild(q);else{let D=Ie.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(q,D.nextSibling):Ie.appendChild(q)}break;case"body-top":{let D=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(q):ve.insertBefore(q,ve.firstChild);break}case"body-bottom":ve.appendChild(q);break;case"footer-top":Lt.replaceWith(q);break;case"footer-bottom":fn.replaceWith(q);break;default:break}};for(let[W,q]of Object.entries(c))if(q)try{let _=q({config:r,defaultContent:()=>m(W)});_&&h(W,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,_)}})();let oo=c=>{var q,_;let h=c.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 W=h.getAttribute("data-bubble-type");if(W==="reasoning")Ls.has(S)?Ls.delete(S):Ls.add(S),bg(S,b);else if(W==="tool")Ps.has(S)?Ps.delete(S):Ps.add(S),xg(S,b,r);else if(W==="approval"){let D=r.approval!==!1?r.approval:void 0,de=((q=D==null?void 0:D.detailsDisplay)!=null?q:"collapsed")==="expanded",le=(_=ts.get(S))!=null?_:de;ts.set(S,!le),Ag(S,b,r)}Lr.delete(S)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),oo(c))}),nt.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),oo(c))}),nt.addEventListener("copy",c=>{let{clipboardData:m}=c;if(!m)return;let h=nt.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),W=Km(S);!W||W===S||(m.setData("text/plain",W),c.preventDefault())});let qr=new Map,so=null,ao="idle",Wo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ho=(c,m)=>{let{icon:h,label:b}=Wo[m];c.setAttribute("aria-label",b),c.title=b,c.setAttribute("aria-pressed",m==="idle"?"false":"true"),c.classList.toggle("persona-message-action-active",m!=="idle"),c.classList.toggle("persona-message-action-loading",m==="loading");let S=ge(h,14,"currentColor",2);S&&(c.innerHTML="",c.appendChild(S))},io=()=>{nt.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var W;let h=m.closest("[data-actions-for]"),b=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;Ho(m,b&&b===so?ao:"idle")})};nt.addEventListener("click",c=>{var q;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let W=h.getAttribute("data-action");if(W==="copy"){let D=$.getMessages().find(de=>de.id===S);if(D&&fe.onCopy){let de=D.content||"";navigator.clipboard.writeText(de).then(()=>{h.classList.add("persona-message-action-success");let le=ge("check",14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=ge("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),fe.onCopy(D)}}else if(W==="read-aloud")$.toggleReadAloud(S);else if(W==="upvote"||W==="downvote"){let D=((q=qr.get(S))!=null?q:null)===W,de=W==="upvote"?"thumbs-up":"thumbs-down";if(D){qr.delete(S),h.classList.remove("persona-message-action-active");let le=ge(de,14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le))}else{let le=W==="upvote"?"downvote":"upvote",Q=b.querySelector(`[data-action="${le}"]`);if(Q){Q.classList.remove("persona-message-action-active");let Ue=ge(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(Q.innerHTML="",Q.appendChild(Ue))}qr.set(S,W),h.classList.add("persona-message-action-active");let we=ge(de,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(we)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ee=$.getMessages().find(Ze=>Ze.id===S);Ee&&fe.onFeedback&&fe.onFeedback({type:W,messageId:Ee.id,message:Ee})}}}),nt.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let W=h.getAttribute("data-approval-action");if(!W)return;let q=W==="approve"?"approved":"denied",D=$.getMessages().find(le=>le.id===S);if(!(D!=null&&D.approval))return;let de=b.querySelector("[data-approval-buttons]");de&&de.querySelectorAll("button").forEach(Q=>{Q.disabled=!0,Q.style.opacity="0.5",Q.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?$.resolveWebMcpApproval(S,q):$.resolveApproval(D.approval,q)});let yt=null,Wn=null,Hn={artifacts:[],selectedId:null},Cn=!1,wt={current:null};nt.addEventListener("click",c=>{var Q,we,Fe,Ee,Ze;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Fe=(we=(Q=r.features)==null?void 0:Q.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:b}))===!0)return;let W=$.getArtifactById(b),q=W==null?void 0:W.markdown,_=(W==null?void 0:W.title)||"artifact";if(!q){let Ue=h.closest("[data-open-artifact]"),ct=Ue==null?void 0:Ue.closest("[data-message-id]"),rt=ct==null?void 0:ct.getAttribute("data-message-id");if(rt){let Pe=$.getMessages().find(ze=>ze.id===rt);if(Pe!=null&&Pe.rawContent)try{let ze=JSON.parse(Pe.rawContent);q=(Ee=ze==null?void 0:ze.props)==null?void 0:Ee.markdown,_=((Ze=ze==null?void 0:ze.props)==null?void 0:Ze.title)||_}catch{}}}if(!q)return;let D=new Blob([q],{type:"text/markdown"}),de=URL.createObjectURL(D),le=document.createElement("a");le.href=de,le.download=`${_}.md`,le.click(),URL.revokeObjectURL(de)}),nt.addEventListener("click",c=>{var W,q,_;let h=c.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(q=(W=r.features)==null?void 0:W.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:_.call(q,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),Cn=!1,$.selectArtifact(b),Er())}),nt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let zn=qe.composerOverlay,Vn=(c,m,h)=>{var _,D,de,le;let b=m.trim();if(!b||!wt.current)return;let S=(_=c.getAttribute("data-tool-call-id"))!=null?_:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?b.split(", "):[b],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Jo(zn,S);let q=wt.current.getMessages().find(Q=>{var we;return((we=Q.toolCall)==null?void 0:we.id)===S});(de=q==null?void 0:q.agentMetadata)!=null&&de.awaitingLocalTool?wt.current.resolveAskUserQuestion(q,(le=h.structured)!=null?le:b):wt.current.sendMessage(b)},Bn=c=>{var S;let m=wt.current;if(!m)return;let h=(S=c.getAttribute("data-tool-call-id"))!=null?S:"",b=m.getMessages().find(W=>{var q;return((q=W.toolCall)==null?void 0:q.id)===h});b&&m.persistAskUserQuestionProgress(b,{answers:Na(c,b),currentIndex:tr(c)})},lo=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ce=c=>{var S,W,q;if(((W=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let m=tr(c),h=vs(c);if(m>=h-1)return;let b=(q=wt.current)==null?void 0:q.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});b&&(Oa(c,b,r,m+1),Bn(c))};zn.addEventListener("click",c=>{var W,q,_,D,de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt;let h=c.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(c.preventDefault(),c.stopPropagation(),S==="dismiss"){let Re=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Jo(zn,Re);let Pe=(q=wt.current)==null?void 0:q.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Re});(_=Pe==null?void 0:Pe.agentMetadata)!=null&&_.awaitingLocalTool&&((D=wt.current)==null||D.markAskUserQuestionResolved(Pe),(de=wt.current)==null||de.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(S==="pick"){let Re=h.getAttribute("data-option-label");if(!Re)return;let Pe=b.getAttribute("data-multi-select")==="true",ze=wo(b);if(ze&&Pe){let Ke=Go(b)[tr(b)],gt=new Set(Array.isArray(Ke)?Ke:[]);gt.has(Re)?gt.delete(Re):gt.add(Re),Co(b,Array.from(gt)),Bn(b);return}if(ze){Co(b,Re),Bn(b),Ce(b);return}if(Pe){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let gt=b.querySelector('[data-ask-user-action="submit-multi"]');gt&&(gt.disabled=Yi(b).length===0);return}Vn(b,Re,{source:"pick",values:[Re]});return}if(S==="submit-multi"){let Re=Yi(b);if(Re.length===0)return;Vn(b,Re.join(", "),{source:"multi",values:Re});return}if(S==="open-free-text"){let Re=b.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Pe=Re.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(S==="focus-free-text"){let Re=b.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(S==="submit-free-text"){let Re=b.querySelector('[data-ask-free-text-input="true"]'),Pe=(le=Re==null?void 0:Re.value)!=null?le:"";if(!Pe.trim())return;if(wo(b)){Co(b,Pe.trim()),Bn(b),Ce(b);return}Vn(b,Pe,{source:"free-text"});return}if(S==="next"||S==="back"){if(!wt.current)return;let Re=(Q=b.getAttribute("data-tool-call-id"))!=null?Q:"",Pe=wt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Re});if(!Pe)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Fe=(we=ze==null?void 0:ze.value)==null?void 0:we.trim())!=null?Fe:"";if(Ke){let De=Go(b)[tr(b)];(typeof De!="string"||De!==Ke)&&Co(b,Ke)}let gt=S==="next"?1:-1,I=tr(b)+gt;Oa(b,Pe,r,I),Bn(b);return}if(S==="submit-all"){if(!wt.current)return;let Re=(Ee=b.getAttribute("data-tool-call-id"))!=null?Ee:"",Pe=wt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Re});if(!Pe)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ue=(Ze=ze==null?void 0:ze.value)==null?void 0:Ze.trim())!=null?Ue:"";Ke&&Co(b,Ke);let gt=Na(b,Pe);wt.current.persistAskUserQuestionProgress(Pe,{answers:gt,currentIndex:tr(b)});let I=lo(gt);Vn(b,I||"(submitted)",{source:"submit-all",structured:gt});return}if(S==="skip"){if(!wt.current)return;let Re=(ct=b.getAttribute("data-tool-call-id"))!=null?ct:"",Pe=wt.current.getMessages().find(We=>{var me;return((me=We.toolCall)==null?void 0:me.id)===Re});if(!Pe)return;let ze=wo(b),Ke=tr(b),gt=vs(b),I=Ke>=gt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Jo(zn,Re),(rt=Pe.agentMetadata)!=null&&rt.awaitingLocalTool&&(wt.current.markAskUserQuestionResolved(Pe),wt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}Co(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),I){let We=Na(b,Pe),me=lo(We);Vn(b,me||"(skipped)",{source:"submit-all",structured:We});return}Oa(b,Pe,r,Ke+1),Bn(b);return}}),zn.addEventListener("keydown",c=>{var W;if(c.key!=="Enter")return;let h=c.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let S=h.value;if(S.trim()){if(wo(b)){Co(b,S.trim()),Bn(b),Ce(b);return}Vn(b,S,{source:"free-text"})}});let zr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=zn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),W=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];W&&(c.preventDefault(),W.click())};document.addEventListener("keydown",zr);let Kn=null,_t=null,Gn=null,Vr=null,Hs=()=>{};function ss(){Vr==null||Vr(),Vr=null}let Bs=()=>{var q;if(!Kn||!_t)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((q=e.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){_t.style.removeProperty("position"),_t.style.removeProperty("left"),_t.style.removeProperty("top"),_t.style.removeProperty("bottom"),_t.style.removeProperty("width"),_t.style.removeProperty("z-index");return}let b=Kn.firstElementChild;if(!b||b===_t)return;let S=10;_t.style.position="absolute",_t.style.top="0",_t.style.bottom="0",_t.style.width=`${S}px`,_t.style.zIndex="5";let W=b.offsetWidth-S/2;_t.style.left=`${Math.max(0,W)}px`},Bo=()=>{},Er=()=>{var h,b,S,W,q;if(!yt||!or(r))return;wi(e,r),Ci(e,r),Bo();let c=(W=(S=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?W:520,m=J.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),yt.update(Hn),Cn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(q=yt.backdrop)==null||q.classList.add("persona-hidden")):Hn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),Hs()};if(or(r)){J.style.position="relative";let c=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(Se),yt=Bg(r,{onSelect:h=>{var b;return(b=wt.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Cn=!0,Er()}}),yt.element.classList.add("persona-hidden"),Kn=m,m.appendChild(c),m.appendChild(yt.element),yt.backdrop&&J.appendChild(yt.backdrop),J.appendChild(m),Hs=()=>{var b,S,W,q;if(!Kn||!yt)return;if(!(((W=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:W.resizable)===!0)){Gn==null||Gn(),Gn=null,ss(),_t&&(_t.remove(),_t=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!_t){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let D=e.ownerDocument,de=(q=D.defaultView)!=null?q:window,le=Q=>{var ct,rt;if(!yt||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||de.innerWidth<=640)return;Q.preventDefault(),ss();let we=Q.clientX,Fe=yt.element.getBoundingClientRect().width,Ee=(rt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:rt.layout,Ze=Re=>{let Pe=Kn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Fg(Kn,de),gt=ze?0:_.getBoundingClientRect().width||6,I=Fe-(Re.clientX-we),De=_g(I,Pe,Ke,gt,Ee==null?void 0:Ee.resizableMinWidth,Ee==null?void 0:Ee.resizableMaxWidth);yt.element.style.width=`${De}px`,yt.element.style.maxWidth="none",Bs()},Ue=()=>{D.removeEventListener("pointermove",Ze),D.removeEventListener("pointerup",Ue),D.removeEventListener("pointercancel",Ue),Vr=null;try{_.releasePointerCapture(Q.pointerId)}catch{}};Vr=Ue,D.addEventListener("pointermove",Ze),D.addEventListener("pointerup",Ue),D.addEventListener("pointercancel",Ue);try{_.setPointerCapture(Q.pointerId)}catch{}};_.addEventListener("pointerdown",le),_t=_,Kn.insertBefore(_,yt.element),Gn=()=>{_.removeEventListener("pointerdown",le)}}if(_t){let _=Hn.artifacts.length>0&&!Cn;_t.classList.toggle("persona-hidden",!_),Bs()}},Bo=()=>{var de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt,Re,Pe,ze,Ke;if(!k||!yt||((le=(de=r.launcher)==null?void 0:de.sidebarMode)!=null?le:!1)||dn(r)&&rr(r).reveal==="emerge")return;let b=(Q=e.ownerDocument.defaultView)!=null?Q:window,S=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,W=(Ze=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?Ze:640;if(S&&b.innerWidth<=W||!Og(r,k))return;let q=(rt=(ct=(Ue=r.launcher)==null?void 0:Ue.width)!=null?ct:r.launcherWidth)!=null?rt:nr,_=(Ke=(ze=(Pe=(Re=r.features)==null?void 0:Re.artifacts)==null?void 0:Pe.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!Cn?(J.style.width=_,J.style.maxWidth=_):(J.style.width=q,J.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Wn=new ResizeObserver(()=>{Er()}),Wn.observe(J))}else J.appendChild(Se),H()&&dt&&(qe.peekBanner&&dt.appendChild(qe.peekBanner),dt.appendChild(Oe));e.appendChild(ye),dt&&e.appendChild(dt);let co=()=>{var De,We,me,Wt,It,Vt,ft,jt,Fn,Zt,Je,Tt,nn,Zn,_n,_o,$o,gs,fs,Gt,jo,ho,yo,Qr,Uo,gr,Hr,Qe;if(H()){J.style.width="100%",J.style.maxWidth="100%";let Ht=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},zt=ye.dataset.state==="expanded",Bt=(me=Ht.expandedSize)!=null?me:"anchored";if(!(zt&&Bt!=="fullscreen")){Se.style.background="",Se.style.border="",Se.style.borderRadius="",Se.style.overflow="",Se.style.boxShadow="";return}let Et=(It=(Wt=r.theme)==null?void 0:Wt.components)==null?void 0:It.panel,Nt=ua(r),un=(gn,er)=>{var bo;return gn==null||gn===""?er:(bo=Es(Nt,gn))!=null?bo:gn},$n="1px solid var(--persona-border)",Br="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Se.style.background="var(--persona-surface, #ffffff)",Se.style.border=un(Et==null?void 0:Et.border,$n),Se.style.borderRadius=un(Et==null?void 0:Et.borderRadius,mn),Se.style.boxShadow=un(Et==null?void 0:Et.shadow,Br),Se.style.overflow="hidden";return}let c=dn(r),m=(ft=(Vt=r.launcher)==null?void 0:Vt.sidebarMode)!=null?ft:!1,h=c||m||((Fn=(jt=r.launcher)==null?void 0:jt.fullHeight)!=null?Fn:!1),b=((Zt=r.launcher)==null?void 0:Zt.enabled)===!1,S=(Tt=(Je=r.theme)==null?void 0:Je.components)==null?void 0:Tt.panel,W=ua(r),q=(Ht,zt)=>{var Bt;return Ht==null||Ht===""?zt:(Bt=Es(W,Ht))!=null?Bt:Ht},_=(nn=e.ownerDocument.defaultView)!=null?nn:window,D=(_n=(Zn=r.launcher)==null?void 0:Zn.mobileFullscreen)!=null?_n:!0,de=($o=(_o=r.launcher)==null?void 0:_o.mobileBreakpoint)!=null?$o:640,le=_.innerWidth<=de,Q=D&&le&&k,we=(fs=(gs=r.launcher)==null?void 0:gs.position)!=null?fs:"bottom-left",Fe=we==="bottom-left"||we==="top-left",Ee=(jo=(Gt=r.launcher)==null?void 0:Gt.zIndex)!=null?jo:vn,Ze=m||Q?"none":"1px solid var(--persona-border)",Ue=Q?"none":m?Fe?"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))";c&&!Q&&(Ue="none",Ze="none");let ct=m||Q?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=q(S==null?void 0:S.border,Ze),Re=q(S==null?void 0:S.shadow,Ue),Pe=q(S==null?void 0:S.borderRadius,ct),ze=ve.scrollTop;e.style.cssText="",ye.style.cssText="",J.style.cssText="",Se.style.cssText="",ve.style.cssText="",Oe.style.cssText="",K&&(ve.style.display="none");let Ke=()=>{var zt;if(ze<=0)return;((zt=ve.ownerDocument.defaultView)!=null?zt:window).requestAnimationFrame(()=>{if(ve.scrollTop===ze)return;let Bt=ve.scrollHeight-ve.clientHeight;Bt<=0||(ve.scrollTop=Math.min(ze,Bt))})};if(Q){ye.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"),ye.style.cssText=`
35
35
  position: fixed !important;
36
36
  inset: 0 !important;
37
37
  width: 100% !important;
@@ -41,7 +41,7 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
41
41
  padding: 0 !important;
42
42
  display: flex !important;
43
43
  flex-direction: column !important;
44
- z-index: ${Se} !important;
44
+ z-index: ${Ee} !important;
45
45
  background-color: var(--persona-surface, #ffffff) !important;
46
46
  `,J.style.cssText=`
47
47
  position: relative !important;
@@ -56,7 +56,7 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
56
56
  padding: 0 !important;
57
57
  box-shadow: none !important;
58
58
  border-radius: 0 !important;
59
- `,Ae.style.cssText=`
59
+ `,Se.style.cssText=`
60
60
  display: flex !important;
61
61
  flex-direction: column !important;
62
62
  flex: 1 1 0% !important;
@@ -67,19 +67,19 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
67
67
  overflow: hidden !important;
68
68
  border-radius: 0 !important;
69
69
  border: none !important;
70
- `,Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0",j=!0,Ke();return}let ft=(lo=(io=r==null?void 0:r.launcher)==null?void 0:io.width)!=null?lo:r==null?void 0:r.launcherWidth,I=ft!=null?ft:sr;if(!m&&!c)b&&h?(J.style.width="100%",J.style.maxWidth="100%"):(J.style.width=I,J.style.maxWidth=I);else if(c)if(ar(r).reveal==="emerge"){let Vt=ar(r).width;J.style.width=Vt,J.style.maxWidth=Vt}else J.style.width="100%",J.style.maxWidth="100%";if(xe(),J.style.boxShadow=Ie,J.style.borderRadius=Le,Ae.style.border=rt,Ae.style.borderRadius=Le,c&&!Q&&(S==null?void 0:S.border)===void 0&&(Ae.style.border="none",ar(r).side==="right"?Ae.style.borderLeft="1px solid var(--persona-border)":Ae.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),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%",b&&(fe.style.overflow="hidden"),J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",J.style.overflow="hidden",Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.overflow="hidden",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0"),fe.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"),!m&&!b&&!c&&((zr=hr[ve])!=null?zr:hr["bottom-right"]).split(" ").forEach(Vt=>fe.classList.add(Vt)),m){let Dt=(ur=(Ho=r.launcher)==null?void 0:Ho.sidebarWidth)!=null?ur:"420px";fe.style.cssText=`
70
+ `,ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",Oe.style.flexShrink="0",j=!0,Ke();return}let gt=(yo=(ho=r==null?void 0:r.launcher)==null?void 0:ho.width)!=null?yo:r==null?void 0:r.launcherWidth,I=gt!=null?gt:nr;if(!m&&!c)b&&h?(J.style.width="100%",J.style.maxWidth="100%"):(J.style.width=I,J.style.maxWidth=I);else if(c)if(rr(r).reveal==="emerge"){let zt=rr(r).width;J.style.width=zt,J.style.maxWidth=zt}else J.style.width="100%",J.style.maxWidth="100%";if(Bo(),J.style.boxShadow=Re,J.style.borderRadius=Pe,Se.style.border=rt,Se.style.borderRadius=Pe,c&&!Q&&(S==null?void 0:S.border)===void 0&&(Se.style.border="none",rr(r).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",b&&(ye.style.overflow="hidden"),J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",J.style.overflow="hidden",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.overflow="hidden",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",Oe.style.flexShrink="0"),ye.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"),!m&&!b&&!c&&((Qr=br[we])!=null?Qr:br["bottom-right"]).split(" ").forEach(zt=>ye.classList.add(zt)),m){let Ht=(gr=(Uo=r.launcher)==null?void 0:Uo.sidebarWidth)!=null?gr:"420px";ye.style.cssText=`
71
71
  position: fixed !important;
72
72
  top: 0 !important;
73
73
  bottom: 0 !important;
74
- width: ${Dt} !important;
74
+ width: ${Ht} !important;
75
75
  height: 100vh !important;
76
76
  max-height: 100vh !important;
77
77
  margin: 0 !important;
78
78
  padding: 0 !important;
79
79
  display: flex !important;
80
80
  flex-direction: column !important;
81
- z-index: ${Se} !important;
82
- ${Oe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
81
+ z-index: ${Ee} !important;
82
+ ${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
83
  `,J.style.cssText=`
84
84
  position: relative !important;
85
85
  display: flex !important;
@@ -91,9 +91,9 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
91
91
  min-height: 0 !important;
92
92
  margin: 0 !important;
93
93
  padding: 0 !important;
94
- box-shadow: ${Ie} !important;
95
- border-radius: ${Le} !important;
96
- `,J.style.setProperty("width","100%","important"),J.style.setProperty("max-width","100%","important"),Ae.style.cssText=`
94
+ box-shadow: ${Re} !important;
95
+ border-radius: ${Pe} !important;
96
+ `,J.style.setProperty("width","100%","important"),J.style.setProperty("max-width","100%","important"),Se.style.cssText=`
97
97
  display: flex !important;
98
98
  flex-direction: column !important;
99
99
  flex: 1 1 0% !important;
@@ -102,29 +102,29 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
102
102
  min-height: 0 !important;
103
103
  max-height: 100% !important;
104
104
  overflow: hidden !important;
105
- border-radius: ${Le} !important;
105
+ border-radius: ${Pe} !important;
106
106
  border: ${rt} !important;
107
- `,Ne.style.cssText=`
107
+ `,Oe.style.cssText=`
108
108
  flex-shrink: 0 !important;
109
109
  border-top: none !important;
110
110
  padding: 8px 16px 12px 16px !important;
111
- `}if(!b&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",Vt=m?"":"padding-top: 1.25em !important;",Nt=m?"":`z-index: ${(Qe=(Pr=r.launcher)==null?void 0:Pr.zIndex)!=null?Qe:wn} !important;`;fe.style.cssText+=Dt+Vt+Nt}Ke()};Cr(),qo(e,r),hi(e,r),yi(e,r);let mt=[];mt.push(()=>{document.removeEventListener("keydown",no)});let rn=null,on=null;mt.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Dn&&mt.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),mt.push(()=>{Sn==null||Sn(),Sn=null,Fr(),Rt&&(Rt.remove(),Rt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),re&&mt.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),We==null||We.destroy(),We=null,V==null||V.destroy(),V=null,be=null});let Ar=null,ks=()=>{Ar&&(Ar(),Ar=null),r.colorScheme==="auto"&&(Ar=cl(()=>{qo(e,r)}))};ks(),mt.push(()=>{Ar&&(Ar(),Ar=null)}),mt.push(a);let _r=(ad=r.features)==null?void 0:ad.streamAnimation;if(_r!=null&&_r.type&&_r.type!=="none"){let c=ia(_r.type,_r.plugins);c&&(ul(c,e),mt.push(()=>qm(e)))}let Eo=mg(Pt),Sr=null,$,Qo=c=>{var b,S;if(!$)return;let m=c!=null?c:$.getMessages(),h=((S=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:S.enabled)!==!1?Gi(m):null;h?Eo.render(h,$,ee,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(B=>B.role==="user")?Eo.render([],$,ee,m):Eo.render(r.suggestionChips,$,ee,m,r.suggestionChipsConfig)},Tr=!1,Er=Bm(),$r=new Map,Mr=new Map,cr=new Map,Yo=0,xa=No()!==null,_n=Qa(),$n=0,dr=null,pr=!1,Mo=!1,jr=0,bn=null,kr=null,Zo=!1,ko=!1,es=null,va=4,ts=24,wa=80,ns=new Map,pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ls=(ld=(id=r.voiceRecognition)==null?void 0:id.autoResume)!=null?ld:!1,Zn=c=>{i.emit("voice:state",{active:pt.active,source:c,timestamp:Date.now()})},In=()=>{x(c=>({...c,voiceState:{active:pt.active,timestamp:Date.now(),manuallyDeactivated:pt.manuallyDeactivated}}))},Ca=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Ol(p.voiceState),m=!!c.active,h=Number((S=c.timestamp)!=null?S:0);pt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<Qv&&setTimeout(()=>{var B,q;pt.active||(pt.manuallyDeactivated=!1,((q=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:q.type)==="runtype"?$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),Zn("restore"),$.isVoiceActive()&&as()}):Sa("restore"))},1e3)},rs=()=>$?Pg($.getMessages()).filter(c=>!c.__skipPersist):[];function tt(c){if(!(l!=null&&l.save))return;let h={messages:c?Pg(c):$?rs():[],metadata:p,artifacts:Nn.artifacts,selectedArtifactId:Nn.selectedId};try{let b=l.save(h);b instanceof Promise&&b.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let w=null,z=()=>fe.querySelector("#persona-scroll-container")||Me,U=()=>{w!==null&&(cancelAnimationFrame(w),w=null),pr=!1},G=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),Mo=!1,U()},ye=()=>{jr>0?(yn.textContent=String(jr),yn.style.display="",jt.setAttribute("aria-label",`${ht()||"Jump to latest"} (${jr} new)`)):(yn.textContent="",yn.style.display="none",jt.setAttribute("aria-label",ht()||"Jump to latest"))},_e=()=>{jr!==0&&(jr=0,ye())},gt=()=>Ft()==="follow"?!_n.isFollowing():!zo(Me,ts),st=()=>{if(!Qt()||K){jt.parentNode&&jt.remove(),jt.style.display="none";return}jt.parentNode!==Ae&&Ae.appendChild(jt),Jn();let m=Gr(Me)>0&&gt();m||_e(),jt.style.display=m?"":"none"},Ps=()=>{_n.pause()&&(G(),st())},Rn=()=>{_n.resume(),_e(),st()},dn=(c=!1)=>{Ft()==="follow"&&_n.isFollowing()&&(!c&&!Tr||(dr!==null&&(cancelAnimationFrame(dr),dr=null),Mo=!0,dr=requestAnimationFrame(()=>{dr=null,Mo=!1,_n.isFollowing()&&Lo(z(),c?220:140)})))},pn=(c,m,h,b=()=>!0)=>{let S=c.scrollTop,B=m(),q=B-S;U();let _=performance.now();pr=!0;let D=ie=>1-Math.pow(1-ie,3),ae=ie=>{if(!b()){U();return}let Q=m();Q!==B&&(B=Q,q=B-S);let ve=ie-_,Oe=Math.min(ve/h,1),Se=D(Oe),Ze=S+q*Se;c.scrollTop=Ze,$n=c.scrollTop,Oe<1?w=requestAnimationFrame(ae):(c.scrollTop=B,$n=c.scrollTop,w=null,pr=!1)};w=requestAnimationFrame(ae)},Lo=(c,m=500)=>{let h=Gr(c)-c.scrollTop;if(Math.abs(h)<1){$n=c.scrollTop;return}if(Math.abs(h)>=wa){U(),pr=!0,c.scrollTop=Gr(c),$n=c.scrollTop,pr=!1;return}pn(c,()=>Gr(c),m,()=>_n.isFollowing())},Ur=()=>{let c=z();pr=!0,c.scrollTop=Gr(c),$n=c.scrollTop,pr=!1,st()},Tn=c=>{kn.style.height=`${Math.max(0,Math.round(c))}px`,bn&&(bn.spacerHeight=Math.max(0,c))},fn=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),U(),bn=null,kn.style.height="0px"},jn=c=>{kr!==null&&cancelAnimationFrame(kr),kr=requestAnimationFrame(()=>{var ae;kr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${m}"]`);if(!h)return;let b=0,S=h;for(;S&&S!==Me;)b+=S.offsetTop,S=S.offsetParent;let B=(ae=bn==null?void 0:bn.spacerHeight)!=null?ae:0,q=Me.scrollHeight-B,{targetScrollTop:_,spacerHeight:D}=_m({anchorOffsetTop:b,topOffset:Hn(),viewportHeight:Me.clientHeight,contentHeight:q});bn={initialSpacerHeight:D,contentHeightAtAnchor:q,spacerHeight:D},Tn(D),pn(Me,()=>_,220)})},mf=()=>{if(Ft()==="follow"){if(!_n.isFollowing()||zo(Me,1))return;dn(!Tr);return}if(bn&&bn.initialSpacerHeight>0){let c=Me.scrollHeight-bn.spacerHeight,m=$m({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:c});m!==bn.spacerHeight&&Tn(m)}st()},gf=c=>{let m=Ft();m==="follow"?(Rn(),dn(!0)):m==="anchor-top"&&jn(c)},ff=c=>{let m=new Map;c.forEach(h=>{let b=ns.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!ko&&Ft()!=="anchor-top"&&gt()&&(jr+=1,ye(),st())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),ns.clear(),m.forEach((h,b)=>{ns.set(b,h)})},hf=(c,m,h)=>{var rt,Ie,Le,ze,Ke,ft;let b=document.createElement("div"),B=(()=>{var Be;let I=o.find(Re=>Re.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),q=(I,Be)=>Be==null?!1:typeof Be=="string"?(I.textContent=Be,!0):(I.appendChild(Be),!0),_=new Set,D=new Set,ae=o.some(I=>I.renderAskUserQuestion),ie=[],Q=[],ve=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Se=[];if(m.forEach(I=>{var Je,Et,nn,nr,qn,Io,Ro,ls,cs,Jt,Wo,io,lo,zr,Ho,ur,Pr;_.add(I.id);let Be=ae&&po(I),Re=Oe&&I.variant==="approval"&&!!I.approval,ue=!Be&&I.role==="assistant"&&!I.variant&&ve&&Hl(I);if(!Re&&cr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),cr.delete(I.id)}if(!ue&&Mr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),Mr.delete(I.id)}let Bt=po(I)?`:${(Je=I.agentMetadata)!=null&&Je.askUserQuestionAnswered?"a":"u"}:${(Et=I.agentMetadata)!=null&&Et.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",Wt=Hm(I,Yo)+Bt,Kt=Be||Re||ue?null:Dm(Er,I.id,Wt);if(Kt){b.appendChild(Kt.cloneNode(!0)),po(I)&&((nn=I.toolCall)!=null&&nn.id)&&((nr=I.agentMetadata)==null?void 0:nr.awaitingLocalTool)===!0&&!((qn=I.agentMetadata)!=null&&qn.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,qe.composerOverlay));return}let yt=null,qt=o.find(Qe=>!!(I.variant==="reasoning"&&Qe.renderReasoning||I.variant==="tool"&&Qe.renderToolCall||!I.variant&&Qe.renderMessage)),Un=(Io=r.layout)==null?void 0:Io.messages;if(po(I)&&((Ro=I.agentMetadata)==null?void 0:Ro.askUserQuestionAnswered)===!0){$r.delete(I.id);let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime");return}if(Ha(I)&&((cs=(ls=r.features)==null?void 0:ls.suggestReplies)==null?void 0:cs.enabled)!==!1)return;if(po(I)&&((Wo=(Jt=r.features)==null?void 0:Jt.askUserQuestion)==null?void 0:Wo.enabled)!==!1){let Qe=o.find(Dt=>typeof Dt.renderAskUserQuestion=="function");if(Qe&&Ct.current){let Dt=$r.get(I.id),Vt=Dt!==Wt,Nt=null;if(Vt){let{payload:_t,complete:un}=uo(I),zn=I.id,Ir=()=>{var mn;return(mn=Ct.current)==null?void 0:mn.getMessages().find(gn=>gn.id===zn)};Nt=Qe.renderAskUserQuestion({message:I,payload:_t,complete:un,resolve:mn=>{var rr;let gn=Ir();gn&&((rr=Ct.current)==null||rr.resolveAskUserQuestion(gn,mn))},dismiss:()=>{var gn,rr,co;let mn=Ir();(gn=mn==null?void 0:mn.agentMetadata)!=null&&gn.awaitingLocalTool&&((rr=Ct.current)==null||rr.markAskUserQuestionResolved(mn),(co=Ct.current)==null||co.resolveAskUserQuestion(mn,"(dismissed)"))},config:r})}let Xt=Dt!=null;if(Vt&&Nt===null&&!Xt){((io=I.agentMetadata)==null?void 0:io.awaitingLocalTool)===!0&&!((lo=I.agentMetadata)!=null&&lo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,qe.composerOverlay));return}let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id=`wrapper-${I.id}`,Mt.setAttribute("data-wrapper-id",I.id),Mt.setAttribute("data-ask-plugin-stub","true"),Mt.setAttribute("data-preserve-runtime","true"),b.appendChild(Mt),ie.push({messageId:I.id,fingerprint:Wt,bubble:Nt});return}else{((zr=I.agentMetadata)==null?void 0:zr.awaitingLocalTool)===!0&&!((Ho=I.agentMetadata)!=null&&Ho.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,qe.composerOverlay));return}}else if(Re){let Qe=(ur=o.find(Xt=>typeof Xt.renderApproval=="function"))!=null?ur:s,Vt=cr.get(I.id)!==Wt,Nt=null;if(Vt&&(Qe!=null&&Qe.renderApproval)){let Xt=I.id,Mt=(_t,un)=>{var Ir,mn,gn;let zn=(Ir=Ct.current)==null?void 0:Ir.getMessages().find(rr=>rr.id===Xt);zn!=null&&zn.approval&&(zn.approval.toolType==="webmcp"?(mn=Ct.current)==null||mn.resolveWebMcpApproval(zn.id,_t):(gn=Ct.current)==null||gn.resolveApproval(zn.approval,_t,un))};Nt=Qe.renderApproval({message:I,defaultRenderer:()=>gi(I,r),config:r,approve:_t=>Mt("approved",_t),deny:_t=>Mt("denied",_t)})}if(Vt&&Nt===null){let Xt=c.querySelector(`#wrapper-${I.id}`);Xt==null||Xt.removeAttribute("data-preserve-runtime"),cr.delete(I.id),yt=gi(I,r)}else{let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${I.id}`,Xt.setAttribute("data-wrapper-id",I.id),Xt.setAttribute("data-approval-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),b.appendChild(Xt),Se.push({messageId:I.id,fingerprint:Wt,bubble:Nt});return}}else if(qt)if(I.variant==="reasoning"&&I.reasoning&&qt.renderReasoning){if(!Ce)return;yt=qt.renderReasoning({message:I,defaultRenderer:()=>wl(I,r),config:r})}else if(I.variant==="tool"&&I.toolCall&&qt.renderToolCall){if(!ke)return;yt=qt.renderToolCall({message:I,defaultRenderer:()=>Al(I,r),config:r})}else qt.renderMessage&&(yt=qt.renderMessage({message:I,defaultRenderer:()=>{let Qe=ga(I,h,Un,r.messageActions,ge,{loadingIndicatorRenderer:B,widgetConfig:r});return I.role!=="user"&&kl(Qe,I,r,$),Qe},config:r}));if(!yt&&ue){let Qe=Bl(I);if(Qe){let Dt=Mr.get(I.id),Vt=Dt!==Wt,Nt=r.wrapComponentDirectiveInBubble!==!1,Xt=null;if(Vt){let Mt=Wl(Qe,{config:r,message:I,transform:h});if(Mt)if(Nt){let _t=document.createElement("div");if(_t.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),_t.id=`bubble-${I.id}`,_t.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let un=document.createElement("div");un.className="persona-mb-3 persona-text-sm persona-leading-relaxed",un.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),_t.appendChild(un)}_t.appendChild(Mt),Xt=_t}else{let _t=document.createElement("div");if(_t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",_t.id=`bubble-${I.id}`,_t.setAttribute("data-message-id",I.id),_t.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let un=document.createElement("div");un.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",un.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),_t.appendChild(un)}_t.appendChild(Mt),Xt=_t}}if(Xt||Dt!=null){let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id=`wrapper-${I.id}`,Mt.setAttribute("data-wrapper-id",I.id),Mt.setAttribute("data-component-directive-stub","true"),Mt.setAttribute("data-preserve-runtime","true"),Nt||Mt.classList.add("persona-w-full"),b.appendChild(Mt),Q.push({messageId:I.id,fingerprint:Wt,bubble:Xt});return}}}if(!yt)if(I.variant==="reasoning"&&I.reasoning){if(!Ce)return;yt=wl(I,r)}else if(I.variant==="tool"&&I.toolCall){if(!ke)return;yt=Al(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;yt=gi(I,r)}else{let Qe=(Pr=r.layout)==null?void 0:Pr.messages;Qe!=null&&Qe.renderUserMessage&&I.role==="user"?yt=Qe.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):Qe!=null&&Qe.renderAssistantMessage&&I.role==="assistant"?yt=Qe.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):yt=ga(I,h,Qe,r.messageActions,ge,{loadingIndicatorRenderer:B,widgetConfig:r}),I.role!=="user"&&yt&&kl(yt,I,r,$)}let en=document.createElement("div");en.className="persona-flex",en.id=`wrapper-${I.id}`,en.setAttribute("data-wrapper-id",I.id),I.role==="user"&&en.classList.add("persona-justify-end"),(yt==null?void 0:yt.getAttribute("data-persona-component-directive"))==="true"&&en.classList.add("persona-w-full"),en.appendChild(yt),Nm(Er,I.id,Wt,en),b.appendChild(en)}),qe.composerOverlay&&qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Re=Be.getAttribute("data-persona-ask-sheet-for");Re&&!D.has(Re)&&_o(qe.composerOverlay,Re)}),(Ie=(rt=r.features)==null?void 0:rt.toolCallDisplay)!=null&&Ie.grouped){let I=[],Be=[];m.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&ke){Be.push(Re);return}Be.length>1&&I.push(Be),Be=[]}),Be.length>1&&I.push(Be),I.forEach((Re,ue)=>{var Je,Et;let Bt=Re.map(nn=>Array.from(b.children).find(nr=>nr instanceof HTMLElement&&nr.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Bt.length<2)return;let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-tool-group-${ue}-${Re[0].id}`,Wt.setAttribute("data-wrapper-id",`tool-group-${ue}-${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 yt=document.createElement("div");yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Re.length} tools`,Un=(Et=(Je=r.toolCall)==null?void 0:Je.renderGroupedSummary)==null?void 0:Et.call(Je,{messages:Re,toolCalls:Re.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:qt,config:r});q(yt,Un)||(yt.textContent=qt);let en=document.createElement("div");en.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(yt,en),Wt.appendChild(Kt),Bt[0].before(Wt),Bt.forEach((nn,nr)=>{let qn=document.createElement("div");qn.className="persona-tool-group-item persona-relative",qn.setAttribute("data-persona-tool-group-item","true"),nr<Bt.length-1&&qn.setAttribute("data-persona-tool-group-connector","true"),qn.appendChild(nn),en.appendChild(qn)})})}Om(Er,_);let Ze=m.some(I=>I.role==="assistant"&&I.streaming),Ue=m[m.length-1],ct=(Ue==null?void 0:Ue.role)==="assistant"&&!Ue.streaming&&Ue.variant!=="approval";if(Tr&&m.some(I=>I.role==="user")&&!Ze&&!ct){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:Cs},Be=o.find(ue=>ue.renderLoadingIndicator),Re=null;if(Be!=null&&Be.renderLoadingIndicator&&(Re=Be.renderLoadingIndicator(I)),Re===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Re=r.loadingIndicator.render(I)),Re===null&&(Re=Cs()),Re){let ue=document.createElement("div"),Bt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ue.className=Bt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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(" "),ue.setAttribute("data-typing-indicator","true"),ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ue.appendChild(Re);let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id="wrapper-typing-indicator",Wt.setAttribute("data-wrapper-id","typing-indicator"),Wt.appendChild(ue),b.appendChild(Wt)}}if(!Tr&&m.length>0){let I=m[m.length-1],Be={config:r,lastMessage:I,messageCount:m.length},Re=o.find(Bt=>Bt.renderIdleIndicator),ue=null;if(Re!=null&&Re.renderIdleIndicator&&(ue=Re.renderIdleIndicator(Be)),ue===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(ue=r.loadingIndicator.renderIdle(Be)),ue){let Bt=document.createElement("div"),Wt=((ft=r.loadingIndicator)==null?void 0:ft.showBubble)!==!1;Bt.className=Wt?["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(" "),Bt.setAttribute("data-idle-indicator","true"),Bt.appendChild(ue);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Bt),b.appendChild(Kt)}}if(Ja(c,b),ie.length>0)for(let{messageId:I,fingerprint:Be,bubble:Re}of ie){let ue=c.querySelector(`#wrapper-${I}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",Be),$r.set(I,Be))}if($r.size>0)for(let I of $r.keys())_.has(I)||$r.delete(I);if(Q.length>0)for(let{messageId:I,fingerprint:Be,bubble:Re}of Q){let ue=c.querySelector(`#wrapper-${I}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",Be),Mr.set(I,Be))}if(Mr.size>0)for(let I of Mr.keys())_.has(I)||Mr.delete(I);if(Se.length>0)for(let{messageId:I,fingerprint:Be,bubble:Re}of Se){let ue=c.querySelector(`#wrapper-${I}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",Be),cr.set(I,Be))}if(cr.size>0)for(let I of cr.keys())_.has(I)||cr.delete(I)},Is=(c,m,h)=>{hf(c,m,h),eo()},Rs=null,yf=()=>{var h;if(Rs)return;let c=b=>{let S=b.composedPath();S.includes(fe)||dt&&S.includes(dt)||Ut(!1,"user")};Rs=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Xl=()=>{var m;if(!Rs)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Rs,!0),Rs=null};mt.push(()=>Xl());let Ws=null,bf=()=>{var h;if(Ws)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Ut(!1,"user"))};Ws=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Ql=()=>{var m;if(!Ws)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Ws,!0),Ws=null};mt.push(()=>Ql());let Hs=!1,Yl=new Set,xf=()=>{var m,h,b,S;let c=(b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return c||((S=r.features)==null?void 0:S.streamAnimation)},os=()=>{var ct,rt,Ie,Le;if(!W())return;let c=qe.peekBanner,m=qe.peekTextNode;if(!c||!m)return;if(N){c.classList.remove("persona-pill-peek--visible");return}let h=(ct=$==null?void 0:$.getMessages())!=null?ct:[],b;for(let ze=h.length-1;ze>=0;ze--){let Ke=h[ze];if(Ke.role==="assistant"&&Ke.content){b=Ke;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let S=b.content,B=!!b.streaming,q=xf(),_=ei(q),D=_.type!=="none"?ia(_.type,q==null?void 0:q.plugins):null,ae=((rt=D==null?void 0:D.isAnimating)==null?void 0:rt.call(D,b))===!0,ie=D!==null&&(B||ae);ie&&D&&!Yl.has(D.name)&&(ul(D,e),Yl.add(D.name));let Q=ie&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;ve&&ve!==Q&&(m.classList.remove(ve),delete m.dataset.personaPeekStreamClass),Q&&ve!==Q&&(m.classList.add(Q),m.dataset.personaPeekStreamClass=Q),ie?(m.style.setProperty("--persona-stream-step",`${_.speed}ms`),m.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Oe=ie?ti(S,_.buffer,D,b,B):S;if(ie&&_.placeholder==="skeleton"&&B&&(!Oe||!Oe.trim())){let ze=document.createElement("div"),Ke=ca();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),Ja(m,ze)}else{let ze=Math.max(0,Oe.length-100),Ke=Oe.length>100?Oe.slice(-100):Oe,ft=Vr(Ke);if(!ie||!D){let I=Oe.length>100?`\u2026${Ke}`:Ke;m.textContent!==I&&(m.textContent=I)}else{let I=ft;(D.wrap==="char"||D.wrap==="word")&&(I=la(ft,D.wrap,`peek-${b.id}`,{skipTags:D.skipTags,startIndex:ze}));let Be=document.createElement("div");if(Be.innerHTML=I,D.useCaret&&Ke.length>0){let Re=ni(),ue=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bt=ue[ue.length-1];Bt!=null&&Bt.parentNode?Bt.parentNode.insertBefore(Re,Bt.nextSibling):Be.appendChild(Re)}Ja(m,Be),(Le=D.onAfterRender)==null||Le.call(D,{container:m,bubble:c,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let Ue=Tr||Hs;c.classList.toggle("persona-pill-peek--visible",Ue)};if(W()){let c=qe.peekBanner;if(c){let b=S=>{S.preventDefault(),S.stopPropagation(),Ut(!0,"user")};c.addEventListener("pointerdown",b),mt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Hs||(Hs=!0,os())},h=()=>{Hs&&(Hs=!1,os())};J.addEventListener("pointerenter",m),J.addEventListener("pointerleave",h),mt.push(()=>{J.removeEventListener("pointerenter",m),J.removeEventListener("pointerleave",h)}),dt&&(dt.addEventListener("pointerenter",m),dt.addEventListener("pointerleave",h),mt.push(()=>{dt.removeEventListener("pointerenter",m),dt.removeEventListener("pointerleave",h)}))}let vf=c=>{var ve,Oe,Se,Ze,Ue,ct,rt,Ie;let m=(Oe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Oe:{},h=(Se=m.expandedSize)!=null?Se:"anchored",b=(Ze=m.bottomOffset)!=null?Ze:"16px",S=m.collapsedMaxWidth,B=(Ue=m.expandedMaxWidth)!=null?Ue:"880px",q=(ct=m.expandedTopOffset)!=null?ct:"5vh",_=(rt=m.modalMaxWidth)!=null?rt:"880px",D=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",ae="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",Q=fe.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",dt){let Le=dt.style;Le.bottom=b,Le.width=S!=null?S:""}if(c&&h!=="fullscreen"){if(h==="modal"){Q.top="50%",Q.left="50%",Q.transform="translate(-50%, -50%)",Q.bottom="auto",Q.right="auto",Q.width=_,Q.maxWidth=ae,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${b} + ${ie})`,Q.top=q,Q.width=B,Q.maxWidth=ae}},Bs=()=>{var D,ae,ie,Q,ve,Oe,Se,Ze;if(!O())return;if(W()){let ct=(ie=((ae=(D=r.launcher)==null?void 0:D.composerBar)!=null?ae:{}).expandedSize)!=null?ie:"anchored",rt=N?"expanded":"collapsed";fe.dataset.state=rt,fe.dataset.expandedSize=ct,dt&&(dt.dataset.state=rt,dt.dataset.expandedSize=ct),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),vf(N),Ae.style.display=N?"flex":"none",Cr(),N?(yf(),bf()):(Xl(),Ql()),os();return}let c=cn(r),m=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(Oe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Oe:640,b=(Ze=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Ze:!0,S=m.innerWidth<=h,B=b&&S&&k,q=ar(r).reveal;N?(fe.style.removeProperty("display"),fe.style.display=c?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0"),J.classList.add("persona-scale-100","persona-opacity-100"),Zt?Zt.element.style.display="none":sn&&(sn.style.display="none")):(c?c&&(q==="overlay"||q==="push")&&!B?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100"),J.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=c?"none":"":sn&&(sn.style.display=c?"none":""))},Ut=(c,m="user")=>{var B,q;if(!O()||N===c)return;let h=N;N=c,Bs();let b=(()=>{var Se,Ze,Ue,ct,rt,Ie,Le,ze,Ke,ft;let _=(Ze=(Se=r.launcher)==null?void 0:Se.sidebarMode)!=null?Ze:!1,D=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,ae=(rt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?rt:!0,ie=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,Q=D.innerWidth<=ie,ve=cn(r)&&ae&&Q,Oe=W()&&((ft=(Ke=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?ft:"fullscreen")==="fullscreen";return _||ae&&Q&&k||ve||Oe})();if(N&&b){if(!rn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(rn=ml(D,(q=(B=r.launcher)==null?void 0:B.zIndex)!=null?q:wn))}on||(on=gl(e.ownerDocument))}else N||(rn==null||rn(),rn=null,on==null||on(),on=null);N&&(Ds(),Ft()==="follow"?dn(!0):Ur());let S={open:N,source:m,timestamp:Date.now()};N&&!h?i.emit("widget:opened",S):!N&&h&&i.emit("widget:closed",S),i.emit("widget:state",{open:N,launcherEnabled:k,voiceActive:pt.active,streaming:$.isStreaming()})},Pi=c=>{ce(c?"stop":"send"),H&&(H.disabled=c),Eo.buttons.forEach(m=>{m.disabled=c}),Ne.dataset.personaComposerStreaming=c?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Ii=()=>{pt.active||ee&&ee.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Ii(),200)});let Zl=()=>{var h,b,S,B,q,_,D,ae,ie,Q,ve;yr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",br.textContent=(B=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",ee.placeholder=(_=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?_:"How can I help...";let c=Me.querySelector("[data-persona-intro-card]");if(c){let Oe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Oe?"":"none",Oe?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((ie=(ae=r.sendButton)==null?void 0:ae.useIcon)!=null&&ie)&&!($!=null&&$.isStreaming())&&(je.textContent=(ve=(Q=r.copy)==null?void 0:Q.sendButtonLabel)!=null?ve:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=p.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{x(m=>({...m,sessionId:c}))}});let Po=null,wf=()=>{Po==null&&(Po=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Po),Po=null;return}let m=Date.now();c.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Na(m-b))})},100))};$=new ta(r,{onMessagesChanged(c){var b;Is(nt,c,Z),wf(),Qo(c),dn(!Tr),ff(c);let m=[...c].reverse().find(S=>S.role==="user");c.length===0&&fn(),!Zo||ko?(Zo=!0,es=(b=m==null?void 0:m.id)!=null?b:null):m&&m.id!==es&&(es=m.id,gf(m.id));let h=pt.lastUserMessageId;m&&m.id!==h&&(pt.lastUserMessageId=m.id,i.emit("user:message",m)),pt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),tt(c),os()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};$t(hn,(S=>{var B,q,_,D;return S==="idle"?(B=m.idleText)!=null?B:vn.idle:S==="connecting"?(q=m.connectingText)!=null?q:vn.connecting:S==="connected"?(_=m.connectedText)!=null?_:vn.connected:S==="error"?(D=m.errorText)!=null?D:vn.error:vn[S]})(c),m,c)},onStreamingChanged(c){Tr=c,Pi(c),$&&Is(nt,$.getMessages(),Z),c||dn(!0),os()},onVoiceStatusChanged(c){var m,h;if(i.emit("voice:status",{status:c,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":qr(),as();break;case"processing":qr(),Ef();break;case"speaking":qr(),Mf();break;default:c==="idle"&&$.isBargeInActive()?(qr(),as(),H==null||H.setAttribute("aria-label","End voice session")):(pt.active=!1,qr(),Zn("system"),In());break}},onArtifactsState(c){Nn=c,Pn(),tt()}}),Ct.current=$;let Ri=null;if($.onReadAloudChange((c,m)=>{var S;Yr=c,Zr=m,eo();let h=c!=null?c:Ri;c&&(Ri=c);let b=h&&(S=$.getMessages().find(B=>B.id===h))!=null?S:null;i.emit("message:read-aloud",{messageId:h,message:b,state:m,timestamp:Date.now()}),m==="idle"&&(Ri=null)}),Zo=!0,((dd=(cd=r.voiceRecognition)==null?void 0:cd.provider)==null?void 0:dd.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&$.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(V||r.onSSEEvent)&&$.setSSEEventCallback((c,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,c,m),X==null||X.processEvent(c,m),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(c=>{var m,h,b;if(c){if(c.metadata&&(p=Ol(c.metadata),L.syncFromMetadata()),(m=c.messages)!=null&&m.length){ko=!0;try{$.hydrateMessages(c.messages)}finally{ko=!1}}(h=c.artifacts)!=null&&h.length&&$.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ec=()=>{var m,h,b;!W()||N||!((b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||Ut(!0,"auto")},tc=c=>{var S;if(c.preventDefault(),$.isStreaming()){$.cancel(),X==null||X.reset(),We==null||We.update();return}let m=ee.value.trim(),h=(S=wt==null?void 0:wt.hasAttachments())!=null?S:!1;if(!m&&!h)return;ec();let b;h&&(b=[],b.push(...wt.getContentParts()),m&&b.push(ja(m))),ee.value="",ee.style.height="auto",Aa(),$.sendMessage(m,{contentParts:b}),h&&wt.clearAttachments()},Cf=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Wi={...Xa},Hi=!1,Aa=()=>{Wi={...Xa}},Af=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),Sf=c=>{if(!ee)return;Hi=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),Hi=!1;let m=ee.value.length;ee.setSelectionRange(m,m)},nc=()=>{Hi||Aa()},rc=c=>{if(ee){if(Cf()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=ee.selectionStart===0&&ee.selectionEnd===0,h=Wm({direction:c.key==="ArrowUp"?"up":"down",history:Af(),currentValue:ee.value,atStart:m,state:Wi});if(Wi=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Sf(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Aa(),c.preventDefault(),je.click()}}},oc=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(Ae)&&($.cancel(),X==null||X.reset(),We==null||We.update(),Aa(),c.preventDefault(),c.stopImmediatePropagation())},sc=async c=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!wt)return;let m=Zv(c.clipboardData);m.length!==0&&(c.preventDefault(),await wt.handleFiles(m))},er=null,Lr=!1,ss=null,lt=null,ac=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Sa=(c="user")=>{var B,q,_,D,ae,ie,Q;if(Lr||$.isStreaming())return;let m=ac();if(!m)return;er=new m;let b=(q=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?q:2e3;er.continuous=!0,er.interimResults=!0,er.lang="en-US";let S=ee.value;er.onresult=ve=>{let Oe="",Se="";for(let Ue=0;Ue<ve.results.length;Ue++){let ct=ve.results[Ue],rt=ct[0].transcript;ct.isFinal?Oe+=rt+" ":Se=rt}let Ze=S+Oe+Se;ee.value=Ze,ss&&clearTimeout(ss),(Oe||Se)&&(ss=window.setTimeout(()=>{let Ue=ee.value.trim();Ue&&er&&Lr&&(so(),ee.value="",ee.style.height="auto",$.sendMessage(Ue,{viaVoice:!0}))},b))},er.onerror=ve=>{ve.error!=="no-speech"&&so()},er.onend=()=>{if(Lr){let ve=ee.value.trim();ve&&ve!==S.trim()&&(ee.value="",ee.style.height="auto",$.sendMessage(ve,{viaVoice:!0})),so()}};try{if(er.start(),Lr=!0,pt.active=!0,c!=="system"&&(pt.manuallyDeactivated=!1),Zn(c),In(),H){let ve=(_=r.voiceRecognition)!=null?_:{};lt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(ie=ve.iconSize)!=null?ie:(ae=r.sendButton)==null?void 0:ae.size)!=null?Q:"40")||24};let Oe=ve.recordingBackgroundColor,Se=ve.recordingIconColor,Ze=ve.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let Ue=H.querySelector("svg");Ue&&Ue.setAttribute("stroke",Se)}Ze&&(H.style.borderColor=Ze),H.setAttribute("aria-label","Stop voice recognition")}}catch{so("system")}},so=(c="user")=>{if(Lr){if(Lr=!1,ss&&(clearTimeout(ss),ss=null),er){try{er.stop()}catch{}er=null}if(pt.active=!1,Zn(c),In(),H){if(H.classList.remove("persona-voice-recording"),lt){H.style.backgroundColor=lt.backgroundColor,H.style.color=lt.color,H.style.borderColor=lt.borderColor;let m=H.querySelector("svg");m&&m.setAttribute("stroke",lt.color||"currentColor"),lt=null}H.setAttribute("aria-label","Start voice recognition")}}},Tf=(c,m)=>{var rt,Ie,Le,ze,Ke,ft,I,Be,Re;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((rt=c==null?void 0:c.provider)==null?void 0:rt.type)==="runtype",S=((Ie=c==null?void 0:c.provider)==null?void 0:Ie.type)==="custom";if(!(h||b||S))return null;let q=y("div","persona-send-button-wrapper"),_=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let D=(Le=c==null?void 0:c.iconName)!=null?Le:"mic",ae=(ze=m==null?void 0:m.size)!=null?ze:"40px",ie=(Ke=c==null?void 0:c.iconSize)!=null?Ke:ae,Q=parseFloat(ie)||24,ve=(ft=c==null?void 0:c.backgroundColor)!=null?ft:m==null?void 0:m.backgroundColor,Oe=(I=c==null?void 0:c.iconColor)!=null?I:m==null?void 0:m.textColor;_.style.width=ie,_.style.height=ie,_.style.minWidth=ie,_.style.minHeight=ie,_.style.fontSize="18px",_.style.lineHeight="1",Oe?_.style.color=Oe:_.style.color="var(--persona-text, #111827)";let Ze=me(D,Q,Oe||"currentColor",1.5);Ze?_.appendChild(Ze):_.textContent="\u{1F3A4}",ve?_.style.backgroundColor=ve:_.style.backgroundColor="",c!=null&&c.borderWidth&&(_.style.borderWidth=c.borderWidth,_.style.borderStyle="solid"),c!=null&&c.borderColor&&(_.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(_.style.paddingLeft=c.paddingX,_.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(_.style.paddingTop=c.paddingY,_.style.paddingBottom=c.paddingY),q.appendChild(_);let Ue=(Be=c==null?void 0:c.tooltipText)!=null?Be:"Start voice recognition";if(((Re=c==null?void 0:c.showTooltip)!=null?Re:!1)&&Ue){let ue=y("div","persona-send-button-tooltip");ue.textContent=Ue,q.appendChild(ue)}return{micButton:_,micButtonWrapper:q}},Bi=()=>{var m,h,b,S,B;if(!H||lt)return;let c=(m=r.voiceRecognition)!=null?m:{};lt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((B=(S=c.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Di=(c,m)=>{var B,q,_,D,ae;if(!H)return;let h=H.querySelector("svg");h&&h.remove();let b=(ae=lt==null?void 0:lt.iconSize)!=null?ae:parseFloat((D=(_=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?_:(q=r.sendButton)==null?void 0:q.size)!=null?D:"40")||24,S=me(c,b,m,1.5);S&&H.appendChild(S)},Ta=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},as=()=>{var S;if(!H)return;Bi();let c=(S=r.voiceRecognition)!=null?S:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,b=c.recordingBorderColor;if(Ta(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let B=H.querySelector("svg");B&&B.setAttribute("stroke",h)}b&&(H.style.borderColor=b),H.setAttribute("aria-label","Stop voice recognition")},Ef=()=>{var _,D,ae,ie,Q,ve,Oe,Se;if(!H)return;Bi();let c=(_=r.voiceRecognition)!=null?_:{},m=$.getVoiceInterruptionMode(),h=(D=c.processingIconName)!=null?D:"loader",b=(ie=(ae=c.processingIconColor)!=null?ae:lt==null?void 0:lt.color)!=null?ie:"",S=(ve=(Q=c.processingBackgroundColor)!=null?Q:lt==null?void 0:lt.backgroundColor)!=null?ve:"",B=(Se=(Oe=c.processingBorderColor)!=null?Oe:lt==null?void 0:lt.borderColor)!=null?Se:"";Ta(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=S,H.style.borderColor=B;let q=b||"currentColor";H.style.color=q,Di(h,q),H.setAttribute("aria-label","Processing voice input"),m==="none"&&(H.style.cursor="default")},Mf=()=>{var ae,ie,Q,ve,Oe,Se,Ze,Ue,ct,rt,Ie,Le;if(!H)return;Bi();let c=(ae=r.voiceRecognition)!=null?ae:{},m=$.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(ie=c.speakingIconName)!=null?ie:h,S=(Se=c.speakingIconColor)!=null?Se:m==="barge-in"?(ve=(Q=c.recordingIconColor)!=null?Q:lt==null?void 0:lt.color)!=null?ve:"":(Oe=lt==null?void 0:lt.color)!=null?Oe:"",B=(ct=c.speakingBackgroundColor)!=null?ct:m==="barge-in"?(Ze=c.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(Ue=lt==null?void 0:lt.backgroundColor)!=null?Ue:"",q=(Le=c.speakingBorderColor)!=null?Le:m==="barge-in"?(rt=c.recordingBorderColor)!=null?rt:"":(Ie=lt==null?void 0:lt.borderColor)!=null?Ie:"";Ta(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=B,H.style.borderColor=q;let _=S||"currentColor";H.style.color=_,Di(b,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",D),m==="none"&&(H.style.cursor="default"),m==="barge-in"&&H.classList.add("persona-voice-recording")},qr=()=>{var c,m,h;H&&(Ta(),lt&&(H.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",H.style.color=(m=lt.color)!=null?m:"",H.style.borderColor=(h=lt.borderColor)!=null?h:"",Di(lt.iconName,lt.color||"currentColor"),lt=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},Ea=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.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(()=>{pt.active=!1,pt.manuallyDeactivated=!0,In(),Zn("user"),qr()});return}$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),pt.manuallyDeactivated=!$.isVoiceActive(),In(),Zn("user"),$.isVoiceActive()?as():qr()});return}if(Lr){let h=ee.value.trim();pt.manuallyDeactivated=!0,In(),so("user"),h&&(ee.value="",ee.style.height="auto",$.sendMessage(h))}else pt.manuallyDeactivated=!1,In(),Sa("user")};xr=Ea,H&&(H.addEventListener("click",Ea),mt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),qr()):so("system"),H&&H.removeEventListener("click",Ea)}));let kf=i.on("assistant:complete",()=>{Ls&&(pt.active||pt.manuallyDeactivated||Ls==="assistant"&&!pt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!pt.active&&!pt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),Zn("auto"),$.isVoiceActive()&&as()}):Sa("auto"))},600))});mt.push(kf);let Lf=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});mt.push(Lf);let ic=()=>{Ut(!N,"user")},Zt=null,sn=null;if(k&&!W()){let{instance:c,element:m}=bl({config:r,plugins:o,onToggle:ic});Zt=c,c||(sn=m)}Zt?e.appendChild(Zt.element):sn&&e.appendChild(sn),Bs(),Qo(),Zl(),Pi($.isStreaming()),Ft()==="follow"?dn(!0):Ur(),Ca(),P&&(!k||W()?setTimeout(()=>Ii(),0):N&&setTimeout(()=>Ii(),200));let Ds=()=>{var D,ae,ie,Q,ve,Oe,Se,Ze,Ue,ct,rt,Ie,Le,ze,Ke,ft,I,Be,Re,ue,Bt,Wt;if(W()){Jn(),Bs();return}let c=cn(r),m=(ae=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?ae:!1,h=c||m||((Q=(ie=r.launcher)==null?void 0:ie.fullHeight)!=null?Q:!1),b=(ve=e.ownerDocument.defaultView)!=null?ve:window,S=(Se=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Se:!0,B=(Ue=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?Ue:640,q=b.innerWidth<=B,_=S&&q&&k;try{if(_){Cr(),qo(e,r);return}if(j&&(j=!1,Cr(),qo(e,r)),!k&&!c){J.style.height="",J.style.width="";return}if(!m&&!c){let Kt=(rt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?rt:r==null?void 0:r.launcherWidth,yt=Kt!=null?Kt:sr;J.style.width=yt,J.style.maxWidth=yt}if(xe(),!h){let Kt=b.innerHeight,yt=64,qt=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Un=Math.max(200,Kt-yt),en=Math.min(640,Un),Je=Math.max(200,en-qt);J.style.height=`${Je}px`}}finally{if(Jn(),Bs(),N&&k){let yt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((ft=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?ft:640),qt=(Be=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?Be:!1,Un=(ue=(Re=r.launcher)==null?void 0:Re.mobileFullscreen)!=null?ue:!0,en=cn(r)&&Un&&yt,Je=qt||Un&&yt&&k||en;if(Je&&!on){let Et=e.getRootNode(),nn=Et instanceof ShadowRoot?Et.host:e.closest(".persona-host");nn&&!rn&&(rn=ml(nn,(Wt=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?Wt:wn)),on=gl(e.ownerDocument)}else Je||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};Ds();let lc=(pd=e.ownerDocument.defaultView)!=null?pd:window;if(lc.addEventListener("resize",Ds),mt.push(()=>lc.removeEventListener("resize",Ds)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Jn()});c.observe(Ne),mt.push(()=>c.disconnect())}$n=Me.scrollTop;let cc=Gr(Me),Pf=()=>{let c=Me.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:Me.ownerDocument.getSelection()},Ni=()=>Fm(Pf(),Me),dc=()=>{let c=Me.scrollTop,m=Gr(Me),h=m<cc;if(cc=m,Ft()!=="follow"){$n=c,st();return}let{action:b,nextLastScrollTop:S}=Ya({following:_n.isFollowing(),currentScrollTop:c,lastScrollTop:$n,nearBottom:zo(Me,ts),userScrollThreshold:va,isAutoScrolling:pr||Mo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if($n=S,b==="resume"){Ni()||Rn();return}b==="pause"&&Ps()};if(Me.addEventListener("scroll",dc,{passive:!0}),mt.push(()=>Me.removeEventListener("scroll",dc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{mf()});c.observe(nt),c.observe(Me),mt.push(()=>c.disconnect())}let pc=()=>{Ft()==="follow"&&_n.isFollowing()&&Ni()&&Ps()},uc=Me.ownerDocument;uc.addEventListener("selectionchange",pc),mt.push(()=>{uc.removeEventListener("selectionchange",pc)});let mc=c=>{if(Ft()!=="follow")return;let m=Za({following:_n.isFollowing(),deltaY:c.deltaY,nearBottom:zo(Me,ts),resumeWhenNearBottom:!0});m==="pause"?Ps():m==="resume"&&!Ni()&&Rn()};Me.addEventListener("wheel",mc,{passive:!0}),mt.push(()=>Me.removeEventListener("wheel",mc)),jt.addEventListener("click",()=>{fn(),Me.scrollTop=Me.scrollHeight,$n=Me.scrollTop,Rn(),dn(!0),st()}),mt.push(()=>jt.remove()),mt.push(()=>{G(),fn()});let gc=()=>{A&&(Sr&&(A.removeEventListener("click",Sr),Sr=null),O()?(A.style.display="",Sr=()=>{Ut(!1,"user")},A.addEventListener("click",Sr)):A.style.display="none")};gc(),(()=>{let{clearChatButton:c}=qe;c&&c.addEventListener("click",()=>{$.clearMessages(),Er.clear(),Rn(),_o(qe.composerOverlay);try{localStorage.removeItem(Ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ms}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ms)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 m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),l!=null&&l.clear)try{let h=l.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)}p={},L.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),We==null||We.update()})})(),xt&&xt.addEventListener("submit",tc),ee==null||ee.addEventListener("keydown",rc),ee==null||ee.addEventListener("input",nc),ee==null||ee.addEventListener("paste",sc);let fc=(ud=e.ownerDocument)!=null?ud:document;fc.addEventListener("keydown",oc,!0);let hc="persona-attachment-drop-active",Ns=0,Oi=()=>{Ns=0,Ae.classList.remove(hc)},is=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&wt!==null},yc=c=>{!wi(c.dataTransfer)||!is()||(Ns++,Ns===1&&Ae.classList.add(hc))},bc=c=>{!wi(c.dataTransfer)||!is()||(Ns--,Ns<=0&&Oi())},xc=c=>{!wi(c.dataTransfer)||!is()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},vc=c=>{var h;if(!wi(c.dataTransfer)||!is())return;c.preventDefault(),c.stopPropagation(),Oi();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&wt.handleFiles(m)},ao=!0;Ae.addEventListener("dragenter",yc,ao),Ae.addEventListener("dragleave",bc,ao),e.addEventListener("dragover",xc,ao),e.addEventListener("drop",vc,ao);let Ma=e.ownerDocument,wc=c=>{is()&&c.preventDefault()},Cc=c=>{is()&&c.preventDefault()};Ma.addEventListener("dragover",wc),Ma.addEventListener("drop",Cc),mt.push(()=>{xt&&xt.removeEventListener("submit",tc),ee==null||ee.removeEventListener("keydown",rc),ee==null||ee.removeEventListener("input",nc),ee==null||ee.removeEventListener("paste",sc),fc.removeEventListener("keydown",oc,!0)}),mt.push(()=>{Ae.removeEventListener("dragenter",yc,ao),Ae.removeEventListener("dragleave",bc,ao),e.removeEventListener("dragover",xc,ao),e.removeEventListener("drop",vc,ao),Ma.removeEventListener("dragover",wc),Ma.removeEventListener("drop",Cc),Oi()}),mt.push(()=>{$.cancel()}),Zt?mt.push(()=>{Zt==null||Zt.destroy()}):sn&&mt.push(()=>{sn==null||sn.remove()});let tn={update(c){var _t,un,zn,Ir,mn,gn,rr,co,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu;let m=r.toolCall,h=r.messageActions,b=(_t=r.layout)==null?void 0:_t.messages,S=r.colorScheme,B=r.loadingIndicator,q=r.iterationDisplay,_=(un=r.features)==null?void 0:un.showReasoning,D=(zn=r.features)==null?void 0:zn.showToolCalls,ae=(Ir=r.features)==null?void 0:Ir.toolCallDisplay,ie=(mn=r.features)==null?void 0:mn.reasoningDisplay;r={...r,...c},Cr(),qo(e,r),hi(e,r),yi(e,r),Pn(),r.colorScheme!==S&&ks();let Q=bi.getForInstance(r.plugins);o.length=0,o.push(...Q),k=(rr=(gn=r.launcher)==null?void 0:gn.enabled)!=null?rr:!0,M=(xd=(co=r.launcher)==null?void 0:co.autoExpand)!=null?xd:!1,Ce=(wd=(vd=r.features)==null?void 0:vd.showReasoning)!=null?wd:!0,ke=(Ad=(Cd=r.features)==null?void 0:Cd.showToolCalls)!=null?Ad:!0,we=(Td=(Sd=r.features)==null?void 0:Sd.scrollToBottom)!=null?Td:{};let ve=Ft();le=(Md=(Ed=r.features)==null?void 0:Ed.scrollBehavior)!=null?Md:{},ve!==Ft()&&(fn(),Rn()),Xr(),st();let Oe=re;if(re=(Ld=(kd=r.features)==null?void 0:kd.showEventStreamToggle)!=null?Ld:!1,re&&!Oe){if(V||(be=new ha(oe),V=new fa(He,be),X=X!=null?X:new ya,be.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),$.setSSEEventCallback((ne,At)=>{var zt;(zt=r.onSSEEvent)==null||zt.call(r,ne,At),X==null||X.processEvent(ne,At),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(At)})})),!ut&&Pe){let ne=(Id=(Pd=r.features)==null?void 0:Pd.eventStream)==null?void 0:Id.classNames,At="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"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");ut=y("button",At),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let zt=me("activity","18px","currentColor",1.5);zt&&ut.appendChild(zt);let ot=qe.clearChatButtonWrapper,kt=qe.closeButtonWrapper,an=ot||kt;an&&an.parentNode===Pe?Pe.insertBefore(ut,an):Pe.appendChild(ut),ut.addEventListener("click",()=>{K?lr():Dr()})}}else!re&&Oe&&(lr(),ut&&(ut.remove(),ut=null),V==null||V.clear(),be==null||be.destroy(),V=null,be=null,X==null||X.reset(),X=null);if(((Rd=r.launcher)==null?void 0:Rd.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((Wd=r.launcher)==null?void 0:Wd.enabled)===!1&&sn&&(sn.remove(),sn=null),((Hd=r.launcher)==null?void 0:Hd.enabled)!==!1&&!Zt&&!sn){let{instance:ne,element:At}=bl({config:r,plugins:o,onToggle:ic});Zt=ne,ne||(sn=At),e.appendChild(At)}Zt&&Zt.update(r),Te&&((Bd=r.launcher)==null?void 0:Bd.title)!==void 0&&(Te.textContent=r.launcher.title),De&&((Dd=r.launcher)==null?void 0:Dd.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Se=(Nd=r.layout)==null?void 0:Nd.header;if((Se==null?void 0:Se.layout)!==F&&Pe){let ne=Se?ua(r,Se,{showClose:O(),onClose:()=>Ut(!1,"user")}):xo({config:r,showClose:O(),onClose:()=>Ut(!1,"user")});Xe.replaceHeader(ne),Pe=Xe.header.element,te=Xe.header.iconHolder,Te=Xe.header.headerTitle,De=Xe.header.headerSubtitle,A=Xe.header.closeButton,F=Se==null?void 0:Se.layout}else if(Se&&(te&&(te.style.display=Se.showIcon===!1?"none":""),Te&&(Te.style.display=Se.showTitle===!1?"none":""),De&&(De.style.display=Se.showSubtitle===!1?"none":""),A&&(A.style.display=Se.showCloseButton===!1?"none":""),qe.clearChatButtonWrapper)){let ne=Se.showClearChat;if(ne!==void 0){qe.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:At}=qe;At&&!At.classList.contains("persona-absolute")&&(ne?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let Ue=((Od=r.layout)==null?void 0:Od.showHeader)!==!1;Pe&&(Pe.style.display=Ue?"":"none");let ct=((Fd=r.layout)==null?void 0:Fd.showFooter)!==!1;Ne&&(Ne.style.display=ct?"":"none"),Jn(),st(),k!==R?k?Ut(M,"auto"):(N=!0,Bs()):M!==C&&Ut(M,"auto"),C=M,R=k,Ds(),gc();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(m),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((_d=r.layout)==null?void 0:_d.messages)!==JSON.stringify(b),ft=(($d=r.loadingIndicator)==null?void 0:$d.render)!==(B==null?void 0:B.render)||((jd=r.loadingIndicator)==null?void 0:jd.renderIdle)!==(B==null?void 0:B.renderIdle)||((Ud=r.loadingIndicator)==null?void 0:Ud.showBubble)!==(B==null?void 0:B.showBubble),I=r.iterationDisplay!==q,Be=((zd=(qd=r.features)==null?void 0:qd.showReasoning)!=null?zd:!0)!==(_!=null?_:!0)||((Kd=(Vd=r.features)==null?void 0:Vd.showToolCalls)!=null?Kd:!0)!==(D!=null?D:!0)||JSON.stringify((Gd=r.features)==null?void 0:Gd.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((Jd=r.features)==null?void 0:Jd.reasoningDisplay)!==JSON.stringify(ie);(Le||ze||Ke||ft||I||Be)&&$&&(Yo++,Is(nt,$.getMessages(),Z));let ue=(Xd=r.launcher)!=null?Xd:{},Bt=(Qd=ue.headerIconHidden)!=null?Qd:!1,Wt=(Zd=(Yd=r.layout)==null?void 0:Yd.header)==null?void 0:Zd.showIcon,Kt=Bt||Wt===!1,yt=ue.headerIconName,qt=(ep=ue.headerIconSize)!=null?ep:"48px";if(te){let ne=Ae.querySelector(".persona-border-b-persona-divider"),At=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Kt)te.style.display="none",ne&&At&&!ne.contains(At)&&ne.insertBefore(At,ne.firstChild);else{if(te.style.display="",te.style.height=qt,te.style.width=qt,ne&&At&&(ne.contains(te)?te.nextSibling!==At&&(te.remove(),ne.insertBefore(te,At)):ne.insertBefore(te,At)),yt){let ot=parseFloat(qt)||24,kt=me(yt,ot*.6,"currentColor",1);kt?te.replaceChildren(kt):te.textContent=(tp=ue.agentIconText)!=null?tp:"\u{1F4AC}"}else if(ue.iconUrl){let ot=te.querySelector("img");if(ot)ot.src=ue.iconUrl,ot.style.height=qt,ot.style.width=qt;else{let kt=document.createElement("img");kt.src=ue.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=qt,kt.style.width=qt,te.replaceChildren(kt)}}else{let ot=te.querySelector("svg"),kt=te.querySelector("img");(ot||kt)&&te.replaceChildren(),te.textContent=(np=ue.agentIconText)!=null?np:"\u{1F4AC}"}let zt=te.querySelector("img");zt&&(zt.style.height=qt,zt.style.width=qt)}}let Un=(op=(rp=r.layout)==null?void 0:rp.header)==null?void 0:op.showTitle,en=(ap=(sp=r.layout)==null?void 0:sp.header)==null?void 0:ap.showSubtitle;if(Te&&(Te.style.display=Un===!1?"none":""),De&&(De.style.display=en===!1?"none":""),A){((lp=(ip=r.layout)==null?void 0:ip.header)==null?void 0:lp.showCloseButton)===!1?A.style.display="none":A.style.display="";let At=(cp=ue.closeButtonSize)!=null?cp:"32px",zt=(dp=ue.closeButtonPlacement)!=null?dp:"inline";A.style.height=At,A.style.width=At;let{closeButtonWrapper:ot}=qe,kt=zt==="top-right",an=ot==null?void 0:ot.classList.contains("persona-absolute");if(ot&&kt!==an)if(ot.remove(),kt)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ae.style.position="relative",Ae.appendChild(ot);else{let at=(up=(pp=ue.clearChat)==null?void 0:pp.placement)!=null?up:"inline",ln=(gp=(mp=ue.clearChat)==null?void 0:mp.enabled)!=null?gp:!0;ot.className=ln&&at==="inline"?"":"persona-ml-auto";let Wn=Ae.querySelector(".persona-border-b-persona-divider");Wn&&Wn.appendChild(ot)}if(A.style.color=ue.closeButtonColor||Mn.actionIconColor,ue.closeButtonBackgroundColor?(A.style.backgroundColor=ue.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let at=ue.closeButtonBorderWidth||"0px",ln=ue.closeButtonBorderColor||"transparent";A.style.border=`${at} solid ${ln}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");ue.closeButtonBorderRadius?(A.style.borderRadius=ue.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(A.style.paddingLeft=ue.closeButtonPaddingX,A.style.paddingRight=ue.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),ue.closeButtonPaddingY?(A.style.paddingTop=ue.closeButtonPaddingY,A.style.paddingBottom=ue.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let xn=(fp=ue.closeButtonIconName)!=null?fp:"x",mr=(hp=ue.closeButtonIconText)!=null?hp:"\xD7";A.innerHTML="";let En=me(xn,"28px","currentColor",1);En?A.appendChild(En):A.textContent=mr;let Yt=(yp=ue.closeButtonTooltipText)!=null?yp:"Close chat",Vn=(bp=ue.closeButtonShowTooltip)!=null?bp:!0;if(A.setAttribute("aria-label",Yt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),Vn&&Yt)){let at=null,ln=()=>{if(at||!A)return;let Bo=A.ownerDocument,Os=Bo.body;if(!Os)return;at=Wr(Bo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let Fs=Wr(Bo,"div");Fs.className="persona-clear-chat-tooltip-arrow",at.appendChild(Fs);let Do=A.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(ho),at.style.left=`${Do.left+Do.width/2}px`,at.style.top=`${Do.top-8}px`,at.style.transform="translate(-50%, -100%)",Os.appendChild(at)},Wn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};ot.addEventListener("mouseenter",ln),ot.addEventListener("mouseleave",Wn),A.addEventListener("focus",ln),A.addEventListener("blur",Wn),ot._cleanupTooltip=()=>{Wn(),ot&&(ot.removeEventListener("mouseenter",ln),ot.removeEventListener("mouseleave",Wn)),A&&(A.removeEventListener("focus",ln),A.removeEventListener("blur",Wn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Et}=qe;if(Je){let ne=(xp=ue.clearChat)!=null?xp:{},At=(vp=ne.enabled)!=null?vp:!0,zt=(Cp=(wp=r.layout)==null?void 0:wp.header)==null?void 0:Cp.showClearChat,ot=zt!==void 0?zt:At,kt=(Ap=ne.placement)!=null?Ap:"inline";if(Et){Et.style.display=ot?"":"none";let{closeButtonWrapper:an}=qe;!W()&&an&&!an.classList.contains("persona-absolute")&&(ot?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let xn=kt==="top-right",mr=Et.classList.contains("persona-absolute");if(!W()&&xn!==mr&&ot){if(Et.remove(),xn)Et.className="persona-absolute persona-top-4 persona-z-50",Et.style.right="48px",Ae.style.position="relative",Ae.appendChild(Et);else{Et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Et.style.right="";let Yt=Ae.querySelector(".persona-border-b-persona-divider"),Vn=qe.closeButtonWrapper;Yt&&Vn&&Vn.parentElement===Yt?Yt.insertBefore(Et,Vn):Yt&&Yt.appendChild(Et)}let En=qe.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(xn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ot){if(!W()){let at=(Sp=ne.size)!=null?Sp:"32px";Je.style.height=at,Je.style.width=at}let an=(Tp=ne.iconName)!=null?Tp:"refresh-cw",xn=(Ep=ne.iconColor)!=null?Ep:"";Je.style.color=xn||Mn.actionIconColor,Je.innerHTML="";let mr=W()?"14px":"20px",En=me(an,mr,"currentColor",2);if(En&&Je.appendChild(En),ne.backgroundColor?(Je.style.backgroundColor=ne.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let at=ne.borderWidth||"0px",ln=ne.borderColor||"transparent";Je.style.border=`${at} solid ${ln}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");ne.borderRadius?(Je.style.borderRadius=ne.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),ne.paddingX?(Je.style.paddingLeft=ne.paddingX,Je.style.paddingRight=ne.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),ne.paddingY?(Je.style.paddingTop=ne.paddingY,Je.style.paddingBottom=ne.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Yt=(Mp=ne.tooltipText)!=null?Mp:"Clear chat",Vn=(kp=ne.showTooltip)!=null?kp:!0;if(Je.setAttribute("aria-label",Yt),Et&&(Et._cleanupTooltip&&(Et._cleanupTooltip(),delete Et._cleanupTooltip),Vn&&Yt)){let at=null,ln=()=>{if(at||!Je)return;let Bo=Je.ownerDocument,Os=Bo.body;if(!Os)return;at=Wr(Bo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let Fs=Wr(Bo,"div");Fs.className="persona-clear-chat-tooltip-arrow",at.appendChild(Fs);let Do=Je.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(ho),at.style.left=`${Do.left+Do.width/2}px`,at.style.top=`${Do.top-8}px`,at.style.transform="translate(-50%, -100%)",Os.appendChild(at)},Wn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};Et.addEventListener("mouseenter",ln),Et.addEventListener("mouseleave",Wn),Je.addEventListener("focus",ln),Je.addEventListener("blur",Wn),Et._cleanupTooltip=()=>{Wn(),Et&&(Et.removeEventListener("mouseenter",ln),Et.removeEventListener("mouseleave",Wn)),Je&&(Je.removeEventListener("focus",ln),Je.removeEventListener("blur",Wn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[xi],nr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Es.message,Es.messageAndClick];L=vi({parsers:nn,handlers:nr,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),Z=Ig(r,L,de),$.updateConfig(r),Is(nt,$.getMessages(),Z),Qo(),Zl(),Pi($.isStreaming());let qn=((Lp=r.voiceRecognition)==null?void 0:Lp.enabled)===!0,Io=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ro=((Ip=(Pp=r.voiceRecognition)==null?void 0:Pp.provider)==null?void 0:Ip.type)==="runtype";if(qn&&(Io||Ro))if(!H||!he){let ne=Tf(r.voiceRecognition,r.sendButton);ne&&(H=ne.micButton,he=ne.micButtonWrapper,It.insertBefore(he,Cn),H.addEventListener("click",Ea),H.disabled=$.isStreaming())}else{let ne=(Rp=r.voiceRecognition)!=null?Rp:{},At=(Wp=r.sendButton)!=null?Wp:{},zt=(Hp=ne.iconName)!=null?Hp:"mic",ot=(Bp=At.size)!=null?Bp:"40px",kt=(Dp=ne.iconSize)!=null?Dp:ot,an=parseFloat(kt)||24;H.style.width=kt,H.style.height=kt,H.style.minWidth=kt,H.style.minHeight=kt;let xn=(Op=(Np=ne.iconColor)!=null?Np:At.textColor)!=null?Op:"currentColor";H.innerHTML="";let mr=me(zt,an,xn,2);mr?H.appendChild(mr):H.textContent="\u{1F3A4}";let En=(Fp=ne.backgroundColor)!=null?Fp:At.backgroundColor;En?H.style.backgroundColor=En:H.style.backgroundColor="",xn?H.style.color=xn:H.style.color="var(--persona-text, #111827)",ne.borderWidth?(H.style.borderWidth=ne.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),ne.borderColor?H.style.borderColor=ne.borderColor:H.style.borderColor="",ne.paddingX?(H.style.paddingLeft=ne.paddingX,H.style.paddingRight=ne.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),ne.paddingY?(H.style.paddingTop=ne.paddingY,H.style.paddingBottom=ne.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),Vn=(_p=ne.tooltipText)!=null?_p:"Start voice recognition";if((($p=ne.showTooltip)!=null?$p:!1)&&Vn)if(Yt)Yt.textContent=Vn,Yt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Vn,he==null||he.insertBefore(ln,H)}else Yt&&(Yt.style.display="none");he.style.display="",H.disabled=$.isStreaming()}else H&&he&&(he.style.display="none",((Up=(jp=r.voiceRecognition)==null?void 0:jp.provider)==null?void 0:Up.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Lr&&so());if(((qp=r.attachments)==null?void 0:qp.enabled)===!0)if(!vt||!Fe){let ne=(zp=r.attachments)!=null?zp:{},zt=(Kp=((Vp=r.sendButton)!=null?Vp:{}).size)!=null?Kp:"40px";Ht||(Ht=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ht.style.display="none",xt.insertBefore(Ht,ee)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((Gp=ne.allowedTypes)!=null?Gp:Kr).join(","),Ye.multiple=((Jp=ne.maxFiles)!=null?Jp:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),xt.insertBefore(Ye,ee)),vt=y("div","persona-send-button-wrapper"),Fe=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Fe.type="button",Fe.setAttribute("aria-label",(Xp=ne.buttonTooltipText)!=null?Xp:"Attach file");let ot=(Qp=ne.buttonIconName)!=null?Qp:"paperclip",kt=zt,an=parseFloat(kt)||40,xn=Math.round(an*.6);Fe.style.width=kt,Fe.style.height=kt,Fe.style.minWidth=kt,Fe.style.minHeight=kt,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.style.backgroundColor="transparent",Fe.style.color="var(--persona-primary, #111827)",Fe.style.border="none",Fe.style.borderRadius="6px",Fe.style.transition="background-color 0.15s ease",Fe.addEventListener("mouseenter",()=>{Fe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Fe.addEventListener("mouseleave",()=>{Fe.style.backgroundColor="transparent"});let mr=me(ot,xn,"currentColor",1.5);mr?Fe.appendChild(mr):Fe.textContent="\u{1F4CE}",Fe.addEventListener("click",Vn=>{Vn.preventDefault(),Ye==null||Ye.click()}),vt.appendChild(Fe);let En=(Yp=ne.buttonTooltipText)!=null?Yp:"Attach file",Yt=y("div","persona-send-button-tooltip");Yt.textContent=En,vt.appendChild(Yt),it.append(vt),!wt&&Ye&&Ht&&(wt=xs.fromConfig(ne),wt.setPreviewsContainer(Ht),Ye.addEventListener("change",async()=>{wt&&(Ye!=null&&Ye.files)&&(await wt.handleFileSelect(Ye.files),Ye.value="")})),Ae.querySelector(".persona-attachment-drop-overlay")||Ae.appendChild(Rg(ne.dropOverlay))}else{vt.style.display="";let ne=(Zp=r.attachments)!=null?Zp:{};Ye&&(Ye.accept=((eu=ne.allowedTypes)!=null?eu:Kr).join(","),Ye.multiple=((tu=ne.maxFiles)!=null?tu:4)>1),wt&&wt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else vt&&(vt.style.display="none"),wt&&wt.clearAttachments(),(nu=Ae.querySelector(".persona-attachment-drop-overlay"))==null||nu.remove();let Jt=(ru=r.sendButton)!=null?ru:{},Wo=(ou=Jt.useIcon)!=null?ou:!1,io=(su=Jt.iconText)!=null?su:"\u2191",lo=Jt.iconName,zr=(au=Jt.tooltipText)!=null?au:"Send message",Ho=(iu=Jt.showTooltip)!=null?iu:!1,ur=(lu=Jt.size)!=null?lu:"40px",Pr=Jt.backgroundColor,Qe=Jt.textColor;if(Wo){if(je.style.width=ur,je.style.height=ur,je.style.minWidth=ur,je.style.minHeight=ur,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",Qe?je.style.color=Qe:je.style.color="var(--persona-button-primary-fg, #ffffff)",lo){let ne=parseFloat(ur)||24,At=(Qe==null?void 0:Qe.trim())||"currentColor",zt=me(lo,ne,At,2);zt?je.appendChild(zt):je.textContent=io}else je.textContent=io;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Pr?(je.style.backgroundColor=Pr,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(du=(cu=r.copy)==null?void 0:cu.sendButtonLabel)!=null?du:"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",Pr?(je.style.backgroundColor=Pr,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),Qe?je.style.color=Qe:je.classList.add("persona-text-white");Jt.borderWidth?(je.style.borderWidth=Jt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Jt.borderColor?je.style.borderColor=Jt.borderColor:je.style.borderColor="",Jt.paddingX?(je.style.paddingLeft=Jt.paddingX,je.style.paddingRight=Jt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Jt.paddingY?(je.style.paddingTop=Jt.paddingY,je.style.paddingBottom=Jt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Dt=Cn==null?void 0:Cn.querySelector(".persona-send-button-tooltip");if(Ho&&zr)if(Dt)Dt.textContent=zr,Dt.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=zr,Cn==null||Cn.insertBefore(ne,je)}else Dt&&(Dt.style.display="none");let Vt=(fu=(pu=r.layout)==null?void 0:pu.contentMaxWidth)!=null?fu:W()?(gu=(mu=(uu=r.launcher)==null?void 0:uu.composerBar)==null?void 0:mu.contentMaxWidth)!=null?gu:"720px":void 0;Vt?(nt.style.maxWidth=Vt,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",xt&&(xt.style.maxWidth=Vt,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Vt,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let Nt=(hu=r.statusIndicator)!=null?hu:{},Xt=(yu=Nt.visible)!=null?yu:!0;if(hn.style.display=Xt?"":"none",$){let ne=$.getStatus();$t(hn,(zt=>{var ot,kt,an,xn;return zt==="idle"?(ot=Nt.idleText)!=null?ot:vn.idle:zt==="connecting"?(kt=Nt.connectingText)!=null?kt:vn.connecting:zt==="connected"?(an=Nt.connectedText)!=null?an:vn.connected:zt==="error"?(xn=Nt.errorText)!=null?xn:vn.error:vn[zt]})(ne),Nt,ne)}hn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mt=Nt.align==="left"?"persona-text-left":Nt.align==="center"?"persona-text-center":"persona-text-right";hn.classList.add(Mt)},open(){O()&&Ut(!0,"api")},close(){O()&&Ut(!1,"api")},toggle(){O()&&Ut(!N,"api")},clearChat(){An=!1,$.clearMessages(),Er.clear(),Rn();try{localStorage.removeItem(Ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ms}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ms)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),l!=null&&l.clear)try{let m=l.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},L.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),We==null||We.update()},setMessage(c){return!ee||$.isStreaming()?!1:(!N&&O()&&Ut(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ee.value.trim();return m?(!N&&O()&&Ut(!0,"system"),ee.value="",ee.style.height="auto",$.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return $.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!N&&O()&&Ut(!0,"system"),pt.manuallyDeactivated=!1,In(),$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),Zn("user"),$.isVoiceActive()&&as()})),!0):Lr?!0:ac()?(!N&&O()&&Ut(!0,"system"),pt.manuallyDeactivated=!1,In(),Sa("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,In(),Zn("user"),qr()}),!0):!1:Lr?(pt.manuallyDeactivated=!0,In(),so("user"),!0):!1},injectMessage(c){return!N&&O()&&Ut(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!N&&O()&&Ut(!0,"system");let m=$.injectAssistantMessage(c);return Y&&(Y=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!N&&O()&&Ut(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!N&&O()&&Ut(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!N&&O()&&Ut(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!N&&O()&&Ut(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!N&&O()&&Ut(!0,"system"),$.injectTestEvent(c)},async connectStream(c,m){return $.connectStream(c,m)},__pushEventStreamEvent(c){V&&(X==null||X.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!re||!V||Dr()},hideEventStream(){K&&lr()},isEventStreamVisible(){return K},showArtifacts(){ir(r)&&(An=!1,Pn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(An=!0,Pn())},upsertArtifact(c){return ir(r)?(An=!1,$.upsertArtifact(c)):null},selectArtifact(c){ir(r)&&$.selectArtifact(c)},clearArtifacts(){ir(r)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return k&&!N&&!W()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,m,h){let S=$.getMessages().find(B=>{var q;return B.variant==="approval"&&((q=B.approval)==null?void 0:q.id)===c});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${c}`);if(S.approval.toolType==="webmcp"){$.resolveWebMcpApproval(S.id,m);return}return $.resolveApproval(S.approval,m,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(c){x(c)},on(c,m){return i.on(c,m)},off(c,m){i.off(c,m)},isOpen(){return O()&&N},isVoiceActive(){return pt.active},toggleReadAloud(c){$.toggleReadAloud(c)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(c){return $.getReadAloudState(c)},onReadAloudChange(c){return $.onReadAloudChange(c)},getState(){return{open:O()&&N,launcherEnabled:k,voiceActive:pt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!N&&O()&&Ut(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=Dl({onSubmit:async(b,S)=>{var B;$.isClientTokenMode()&&await $.submitCSATFeedback(b,S),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,S)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!N&&O()&&Ut(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=Nl({onSubmit:async(b,S)=>{var B;$.isClientTokenMode()&&await $.submitNPSFeedback(b,S),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,S)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return $.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return $.submitNPSFeedback(c,m)},destroy(){Po!=null&&(clearInterval(Po),Po=null),mt.forEach(c=>c()),fe.remove(),dt==null||dt.remove(),Zt==null||Zt.destroy(),sn==null||sn.remove(),Sr&&A.removeEventListener("click",Sr)}};if((((md=n==null?void 0:n.debugTools)!=null?md:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,mt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),mt.push(()=>{window.removeEventListener("persona:focusInput",m)}),re){let _=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===c)&&tn.showEventStream()},D=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),mt.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.showArtifacts()},b=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.hideArtifacts()},S=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||D!=null&&D.artifact&&tn.upsertArtifact(D.artifact)},B=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||typeof(D==null?void 0:D.id)=="string"&&tn.selectArtifact(D.id)},q=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",q),mt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",q)})}let tr=ew(r.persistState);if(tr&&O()){let c=tw(tr.storage),m=`${tr.keyPrefix}widget-open`,h=`${tr.keyPrefix}widget-voice`,b=`${tr.keyPrefix}widget-voice-mode`;if(c){let S=((gd=tr.persist)==null?void 0:gd.openState)&&c.getItem(m)==="true",B=((fd=tr.persist)==null?void 0:fd.voiceState)&&c.getItem(h)==="true",q=((hd=tr.persist)==null?void 0:hd.voiceState)&&c.getItem(b)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var _;if(B||q)tn.startVoiceRecognition();else if((_=tr.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(yd=tr.persist)!=null&&yd.openState&&(i.on("widget:opened",()=>{c.setItem(m,"true")}),i.on("widget:closed",()=>{c.setItem(m,"false")})),(bd=tr.persist)!=null&&bd.voiceState&&(i.on("voice:state",_=>{c.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{c.setItem(b,_.viaVoice?"true":"false")})),tr.clearOnChatClear){let _=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(b)},D=()=>_();window.addEventListener("persona:clear-chat",D),mt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return g&&O()&&setTimeout(()=>{tn.open()},0),os(),xa||Au().then(()=>{$&&(Yo++,Er.clear(),Is(nt,$.getMessages(),Z))}).catch(()=>{}),tn};var nw=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},rw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},ow=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},sw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},Wg=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Ul=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Hg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ul(e)},_l=e=>{e.style.transition=""},$l=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},jl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ci=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},aw=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},iw=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Bg=(e,t,n,r,o,s,a)=>{var v,x,E,T,L,k;let i=ar(s),d=i.reveal==="push";aw(e,t,n,r,d),iw(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",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 l=e.ownerDocument.defaultView,p=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(T=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?T:640,g=l!=null?l.innerWidth<=u:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$l(t),_l(r),Hg(r),jl(n),Ci(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((k=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?k:wn),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",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Hg(r),rw(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",$l(t),_l(r),jl(n),Ci(o,r);let M=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":P;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=M,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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",_l(r),Ul(r),Ci(o,r);let M=nw(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",R=i.side==="right"?a?-M:0:a?0:-M;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=`${P+M}px`,t.style.transition=C,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",$l(t),Ul(r),jl(n),Ci(o,r);let M=i.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",R=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",ow(r,i.maxHeight),r.style.overflow=M||R?"hidden":"visible",r.style.transition=C,M&&(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")}},lw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Wg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Wg(n,r)},destroy(){n.remove()}}},cw=(e,t)=>{var k,M,P,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.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=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(M=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||M?(C=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},v=()=>{f(),ar(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Bg(a,i,d,l,p,t,u)}),g.observe(a))},x=!1,E=()=>{Bg(a,i,d,l,p,t,u),v(),u&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,sw(a,ar(t)))},T=a.ownerDocument.defaultView,L=()=>{E()};return T==null||T.addEventListener("resize",L),ar(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),E(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let F=R.launcherEnabled?R.open:!0;u!==F&&(u=F,E())},updateConfig(R){var F,j;t=R,((j=(F=t==null?void 0:t.launcher)==null?void 0:F.enabled)!=null?j:!0)===!1&&(u=!0),E()},destroy(){T==null||T.removeEventListener("resize",L),f(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Ai=(e,t)=>cn(t)?cw(e,t):lw(e,t);var ql={},dw=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},pw=()=>{try{if(typeof ql!="undefined"&&ql.url)return new URL("../widget.css",ql.url).href}catch{}return null},Dg=(e,t)=>{let n=pw(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Ng=e=>{var E;let t=dw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Ai(t,o),a,i=[],d=(T,L)=>{var C,R;let M=!((R=(C=L==null?void 0:L.launcher)==null?void 0:C.enabled)!=null?R:!0)||cn(L),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),M&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let F=T.attachShadow({mode:"open"});F.appendChild(P),Dg(F,r)}else T.appendChild(P),Dg(T,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let T=d(s.host,o);a=Fl(T,o,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(E=e.onChatReady)==null||E.call(e);let f=T=>{g(),s.destroy(),s=Ai(t,T),o=T,u()},v={update(T){var R,F,j,W,O,N;let L={...o,...T,launcher:{...(R=o==null?void 0:o.launcher)!=null?R:{},...(F=T==null?void 0:T.launcher)!=null?F:{},dock:{...(W=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?W:{},...(N=(O=T==null?void 0:T.launcher)==null?void 0:O.dock)!=null?N:{}}}},k=cn(o),M=cn(L),P=bo(o),C=bo(L);if(k!==M||P!==C){f(L);return}o=L,s.updateConfig(o),a.update(T),l()},destroy(){g(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(T,L,k){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,k);let M=a[L];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var jg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),uw=new Set(["button","a","input","select","textarea","details","summary"]),mw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zl=/\b(product|card|item|listing|result)\b/i,Kl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,gw=3e3,fw=100;function Ug(e){let t=typeof e.className=="string"?e.className:"";if(zl.test(t)||e.id&&zl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&zl.test(r.value))return!0}return!1}function qg(e){var t;return Kl.test(((t=e.textContent)!=null?t:"").trim())}function zg(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function hw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Og(e){let t=e.match(Kl);return t?t[0]:null}function Fg(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function yw(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var bw="commerce-card",xw="result-card";function _g(e){return!Ug(e)||!qg(e)||!zg(e)&&!hw(e)?0:5200}function $g(e){var r;return!Ug(e)||qg(e)||!zg(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Vg=[{id:bw,scoreElement(e){return _g(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Kl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(_g(e)===0)return null;let{title:n,href:r}=Fg(e),o=(p=(l=Og(((d=e.textContent)!=null?d:"").trim()))!=null?l:Og(t.text))!=null?p:"",s=yw(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
112
- `)}},{id:xw,scoreElement(e){return $g(e)},formatSummary(e,t){if($g(e)===0)return null;let{title:n,href:r}=Fg(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
- `)}}];function vw(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function ww(e){var p,u,g,f,v,x,E,T,L,k,M,P,C;let t=(p=e.options)!=null?p:{},n=(g=(u=t.maxElements)!=null?u:e.maxElements)!=null?g:80,r=(v=(f=t.excludeSelector)!=null?f:e.excludeSelector)!=null?v:".persona-host",o=(E=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?E:200,s=(L=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?L:!0,a=(k=t.root)!=null?k:e.root,i=(M=t.mode)!=null?M:"structured",d=(P=t.maxCandidates)!=null?P:Math.max(500,n*10),l=(C=e.rules)!=null?C:Vg;return i==="simple"&&e.rules&&e.rules.length>0?(vw(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Vl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Cw=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Aw(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||uw.has(t)||n&&mw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Kg(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Sw(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Gg(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Vl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Cw){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Vl(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>Vl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function Tw(e){return e==="static"?fw:gw}function Jg(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:Gg(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Aw(e),attributes:Sw(e)}}function Ew(e,t,n,r){let o=Tw(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function Mw(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function kw(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(jg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Kg(l)){i=a.nextNode();continue}let u=Jg(l,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!g&&!f){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=Ew(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:x}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;Mw(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,n);f&&(p=f)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function Lw(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(jg.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Kg(d)){s=o.nextNode();continue}let p=Jg(d,e.maxTextLength),u=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!u&&!g){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Pw(e={}){var r;let t=ww(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Lw(t,n):kw(t,n):[]}var Si=100;function Iw(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
111
+ `}if(!b&&!c){let Ht="max-height: -moz-available !important; max-height: stretch !important;",zt=m?"":"padding-top: 1.25em !important;",Bt=m?"":`z-index: ${(Qe=(Hr=r.launcher)==null?void 0:Hr.zIndex)!=null?Qe:vn} !important;`;ye.style.cssText+=Ht+zt+Bt}Ke()};co(),Zo(e,r),wi(e,r),Ci(e,r);let it=[];it.push(()=>{document.removeEventListener("keydown",zr)}),it.push(()=>{lr!==null&&clearTimeout(lr)});let rn=null,on=null;it.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Wn&&it.push(()=>{Wn==null||Wn.disconnect(),Wn=null}),it.push(()=>{Gn==null||Gn(),Gn=null,ss(),_t&&(_t.remove(),_t=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),oe&&it.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),He==null||He.destroy(),He=null,V==null||V.destroy(),V=null,xe=null});let Mr=null,Ds=()=>{Mr&&(Mr(),Mr=null),r.colorScheme==="auto"&&(Mr=hl(()=>{Zo(e,r)}))};Ds(),it.push(()=>{Mr&&(Mr(),Mr=null)}),it.push(a);let Kr=(wd=r.features)==null?void 0:wd.streamAnimation;if(Kr!=null&&Kr.type&&Kr.type!=="none"){let c=fa(Kr.type,Kr.plugins);c&&(xl(c,e),it.push(()=>sg(e)))}let Do=kg(Lt),kr=null,$,as=c=>{var b,S;if(!$)return;let m=c!=null?c:$.getMessages(),h=((S=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:S.enabled)!==!1?tl(m):null;h?Do.render(h,$,ee,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(W=>W.role==="user")?Do.render([],$,ee,m):Do.render(r.suggestionChips,$,ee,m,r.suggestionChipsConfig)},dr=!1,Lr=Xm(),Gr=new Map,Pr=new Map,pr=new Map,is=0,Ma=Vo()!==null,hn=ni(),An=0,ur=null,Sn=!1,No=!1,mr=0,yn=null,Ir=null,ls=!1,Oo=!1,cs=null,Rr=!0,tt=!1,w=null,z=4,U=24,G=80,he=new Map,re={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},mt=(Ad=(Cd=r.voiceRecognition)==null?void 0:Cd.autoResume)!=null?Ad:!1,pt=c=>{i.emit("voice:state",{active:re.active,source:c,timestamp:Date.now()})},Dn=()=>{x(c=>({...c,voiceState:{active:re.active,timestamp:Date.now(),manuallyDeactivated:re.manuallyDeactivated}}))},po=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=zl(p.voiceState),m=!!c.active,h=Number((S=c.timestamp)!=null?S:0);re.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<hw&&setTimeout(()=>{var W,q;re.active||(re.manuallyDeactivated=!1,((q=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:q.type)==="runtype"?$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),pt("restore"),$.isVoiceActive()&&us()}):La("restore"))},1e3)},Jn=()=>$?zg($.getMessages()).filter(c=>!c.__skipPersist):[];function sn(c){if(!(l!=null&&l.save))return;let h={messages:c?zg(c):$?Jn():[],metadata:p,artifacts:Hn.artifacts,selectedArtifactId:Hn.selectedId};try{let b=l.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 Xn=null,Jr=()=>ye.querySelector("#persona-scroll-container")||ve,pn=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Sn=!1},Tn=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),No=!1,pn()},Nn=()=>dr&&Di()&&(Ft()!=="anchor-top"||ar()),Bi=()=>{let c=ht()||"Jump to latest",m=Nn();qt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),mr>0?(In.textContent=String(mr),In.style.display="",qt.setAttribute("aria-label",`${c} (${mr} new)`)):(In.textContent="",In.style.display="none",qt.setAttribute("aria-label",m?`${c} (response streaming below)`:c))},rc=()=>{mr!==0&&(mr=0,Bi())},Di=()=>en()?!hn.isFollowing():!So(ve,U),On=()=>{if(!Xt()||K){qt.parentNode&&qt.remove(),qt.style.display="none";return}qt.parentNode!==Se&&Se.appendChild(qt),qn();let m=Fr(ve)>0&&Di();m?Bi():rc(),qt.style.display=m?"":"none"},Ns=()=>{hn.pause()&&(Tn(),On())},uo=()=>{hn.resume(),rc(),On()},mo=(c=!1)=>{en()&&hn.isFollowing()&&(!c&&!dr||(ur!==null&&(cancelAnimationFrame(ur),ur=null),No=!0,ur=requestAnimationFrame(()=>{ur=null,No=!1,hn.isFollowing()&&kf(Jr(),c?220:140)})))},oc=(c,m,h,b=()=>!0)=>{let S=c.scrollTop,W=m(),q=W-S;if(pn(),Math.abs(q)<1){Sn=!0,c.scrollTop=W,An=c.scrollTop,Sn=!1;return}let _=performance.now();Sn=!0;let D=le=>1-Math.pow(1-le,3),de=le=>{if(!b()){pn();return}let Q=m();Q!==W&&(W=Q,q=W-S);let we=le-_,Fe=Math.min(we/h,1),Ee=D(Fe),Ze=S+q*Ee;c.scrollTop=Ze,An=c.scrollTop,Fe<1?Xn=requestAnimationFrame(de):(c.scrollTop=W,An=c.scrollTop,Xn=null,Sn=!1)};Xn=requestAnimationFrame(de)},kf=(c,m=500)=>{let h=Fr(c)-c.scrollTop;if(Math.abs(h)<1){An=c.scrollTop;return}if(Math.abs(h)>=G){pn(),Sn=!0,c.scrollTop=Fr(c),An=c.scrollTop,Sn=!1;return}oc(c,()=>Fr(c),m,()=>hn.isFollowing())},sc=()=>{let c=Jr();Sn=!0,c.scrollTop=Fr(c),An=c.scrollTop,Sn=!1,On()},ac=c=>{let m=0,h=c;for(;h&&h!==ve;)m+=h.offsetTop,h=h.offsetParent;return m},ic=()=>{var W;if($r()!=="last-user-turn")return!1;let c=(W=$==null?void 0:$.getMessages())!=null?W:[];if(c.length<2)return!1;let m=[...c].reverse().find(q=>q.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ve.querySelector(`[data-message-id="${h}"]`);if(!b)return!1;let S=Math.min(Math.max(0,ac(b)-wr()),Fr(ve));return Sn=!0,ve.scrollTop=S,An=ve.scrollTop,Sn=!1,Ft()==="follow"&&!So(ve,U)&&hn.pause(),On(),!0},lc=c=>{kn.style.height=`${Math.max(0,Math.round(c))}px`,yn&&(yn.spacerHeight=Math.max(0,c))},Os=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),pn(),yn=null,kn.style.height="0px"},Lf=c=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var D;Ir=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ve.querySelector(`[data-message-id="${m}"]`);if(!h)return;let b=ac(h),S=(D=yn==null?void 0:yn.spacerHeight)!=null?D:0,W=ve.scrollHeight-S,{targetScrollTop:q,spacerHeight:_}=tg({anchorOffsetTop:b,topOffset:wr(),viewportHeight:ve.clientHeight,contentHeight:W});yn={initialSpacerHeight:_,contentHeightAtAnchor:W,spacerHeight:_},lc(_),oc(ve,()=>q,220)})},Pf=()=>{if(en()){if(!hn.isFollowing()||So(ve,1))return;mo(!dr);return}if(yn&&yn.initialSpacerHeight>0){let c=ve.scrollHeight-yn.spacerHeight,m=ng({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:c});m!==yn.spacerHeight&&lc(m)}On()},If=c=>{let m=Ft();m==="follow"?(uo(),mo(!0)):m==="anchor-top"&&(Rr=!1,tt=!0,Lf(c))},Rf=()=>{if(Ft()==="anchor-top"){if(tt){Rr=!1;return}Rr=!0,Os(),uo(),mo(!0)}},Wf=c=>{let m=new Map;c.forEach(h=>{let b=he.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!Oo&&(Ft()!=="anchor-top"||ar())&&Di()&&(mr+=1,Bi(),On(),no(mr===1?"1 new message below.":`${mr} new messages below.`))),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),he.clear(),m.forEach((h,b)=>{he.set(b,h)})},Hf=(c,m,h)=>{var rt,Re,Pe,ze,Ke,gt;let b=document.createElement("div"),W=(()=>{var De;let I=o.find(We=>We.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(I,De)=>De==null?!1:typeof De=="string"?(I.textContent=De,!0):(I.appendChild(De),!0),_=new Set,D=new Set,de=o.some(I=>I.renderAskUserQuestion),le=[],Q=[],we=r.enableComponentStreaming!==!1,Fe=r.approval!==!1,Ee=[];if(m.forEach(I=>{var Je,Tt,nn,Zn,_n,_o,$o,gs,fs,Gt,jo,ho,yo,Qr,Uo,gr,Hr;_.add(I.id);let De=de&&xo(I),We=Fe&&I.variant==="approval"&&!!I.approval,me=!De&&I.role==="assistant"&&!I.variant&&we&&$l(I);if(!We&&pr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),pr.delete(I.id)}if(!me&&Pr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),Pr.delete(I.id)}let Wt=xo(I)?`:${(Je=I.agentMetadata)!=null&&Je.askUserQuestionAnswered?"a":"u"}:${(Tt=I.agentMetadata)!=null&&Tt.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",It=Jm(I,is)+Wt,Vt=De||We||me?null:Qm(Lr,I.id,It);if(Vt){b.appendChild(Vt.cloneNode(!0)),xo(I)&&((nn=I.toolCall)!=null&&nn.id)&&((Zn=I.agentMetadata)==null?void 0:Zn.awaitingLocalTool)===!0&&!((_n=I.agentMetadata)!=null&&_n.askUserQuestionAnswered)&&(D.add(I.toolCall.id),ta(I,r,qe.composerOverlay));return}let ft=null,jt=o.find(Qe=>!!(I.variant==="reasoning"&&Qe.renderReasoning||I.variant==="tool"&&Qe.renderToolCall||!I.variant&&Qe.renderMessage)),Fn=(_o=r.layout)==null?void 0:_o.messages;if(xo(I)&&(($o=I.agentMetadata)==null?void 0:$o.askUserQuestionAnswered)===!0){Gr.delete(I.id);let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime");return}if(Fa(I)&&((fs=(gs=r.features)==null?void 0:gs.suggestReplies)==null?void 0:fs.enabled)!==!1)return;if(xo(I)&&((jo=(Gt=r.features)==null?void 0:Gt.askUserQuestion)==null?void 0:jo.enabled)!==!1){let Qe=o.find(Ht=>typeof Ht.renderAskUserQuestion=="function");if(Qe&&wt.current){let Ht=Gr.get(I.id),zt=Ht!==It,Bt=null;if(zt){let{payload:Nt,complete:un}=vo(I),$n=I.id,Br=()=>{var mn;return(mn=wt.current)==null?void 0:mn.getMessages().find(gn=>gn.id===$n)};Bt=Qe.renderAskUserQuestion({message:I,payload:Nt,complete:un,resolve:mn=>{var er;let gn=Br();gn&&((er=wt.current)==null||er.resolveAskUserQuestion(gn,mn))},dismiss:()=>{var gn,er,bo;let mn=Br();(gn=mn==null?void 0:mn.agentMetadata)!=null&&gn.awaitingLocalTool&&((er=wt.current)==null||er.markAskUserQuestionResolved(mn),(bo=wt.current)==null||bo.resolveAskUserQuestion(mn,"(dismissed)"))},config:r})}let Jt=Ht!=null;if(zt&&Bt===null&&!Jt){((ho=I.agentMetadata)==null?void 0:ho.awaitingLocalTool)===!0&&!((yo=I.agentMetadata)!=null&&yo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),ta(I,r,qe.composerOverlay));return}let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${I.id}`,Et.setAttribute("data-wrapper-id",I.id),Et.setAttribute("data-ask-plugin-stub","true"),Et.setAttribute("data-preserve-runtime","true"),b.appendChild(Et),le.push({messageId:I.id,fingerprint:It,bubble:Bt});return}else{((Qr=I.agentMetadata)==null?void 0:Qr.awaitingLocalTool)===!0&&!((Uo=I.agentMetadata)!=null&&Uo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),ta(I,r,qe.composerOverlay));return}}else if(We){let Qe=(gr=o.find(Jt=>typeof Jt.renderApproval=="function"))!=null?gr:s,zt=pr.get(I.id)!==It,Bt=null;if(zt&&(Qe!=null&&Qe.renderApproval)){let Jt=I.id,Et=(Nt,un)=>{var Br,mn,gn;let $n=(Br=wt.current)==null?void 0:Br.getMessages().find(er=>er.id===Jt);$n!=null&&$n.approval&&($n.approval.toolType==="webmcp"?(mn=wt.current)==null||mn.resolveWebMcpApproval($n.id,Nt):(gn=wt.current)==null||gn.resolveApproval($n.approval,Nt,un))};Bt=Qe.renderApproval({message:I,defaultRenderer:()=>xi(I,r),config:r,approve:Nt=>Et("approved",Nt),deny:Nt=>Et("denied",Nt)})}if(zt&&Bt===null){let Jt=c.querySelector(`#wrapper-${I.id}`);Jt==null||Jt.removeAttribute("data-preserve-runtime"),pr.delete(I.id),ft=xi(I,r)}else{let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id=`wrapper-${I.id}`,Jt.setAttribute("data-wrapper-id",I.id),Jt.setAttribute("data-approval-plugin-stub","true"),Jt.setAttribute("data-preserve-runtime","true"),b.appendChild(Jt),Ee.push({messageId:I.id,fingerprint:It,bubble:Bt});return}}else if(jt)if(I.variant==="reasoning"&&I.reasoning&&jt.renderReasoning){if(!Te)return;ft=jt.renderReasoning({message:I,defaultRenderer:()=>kl(I,r),config:r})}else if(I.variant==="tool"&&I.toolCall&&jt.renderToolCall){if(!Le)return;ft=jt.renderToolCall({message:I,defaultRenderer:()=>Pl(I,r),config:r})}else jt.renderMessage&&(ft=jt.renderMessage({message:I,defaultRenderer:()=>{let Qe=Ca(I,h,Fn,r.messageActions,fe,{loadingIndicatorRenderer:W,widgetConfig:r});return I.role!=="user"&&Bl(Qe,I,r,$),Qe},config:r}));if(!ft&&me){let Qe=jl(I);if(Qe){let Ht=Pr.get(I.id),zt=Ht!==It,Bt=r.wrapComponentDirectiveInBubble!==!1,Jt=null;if(zt){let Et=_l(Qe,{config:r,message:I,transform:h});if(Et)if(Bt){let Nt=document.createElement("div");if(Nt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Nt.id=`bubble-${I.id}`,Nt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let un=document.createElement("div");un.className="persona-mb-3 persona-text-sm persona-leading-relaxed",un.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Nt.appendChild(un)}Nt.appendChild(Et),Jt=Nt}else{let Nt=document.createElement("div");if(Nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Nt.id=`bubble-${I.id}`,Nt.setAttribute("data-message-id",I.id),Nt.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let un=document.createElement("div");un.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",un.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Nt.appendChild(un)}Nt.appendChild(Et),Jt=Nt}}if(Jt||Ht!=null){let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${I.id}`,Et.setAttribute("data-wrapper-id",I.id),Et.setAttribute("data-component-directive-stub","true"),Et.setAttribute("data-preserve-runtime","true"),Bt||Et.classList.add("persona-w-full"),b.appendChild(Et),Q.push({messageId:I.id,fingerprint:It,bubble:Jt});return}}}if(!ft)if(I.variant==="reasoning"&&I.reasoning){if(!Te)return;ft=kl(I,r)}else if(I.variant==="tool"&&I.toolCall){if(!Le)return;ft=Pl(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;ft=xi(I,r)}else{let Qe=(Hr=r.layout)==null?void 0:Hr.messages;Qe!=null&&Qe.renderUserMessage&&I.role==="user"?ft=Qe.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):Qe!=null&&Qe.renderAssistantMessage&&I.role==="assistant"?ft=Qe.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):ft=Ca(I,h,Qe,r.messageActions,fe,{loadingIndicatorRenderer:W,widgetConfig:r}),I.role!=="user"&&ft&&Bl(ft,I,r,$)}let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${I.id}`,Zt.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Zt.classList.add("persona-justify-end"),(ft==null?void 0:ft.getAttribute("data-persona-component-directive"))==="true"&&Zt.classList.add("persona-w-full"),Zt.appendChild(ft),Ym(Lr,I.id,It,Zt),b.appendChild(Zt)}),qe.composerOverlay&&qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&Jo(qe.composerOverlay,We)}),(Re=(rt=r.features)==null?void 0:rt.toolCallDisplay)!=null&&Re.grouped){let I=[],De=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Le){De.push(We);return}De.length>1&&I.push(De),De=[]}),De.length>1&&I.push(De),I.forEach((We,me)=>{var Je,Tt;let Wt=We.map(nn=>Array.from(b.children).find(Zn=>Zn instanceof HTMLElement&&Zn.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Wt.length<2)return;let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-tool-group-${me}-${We[0].id}`,It.setAttribute("data-wrapper-id",`tool-group-${me}-${We[0].id}`);let Vt=document.createElement("div");Vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Vt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${We.length} tools`,Fn=(Tt=(Je=r.toolCall)==null?void 0:Je.renderGroupedSummary)==null?void 0:Tt.call(Je,{messages:We,toolCalls:We.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:jt,config:r});q(ft,Fn)||(ft.textContent=jt);let Zt=document.createElement("div");Zt.className="persona-tool-group-stack persona-flex persona-flex-col",Vt.append(ft,Zt),It.appendChild(Vt),Wt[0].before(It),Wt.forEach((nn,Zn)=>{let _n=document.createElement("div");_n.className="persona-tool-group-item persona-relative",_n.setAttribute("data-persona-tool-group-item","true"),Zn<Wt.length-1&&_n.setAttribute("data-persona-tool-group-connector","true"),_n.appendChild(nn),Zt.appendChild(_n)})})}Zm(Lr,_);let Ze=m.some(I=>I.role==="assistant"&&I.streaming),Ue=m[m.length-1],ct=(Ue==null?void 0:Ue.role)==="assistant"&&!Ue.streaming&&Ue.variant!=="approval";if(dr&&m.some(I=>I.role==="user")&&!Ze&&!ct){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:ks},De=o.find(me=>me.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(I)),We===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(We=r.loadingIndicator.render(I)),We===null&&(We=ks()),We){let me=document.createElement("div"),Wt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;me.className=Wt?["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(We);let It=document.createElement("div");It.className="persona-flex",It.id="wrapper-typing-indicator",It.setAttribute("data-wrapper-id","typing-indicator"),It.appendChild(me),b.appendChild(It)}}if(!dr&&m.length>0){let I=m[m.length-1],De={config:r,lastMessage:I,messageCount:m.length},We=o.find(Wt=>Wt.renderIdleIndicator),me=null;if(We!=null&&We.renderIdleIndicator&&(me=We.renderIdleIndicator(De)),me===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(me=r.loadingIndicator.renderIdle(De)),me){let Wt=document.createElement("div"),It=((gt=r.loadingIndicator)==null?void 0:gt.showBubble)!==!1;Wt.className=It?["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(" "),Wt.setAttribute("data-idle-indicator","true"),Wt.appendChild(me);let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id="wrapper-idle-indicator",Vt.setAttribute("data-wrapper-id","idle-indicator"),Vt.appendChild(Wt),b.appendChild(Vt)}}if(ei(c,b),le.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of le){let me=c.querySelector(`#wrapper-${I}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),Gr.set(I,De))}if(Gr.size>0)for(let I of Gr.keys())_.has(I)||Gr.delete(I);if(Q.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of Q){let me=c.querySelector(`#wrapper-${I}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),Pr.set(I,De))}if(Pr.size>0)for(let I of Pr.keys())_.has(I)||Pr.delete(I);if(Ee.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of Ee){let me=c.querySelector(`#wrapper-${I}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),pr.set(I,De))}if(pr.size>0)for(let I of pr.keys())_.has(I)||pr.delete(I)},Fs=(c,m,h)=>{Hf(c,m,h),io()},_s=null,Bf=()=>{var h;if(_s)return;let c=b=>{let S=b.composedPath();S.includes(ye)||dt&&S.includes(dt)||$t(!1,"user")};_s=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},cc=()=>{var m;if(!_s)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",_s,!0),_s=null};it.push(()=>cc());let $s=null,Df=()=>{var h;if($s)return;let c=b=>{b.key==="Escape"&&(b.isComposing||$t(!1,"user"))};$s=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},dc=()=>{var m;if(!$s)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",$s,!0),$s=null};it.push(()=>dc());let js=!1,pc=new Set,Nf=()=>{var m,h,b,S;let c=(b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return c||((S=r.features)==null?void 0:S.streamAnimation)},ds=()=>{var ct,rt,Re,Pe;if(!H())return;let c=qe.peekBanner,m=qe.peekTextNode;if(!c||!m)return;if(N){c.classList.remove("persona-pill-peek--visible");return}let h=(ct=$==null?void 0:$.getMessages())!=null?ct:[],b;for(let ze=h.length-1;ze>=0;ze--){let Ke=h[ze];if(Ke.role==="assistant"&&Ke.content){b=Ke;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let S=b.content,W=!!b.streaming,q=Nf(),_=si(q),D=_.type!=="none"?fa(_.type,q==null?void 0:q.plugins):null,de=((rt=D==null?void 0:D.isAnimating)==null?void 0:rt.call(D,b))===!0,le=D!==null&&(W||de);le&&D&&!pc.has(D.name)&&(xl(D,e),pc.add(D.name));let Q=le&&(D!=null&&D.containerClass)?D.containerClass:null,we=(Re=m.dataset.personaPeekStreamClass)!=null?Re:null;we&&we!==Q&&(m.classList.remove(we),delete m.dataset.personaPeekStreamClass),Q&&we!==Q&&(m.classList.add(Q),m.dataset.personaPeekStreamClass=Q),le?(m.style.setProperty("--persona-stream-step",`${_.speed}ms`),m.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Fe=le?ai(S,_.buffer,D,b,W):S;if(le&&_.placeholder==="skeleton"&&W&&(!Fe||!Fe.trim())){let ze=document.createElement("div"),Ke=ya();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),ei(m,ze)}else{let ze=Math.max(0,Fe.length-100),Ke=Fe.length>100?Fe.slice(-100):Fe,gt=Yr(Ke);if(!le||!D){let I=Fe.length>100?`\u2026${Ke}`:Ke;m.textContent!==I&&(m.textContent=I)}else{let I=gt;(D.wrap==="char"||D.wrap==="word")&&(I=ha(gt,D.wrap,`peek-${b.id}`,{skipTags:D.skipTags,startIndex:ze}));let De=document.createElement("div");if(De.innerHTML=I,D.useCaret&&Ke.length>0){let We=ii(),me=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Wt=me[me.length-1];Wt!=null&&Wt.parentNode?Wt.parentNode.insertBefore(We,Wt.nextSibling):De.appendChild(We)}ei(m,De),(Pe=D.onAfterRender)==null||Pe.call(D,{container:m,bubble:c,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let Ue=dr||js;c.classList.toggle("persona-pill-peek--visible",Ue)};if(H()){let c=qe.peekBanner;if(c){let b=S=>{S.preventDefault(),S.stopPropagation(),$t(!0,"user")};c.addEventListener("pointerdown",b),it.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{js||(js=!0,ds())},h=()=>{js&&(js=!1,ds())};J.addEventListener("pointerenter",m),J.addEventListener("pointerleave",h),it.push(()=>{J.removeEventListener("pointerenter",m),J.removeEventListener("pointerleave",h)}),dt&&(dt.addEventListener("pointerenter",m),dt.addEventListener("pointerleave",h),it.push(()=>{dt.removeEventListener("pointerenter",m),dt.removeEventListener("pointerleave",h)}))}let Of=c=>{var we,Fe,Ee,Ze,Ue,ct,rt,Re;let m=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},h=(Ee=m.expandedSize)!=null?Ee:"anchored",b=(Ze=m.bottomOffset)!=null?Ze:"16px",S=m.collapsedMaxWidth,W=(Ue=m.expandedMaxWidth)!=null?Ue:"880px",q=(ct=m.expandedTopOffset)!=null?ct:"5vh",_=(rt=m.modalMaxWidth)!=null?rt:"880px",D=(Re=m.modalMaxHeight)!=null?Re:"min(90vh, 800px)",de="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",Q=ye.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",dt){let Pe=dt.style;Pe.bottom=b,Pe.width=S!=null?S:""}if(c&&h!=="fullscreen"){if(h==="modal"){Q.top="50%",Q.left="50%",Q.transform="translate(-50%, -50%)",Q.bottom="auto",Q.right="auto",Q.width=_,Q.maxWidth=de,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${b} + ${le})`,Q.top=q,Q.width=W,Q.maxWidth=de}},Us=()=>{var D,de,le,Q,we,Fe,Ee,Ze;if(!O())return;if(H()){let ct=(le=((de=(D=r.launcher)==null?void 0:D.composerBar)!=null?de:{}).expandedSize)!=null?le:"anchored",rt=N?"expanded":"collapsed";ye.dataset.state=rt,ye.dataset.expandedSize=ct,dt&&(dt.dataset.state=rt,dt.dataset.expandedSize=ct),ye.style.removeProperty("display"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Of(N),Se.style.display=N?"flex":"none",co(),N?(Bf(),Df()):(cc(),dc()),ds();return}let c=dn(r),m=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,b=(Ze=(Ee=r.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Ze:!0,S=m.innerWidth<=h,W=b&&S&&k,q=rr(r).reveal;N?(ye.style.removeProperty("display"),ye.style.display=c?"flex":"",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0"),J.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":an&&(an.style.display="none")):(c?c&&(q==="overlay"||q==="push")&&!W?(ye.style.removeProperty("display"),ye.style.display="flex",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.setProperty("display","none","important"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.display="",ye.classList.add("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100"),J.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=c?"none":"":an&&(an.style.display=c?"none":""))},$t=(c,m="user")=>{var W,q;if(!O()||N===c)return;let h=N;N=c,Us();let b=(()=>{var Ee,Ze,Ue,ct,rt,Re,Pe,ze,Ke,gt;let _=(Ze=(Ee=r.launcher)==null?void 0:Ee.sidebarMode)!=null?Ze:!1,D=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,de=(rt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?rt:!0,le=(Pe=(Re=r.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Pe:640,Q=D.innerWidth<=le,we=dn(r)&&de&&Q,Fe=H()&&((gt=(Ke=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?gt:"fullscreen")==="fullscreen";return _||de&&Q&&k||we||Fe})();if(N&&b){if(!rn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(rn=vl(D,(q=(W=r.launcher)==null?void 0:W.zIndex)!=null?q:vn))}on||(on=wl(e.ownerDocument))}else N||(rn==null||rn(),rn=null,on==null||on(),on=null);N&&(qs(),ic()||(Ft()==="follow"?mo(!0):sc()));let S={open:N,source:m,timestamp:Date.now()};N&&!h?i.emit("widget:opened",S):!N&&h&&i.emit("widget:closed",S),i.emit("widget:state",{open:N,launcherEnabled:k,voiceActive:re.active,streaming:$.isStreaming()})},Ni=c=>{ce(c?"stop":"send"),B&&(B.disabled=c),Do.buttons.forEach(m=>{m.disabled=c}),Oe.dataset.personaComposerStreaming=c?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Oi=()=>{re.active||ee&&ee.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Oi(),200)});let uc=()=>{var h,b,S,W,q,_,D,de,le,Q,we;xr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",vr.textContent=(W=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",ee.placeholder=(_=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?_:"How can I help...";let c=ve.querySelector("[data-persona-intro-card]");if(c){let Fe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Fe?"":"none",Fe?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((le=(de=r.sendButton)==null?void 0:de.useIcon)!=null&&le)&&!($!=null&&$.isStreaming())&&(je.textContent=(we=(Q=r.copy)==null?void 0:Q.sendButtonLabel)!=null?we:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=p.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{x(m=>({...m,sessionId:c}))}});let Fo=null,Ff=()=>{Fo==null&&(Fo=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Fo),Fo=null;return}let m=Date.now();c.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=ja(m-b))})},100))};$=new ca(r,{onMessagesChanged(c){var S,W;Fs(nt,c,Z),Ff(),as(c),mo(!dr),Wf(c);let m=[...c].reverse().find(q=>q.role==="user"),h=[...c].reverse().find(q=>q.role==="assistant");c.length===0&&(Os(),Rr=!0,tt=!1),!ls||Oo?(ls=!0,cs=(S=m==null?void 0:m.id)!=null?S:null,w=(W=h==null?void 0:h.id)!=null?W:null):m&&m.id!==cs?(cs=m.id,If(m.id)):h&&h.id!==w&&Rf(),h&&(w=h.id);let b=re.lastUserMessageId;m&&m.id!==b&&(re.lastUserMessageId=m.id,i.emit("user:message",m)),re.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),sn(c),ds()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Ot(fn,(S=>{var W,q,_,D;return S==="idle"?(W=m.idleText)!=null?W:xn.idle:S==="connecting"?(q=m.connectingText)!=null?q:xn.connecting:S==="connected"?(_=m.connectedText)!=null?_:xn.connected:S==="error"?(D=m.errorText)!=null?D:xn.error:xn[S]})(c),m,c)},onStreamingChanged(c){dr=c,Ni(c),$&&Fs(nt,$.getMessages(),Z),c||mo(!0),On(),no(c?"Responding\u2026":"Response complete."),ds()},onVoiceStatusChanged(c){var m,h;if(i.emit("voice:status",{status:c,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":Xr(),us();break;case"processing":Xr(),qf();break;case"speaking":Xr(),zf();break;default:c==="idle"&&$.isBargeInActive()?(Xr(),us(),B==null||B.setAttribute("aria-label","End voice session")):(re.active=!1,Xr(),pt("system"),Dn());break}},onArtifactsState(c){Hn=c,Er(),sn()}}),wt.current=$;let Fi=null;if($.onReadAloudChange((c,m)=>{var S;so=c,ao=m,io();let h=c!=null?c:Fi;c&&(Fi=c);let b=h&&(S=$.getMessages().find(W=>W.id===h))!=null?S:null;i.emit("message:read-aloud",{messageId:h,message:b,state:m,timestamp:Date.now()}),m==="idle"&&(Fi=null)}),ls=!0,((Td=(Sd=r.voiceRecognition)==null?void 0:Sd.provider)==null?void 0:Td.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&$.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(V||r.onSSEEvent)&&$.setSSEEventCallback((c,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,c,m),X==null||X.processEvent(c,m),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(c=>{var m,h,b;if(c){if(c.metadata&&(p=zl(c.metadata),L.syncFromMetadata()),(m=c.messages)!=null&&m.length){Oo=!0;try{$.hydrateMessages(c.messages)}finally{Oo=!1}}(h=c.artifacts)!=null&&h.length&&$.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let mc=()=>{var m,h,b;!H()||N||!((b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||$t(!0,"auto")},gc=c=>{var S;if(c.preventDefault(),$.isStreaming()){$.cancel(),X==null||X.reset(),He==null||He.update();return}let m=ee.value.trim(),h=(S=vt==null?void 0:vt.hasAttachments())!=null?S:!1;if(!m&&!h)return;mc();let b;h&&(b=[],b.push(...vt.getContentParts()),m&&b.push(Ka(m))),ee.value="",ee.style.height="auto",ka(),$.sendMessage(m,{contentParts:b}),h&&vt.clearAttachments()},_f=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},_i={...ti},$i=!1,ka=()=>{_i={...ti}},$f=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),jf=c=>{if(!ee)return;$i=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),$i=!1;let m=ee.value.length;ee.setSelectionRange(m,m)},fc=()=>{$i||ka()},hc=c=>{if(ee){if(_f()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=ee.selectionStart===0&&ee.selectionEnd===0,h=Gm({direction:c.key==="ArrowUp"?"up":"down",history:$f(),currentValue:ee.value,atStart:m,state:_i});if(_i=h.state,h.handled){c.preventDefault(),h.value!==void 0&&jf(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}ka(),c.preventDefault(),je.click()}}},yc=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(Se)&&($.cancel(),X==null||X.reset(),He==null||He.update(),ka(),c.preventDefault(),c.stopImmediatePropagation())},bc=async c=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let m=bw(c.clipboardData);m.length!==0&&(c.preventDefault(),await vt.handleFiles(m))},Qn=null,Wr=!1,ps=null,lt=null,xc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,La=(c="user")=>{var W,q,_,D,de,le,Q;if(Wr||$.isStreaming())return;let m=xc();if(!m)return;Qn=new m;let b=(q=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?q:2e3;Qn.continuous=!0,Qn.interimResults=!0,Qn.lang="en-US";let S=ee.value;Qn.onresult=we=>{let Fe="",Ee="";for(let Ue=0;Ue<we.results.length;Ue++){let ct=we.results[Ue],rt=ct[0].transcript;ct.isFinal?Fe+=rt+" ":Ee=rt}let Ze=S+Fe+Ee;ee.value=Ze,ps&&clearTimeout(ps),(Fe||Ee)&&(ps=window.setTimeout(()=>{let Ue=ee.value.trim();Ue&&Qn&&Wr&&(go(),ee.value="",ee.style.height="auto",$.sendMessage(Ue,{viaVoice:!0}))},b))},Qn.onerror=we=>{we.error!=="no-speech"&&go()},Qn.onend=()=>{if(Wr){let we=ee.value.trim();we&&we!==S.trim()&&(ee.value="",ee.style.height="auto",$.sendMessage(we,{viaVoice:!0})),go()}};try{if(Qn.start(),Wr=!0,re.active=!0,c!=="system"&&(re.manuallyDeactivated=!1),pt(c),Dn(),B){let we=(_=r.voiceRecognition)!=null?_:{};lt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(D=we.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(le=we.iconSize)!=null?le:(de=r.sendButton)==null?void 0:de.size)!=null?Q:"40")||24};let Fe=we.recordingBackgroundColor,Ee=we.recordingIconColor,Ze=we.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Ee!=null?Ee:"var(--persona-voice-recording-indicator, #ffffff)",Ee){let Ue=B.querySelector("svg");Ue&&Ue.setAttribute("stroke",Ee)}Ze&&(B.style.borderColor=Ze),B.setAttribute("aria-label","Stop voice recognition")}}catch{go("system")}},go=(c="user")=>{if(Wr){if(Wr=!1,ps&&(clearTimeout(ps),ps=null),Qn){try{Qn.stop()}catch{}Qn=null}if(re.active=!1,pt(c),Dn(),B){if(B.classList.remove("persona-voice-recording"),lt){B.style.backgroundColor=lt.backgroundColor,B.style.color=lt.color,B.style.borderColor=lt.borderColor;let m=B.querySelector("svg");m&&m.setAttribute("stroke",lt.color||"currentColor"),lt=null}B.setAttribute("aria-label","Start voice recognition")}}},Uf=(c,m)=>{var rt,Re,Pe,ze,Ke,gt,I,De,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((rt=c==null?void 0:c.provider)==null?void 0:rt.type)==="runtype",S=((Re=c==null?void 0:c.provider)==null?void 0:Re.type)==="custom";if(!(h||b||S))return null;let q=y("div","persona-send-button-wrapper"),_=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let D=(Pe=c==null?void 0:c.iconName)!=null?Pe:"mic",de=(ze=m==null?void 0:m.size)!=null?ze:"40px",le=(Ke=c==null?void 0:c.iconSize)!=null?Ke:de,Q=parseFloat(le)||24,we=(gt=c==null?void 0:c.backgroundColor)!=null?gt:m==null?void 0:m.backgroundColor,Fe=(I=c==null?void 0:c.iconColor)!=null?I:m==null?void 0:m.textColor;_.style.width=le,_.style.height=le,_.style.minWidth=le,_.style.minHeight=le,_.style.fontSize="18px",_.style.lineHeight="1",Fe?_.style.color=Fe:_.style.color="var(--persona-text, #111827)";let Ze=ge(D,Q,Fe||"currentColor",1.5);Ze?_.appendChild(Ze):_.textContent="\u{1F3A4}",we?_.style.backgroundColor=we:_.style.backgroundColor="",c!=null&&c.borderWidth&&(_.style.borderWidth=c.borderWidth,_.style.borderStyle="solid"),c!=null&&c.borderColor&&(_.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(_.style.paddingLeft=c.paddingX,_.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(_.style.paddingTop=c.paddingY,_.style.paddingBottom=c.paddingY),q.appendChild(_);let Ue=(De=c==null?void 0:c.tooltipText)!=null?De:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&Ue){let me=y("div","persona-send-button-tooltip");me.textContent=Ue,q.appendChild(me)}return{micButton:_,micButtonWrapper:q}},ji=()=>{var m,h,b,S,W;if(!B||lt)return;let c=(m=r.voiceRecognition)!=null?m:{};lt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((W=(S=c.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},Ui=(c,m)=>{var W,q,_,D,de;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let b=(de=lt==null?void 0:lt.iconSize)!=null?de:parseFloat((D=(_=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?_:(q=r.sendButton)==null?void 0:q.size)!=null?D:"40")||24,S=ge(c,b,m,1.5);S&&B.appendChild(S)},Pa=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},us=()=>{var S;if(!B)return;ji();let c=(S=r.voiceRecognition)!=null?S:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,b=c.recordingBorderColor;if(Pa(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=B.querySelector("svg");W&&W.setAttribute("stroke",h)}b&&(B.style.borderColor=b),B.setAttribute("aria-label","Stop voice recognition")},qf=()=>{var _,D,de,le,Q,we,Fe,Ee;if(!B)return;ji();let c=(_=r.voiceRecognition)!=null?_:{},m=$.getVoiceInterruptionMode(),h=(D=c.processingIconName)!=null?D:"loader",b=(le=(de=c.processingIconColor)!=null?de:lt==null?void 0:lt.color)!=null?le:"",S=(we=(Q=c.processingBackgroundColor)!=null?Q:lt==null?void 0:lt.backgroundColor)!=null?we:"",W=(Ee=(Fe=c.processingBorderColor)!=null?Fe:lt==null?void 0:lt.borderColor)!=null?Ee:"";Pa(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=S,B.style.borderColor=W;let q=b||"currentColor";B.style.color=q,Ui(h,q),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},zf=()=>{var de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt,Re,Pe;if(!B)return;ji();let c=(de=r.voiceRecognition)!=null?de:{},m=$.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:h,S=(Ee=c.speakingIconColor)!=null?Ee:m==="barge-in"?(we=(Q=c.recordingIconColor)!=null?Q:lt==null?void 0:lt.color)!=null?we:"":(Fe=lt==null?void 0:lt.color)!=null?Fe:"",W=(ct=c.speakingBackgroundColor)!=null?ct:m==="barge-in"?(Ze=c.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(Ue=lt==null?void 0:lt.backgroundColor)!=null?Ue:"",q=(Pe=c.speakingBorderColor)!=null?Pe:m==="barge-in"?(rt=c.recordingBorderColor)!=null?rt:"":(Re=lt==null?void 0:lt.borderColor)!=null?Re:"";Pa(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=W,B.style.borderColor=q;let _=S||"currentColor";B.style.color=_,Ui(b,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",D),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},Xr=()=>{var c,m,h;B&&(Pa(),lt&&(B.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",B.style.color=(m=lt.color)!=null?m:"",B.style.borderColor=(h=lt.borderColor)!=null?h:"",Ui(lt.iconName,lt.color||"currentColor"),lt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Ia=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.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(()=>{re.active=!1,re.manuallyDeactivated=!0,Dn(),pt("user"),Xr()});return}$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),re.manuallyDeactivated=!$.isVoiceActive(),Dn(),pt("user"),$.isVoiceActive()?us():Xr()});return}if(Wr){let h=ee.value.trim();re.manuallyDeactivated=!0,Dn(),go("user"),h&&(ee.value="",ee.style.height="auto",$.sendMessage(h))}else re.manuallyDeactivated=!1,Dn(),La("user")};Ar=Ia,B&&(B.addEventListener("click",Ia),it.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Xr()):go("system"),B&&B.removeEventListener("click",Ia)}));let Vf=i.on("assistant:complete",()=>{mt&&(re.active||re.manuallyDeactivated||mt==="assistant"&&!re.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!re.active&&!re.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),pt("auto"),$.isVoiceActive()&&us()}):La("auto"))},600))});it.push(Vf);let Kf=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});it.push(Kf);let vc=()=>{$t(!N,"user")},Yt=null,an=null;if(k&&!H()){let{instance:c,element:m}=Tl({config:r,plugins:o,onToggle:vc});Yt=c,c||(an=m)}Yt?e.appendChild(Yt.element):an&&e.appendChild(an),Us(),as(),uc(),Ni($.isStreaming()),ic()||(Ft()==="follow"?mo(!0):sc()),po(),P&&(!k||H()?setTimeout(()=>Oi(),0):N&&setTimeout(()=>Oi(),200));let qs=()=>{var D,de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt,Re,Pe,ze,Ke,gt,I,De,We,me,Wt,It;if(H()){qn(),Us();return}let c=dn(r),m=(de=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?de:!1,h=c||m||((Q=(le=r.launcher)==null?void 0:le.fullHeight)!=null?Q:!1),b=(we=e.ownerDocument.defaultView)!=null?we:window,S=(Ee=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ee:!0,W=(Ue=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?Ue:640,q=b.innerWidth<=W,_=S&&q&&k;try{if(_){co(),Zo(e,r);return}if(j&&(j=!1,co(),Zo(e,r)),!k&&!c){J.style.height="",J.style.width="";return}if(!m&&!c){let Vt=(rt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?rt:r==null?void 0:r.launcherWidth,ft=Vt!=null?Vt:nr;J.style.width=ft,J.style.maxWidth=ft}if(Bo(),!h){let Vt=b.innerHeight,ft=64,jt=(Pe=(Re=r.launcher)==null?void 0:Re.heightOffset)!=null?Pe:0,Fn=Math.max(200,Vt-ft),Zt=Math.min(640,Fn),Je=Math.max(200,Zt-jt);J.style.height=`${Je}px`}}finally{if(qn(),Us(),N&&k){let ft=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((gt=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?gt:640),jt=(De=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?De:!1,Fn=(me=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?me:!0,Zt=dn(r)&&Fn&&ft,Je=jt||Fn&&ft&&k||Zt;if(Je&&!on){let Tt=e.getRootNode(),nn=Tt instanceof ShadowRoot?Tt.host:e.closest(".persona-host");nn&&!rn&&(rn=vl(nn,(It=(Wt=r.launcher)==null?void 0:Wt.zIndex)!=null?It:vn)),on=wl(e.ownerDocument)}else Je||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};qs();let wc=(Ed=e.ownerDocument.defaultView)!=null?Ed:window;if(wc.addEventListener("resize",qs),it.push(()=>wc.removeEventListener("resize",qs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{qn()});c.observe(Oe),it.push(()=>c.disconnect())}An=ve.scrollTop;let Cc=Fr(ve),Gf=()=>{let c=ve.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:ve.ownerDocument.getSelection()},qi=()=>eg(Gf(),ve),Ac=()=>{let c=ve.scrollTop,m=Fr(ve),h=m<Cc;if(Cc=m,!en()){An=c,On();return}let{action:b,nextLastScrollTop:S}=ri({following:hn.isFollowing(),currentScrollTop:c,lastScrollTop:An,nearBottom:So(ve,U),userScrollThreshold:z,isAutoScrolling:Sn||No||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=S,b==="resume"){qi()||uo();return}b==="pause"&&Ns()};if(ve.addEventListener("scroll",Ac,{passive:!0}),it.push(()=>ve.removeEventListener("scroll",Ac)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Pf()});c.observe(nt),c.observe(ve),it.push(()=>c.disconnect())}let Sc=()=>{en()&&hn.isFollowing()&&qi()&&Ns()},Tc=ve.ownerDocument;Tc.addEventListener("selectionchange",Sc),it.push(()=>{Tc.removeEventListener("selectionchange",Sc)});let Jf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Ec=c=>{sr()&&en()&&hn.isFollowing()&&Jf.has(c.key)&&Ns()},Mc=c=>{if(!sr()||!en()||!hn.isFollowing())return;let m=c.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&Ns()};ve.addEventListener("keydown",Ec),ve.addEventListener("focusin",Mc),it.push(()=>{ve.removeEventListener("keydown",Ec),ve.removeEventListener("focusin",Mc)});let kc=c=>{if(!en())return;let m=oi({following:hn.isFollowing(),deltaY:c.deltaY,nearBottom:So(ve,U),resumeWhenNearBottom:!0});m==="pause"?Ns():m==="resume"&&!qi()&&uo()};ve.addEventListener("wheel",kc,{passive:!0}),it.push(()=>ve.removeEventListener("wheel",kc)),qt.addEventListener("click",()=>{Os(),ve.scrollTop=ve.scrollHeight,An=ve.scrollTop,uo(),mo(!0),On()}),it.push(()=>qt.remove()),it.push(()=>{Tn(),Os()});let Lc=()=>{A&&(kr&&(A.removeEventListener("click",kr),kr=null),O()?(A.style.display="",kr=()=>{$t(!1,"user")},A.addEventListener("click",kr)):A.style.display="none")};Lc(),(()=>{let{clearChatButton:c}=qe;c&&c.addEventListener("click",()=>{$.clearMessages(),Lr.clear(),uo(),Jo(qe.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 m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),l!=null&&l.clear)try{let h=l.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)}p={},L.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),He==null||He.update()})})(),bt&&bt.addEventListener("submit",gc),ee==null||ee.addEventListener("keydown",hc),ee==null||ee.addEventListener("input",fc),ee==null||ee.addEventListener("paste",bc);let Pc=(Md=e.ownerDocument)!=null?Md:document;Pc.addEventListener("keydown",yc,!0);let Ic="persona-attachment-drop-active",zs=0,zi=()=>{zs=0,Se.classList.remove(Ic)},ms=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&vt!==null},Rc=c=>{!Ei(c.dataTransfer)||!ms()||(zs++,zs===1&&Se.classList.add(Ic))},Wc=c=>{!Ei(c.dataTransfer)||!ms()||(zs--,zs<=0&&zi())},Hc=c=>{!Ei(c.dataTransfer)||!ms()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Bc=c=>{var h;if(!Ei(c.dataTransfer)||!ms())return;c.preventDefault(),c.stopPropagation(),zi();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&vt.handleFiles(m)},fo=!0;Se.addEventListener("dragenter",Rc,fo),Se.addEventListener("dragleave",Wc,fo),e.addEventListener("dragover",Hc,fo),e.addEventListener("drop",Bc,fo);let Ra=e.ownerDocument,Dc=c=>{ms()&&c.preventDefault()},Nc=c=>{ms()&&c.preventDefault()};Ra.addEventListener("dragover",Dc),Ra.addEventListener("drop",Nc),it.push(()=>{bt&&bt.removeEventListener("submit",gc),ee==null||ee.removeEventListener("keydown",hc),ee==null||ee.removeEventListener("input",fc),ee==null||ee.removeEventListener("paste",bc),Pc.removeEventListener("keydown",yc,!0)}),it.push(()=>{Se.removeEventListener("dragenter",Rc,fo),Se.removeEventListener("dragleave",Wc,fo),e.removeEventListener("dragover",Hc,fo),e.removeEventListener("drop",Bc,fo),Ra.removeEventListener("dragover",Dc),Ra.removeEventListener("drop",Nc),zi()}),it.push(()=>{$.cancel()}),Yt?it.push(()=>{Yt==null||Yt.destroy()}):an&&it.push(()=>{an==null||an.remove()});let tn={update(c){var Nt,un,$n,Br,mn,gn,er,bo,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru;let m=r.toolCall,h=r.messageActions,b=(Nt=r.layout)==null?void 0:Nt.messages,S=r.colorScheme,W=r.loadingIndicator,q=r.iterationDisplay,_=(un=r.features)==null?void 0:un.showReasoning,D=($n=r.features)==null?void 0:$n.showToolCalls,de=(Br=r.features)==null?void 0:Br.toolCallDisplay,le=(mn=r.features)==null?void 0:mn.reasoningDisplay;r={...r,...c},co(),Zo(e,r),wi(e,r),Ci(e,r),Er(),r.colorScheme!==S&&Ds();let Q=Ai.getForInstance(r.plugins);o.length=0,o.push(...Q),k=(er=(gn=r.launcher)==null?void 0:gn.enabled)!=null?er:!0,M=(Hd=(bo=r.launcher)==null?void 0:bo.autoExpand)!=null?Hd:!1,Te=(Dd=(Bd=r.features)==null?void 0:Bd.showReasoning)!=null?Dd:!0,Le=(Od=(Nd=r.features)==null?void 0:Nd.showToolCalls)!=null?Od:!0,Ae=(_d=(Fd=r.features)==null?void 0:Fd.scrollToBottom)!=null?_d:{};let we=Ft();se=(jd=($d=r.features)==null?void 0:$d.scrollBehavior)!=null?jd:{},we!==Ft()&&(Os(),uo()),ro(),On();let Fe=oe;if(oe=(qd=(Ud=r.features)==null?void 0:Ud.showEventStreamToggle)!=null?qd:!1,oe&&!Fe){if(V||(xe=new Sa(ae),V=new Aa(Be,xe),X=X!=null?X:new Ta,xe.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),$.setSSEEventCallback((ne,Ct)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,ne,Ct),X==null||X.processEvent(ne,Ct),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Ct)})})),!ut&&Ie){let ne=(Vd=(zd=r.features)==null?void 0:zd.eventStream)==null?void 0:Vd.classNames,Ct="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"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");ut=y("button",Ct),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ut=ge("activity","18px","currentColor",1.5);Ut&&ut.appendChild(Ut);let ot=qe.clearChatButtonWrapper,Mt=qe.closeButtonWrapper,ln=ot||Mt;ln&&ln.parentNode===Ie?Ie.insertBefore(ut,ln):Ie.appendChild(ut),ut.addEventListener("click",()=>{K?cr():Ur()})}}else!oe&&Fe&&(cr(),ut&&(ut.remove(),ut=null),V==null||V.clear(),xe==null||xe.destroy(),V=null,xe=null,X==null||X.reset(),X=null);if(((Kd=r.launcher)==null?void 0:Kd.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((Gd=r.launcher)==null?void 0:Gd.enabled)===!1&&an&&(an.remove(),an=null),((Jd=r.launcher)==null?void 0:Jd.enabled)!==!1&&!Yt&&!an){let{instance:ne,element:Ct}=Tl({config:r,plugins:o,onToggle:vc});Yt=ne,ne||(an=Ct),e.appendChild(Ct)}Yt&&Yt.update(r),Me&&((Xd=r.launcher)==null?void 0:Xd.title)!==void 0&&(Me.textContent=r.launcher.title),Ne&&((Qd=r.launcher)==null?void 0:Qd.subtitle)!==void 0&&(Ne.textContent=r.launcher.subtitle);let Ee=(Yd=r.layout)==null?void 0:Yd.header;if((Ee==null?void 0:Ee.layout)!==F&&Ie){let ne=Ee?va(r,Ee,{showClose:O(),onClose:()=>$t(!1,"user")}):ko({config:r,showClose:O(),onClose:()=>$t(!1,"user")});Xe.replaceHeader(ne),Ie=Xe.header.element,te=Xe.header.iconHolder,Me=Xe.header.headerTitle,Ne=Xe.header.headerSubtitle,A=Xe.header.closeButton,F=Ee==null?void 0:Ee.layout}else if(Ee&&(te&&(te.style.display=Ee.showIcon===!1?"none":""),Me&&(Me.style.display=Ee.showTitle===!1?"none":""),Ne&&(Ne.style.display=Ee.showSubtitle===!1?"none":""),A&&(A.style.display=Ee.showCloseButton===!1?"none":""),qe.clearChatButtonWrapper)){let ne=Ee.showClearChat;if(ne!==void 0){qe.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Ct}=qe;Ct&&!Ct.classList.contains("persona-absolute")&&(ne?Ct.classList.remove("persona-ml-auto"):Ct.classList.add("persona-ml-auto"))}}let Ue=((Zd=r.layout)==null?void 0:Zd.showHeader)!==!1;Ie&&(Ie.style.display=Ue?"":"none");let ct=((ep=r.layout)==null?void 0:ep.showFooter)!==!1;Oe&&(Oe.style.display=ct?"":"none"),qn(),On(),k!==R?k?$t(M,"auto"):(N=!0,Us()):M!==C&&$t(M,"auto"),C=M,R=k,qs(),Lc();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(m),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((tp=r.layout)==null?void 0:tp.messages)!==JSON.stringify(b),gt=((np=r.loadingIndicator)==null?void 0:np.render)!==(W==null?void 0:W.render)||((rp=r.loadingIndicator)==null?void 0:rp.renderIdle)!==(W==null?void 0:W.renderIdle)||((op=r.loadingIndicator)==null?void 0:op.showBubble)!==(W==null?void 0:W.showBubble),I=r.iterationDisplay!==q,De=((ap=(sp=r.features)==null?void 0:sp.showReasoning)!=null?ap:!0)!==(_!=null?_:!0)||((lp=(ip=r.features)==null?void 0:ip.showToolCalls)!=null?lp:!0)!==(D!=null?D:!0)||JSON.stringify((cp=r.features)==null?void 0:cp.toolCallDisplay)!==JSON.stringify(de)||JSON.stringify((dp=r.features)==null?void 0:dp.reasoningDisplay)!==JSON.stringify(le);(Pe||ze||Ke||gt||I||De)&&$&&(is++,Fs(nt,$.getMessages(),Z));let me=(pp=r.launcher)!=null?pp:{},Wt=(up=me.headerIconHidden)!=null?up:!1,It=(gp=(mp=r.layout)==null?void 0:mp.header)==null?void 0:gp.showIcon,Vt=Wt||It===!1,ft=me.headerIconName,jt=(fp=me.headerIconSize)!=null?fp:"48px";if(te){let ne=Se.querySelector(".persona-border-b-persona-divider"),Ct=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Vt)te.style.display="none",ne&&Ct&&!ne.contains(Ct)&&ne.insertBefore(Ct,ne.firstChild);else{if(te.style.display="",te.style.height=jt,te.style.width=jt,ne&&Ct&&(ne.contains(te)?te.nextSibling!==Ct&&(te.remove(),ne.insertBefore(te,Ct)):ne.insertBefore(te,Ct)),ft){let ot=parseFloat(jt)||24,Mt=ge(ft,ot*.6,"currentColor",1);Mt?te.replaceChildren(Mt):te.textContent=(hp=me.agentIconText)!=null?hp:"\u{1F4AC}"}else if(me.iconUrl){let ot=te.querySelector("img");if(ot)ot.src=me.iconUrl,ot.style.height=jt,ot.style.width=jt;else{let Mt=document.createElement("img");Mt.src=me.iconUrl,Mt.alt="",Mt.className="persona-rounded-xl persona-object-cover",Mt.style.height=jt,Mt.style.width=jt,te.replaceChildren(Mt)}}else{let ot=te.querySelector("svg"),Mt=te.querySelector("img");(ot||Mt)&&te.replaceChildren(),te.textContent=(yp=me.agentIconText)!=null?yp:"\u{1F4AC}"}let Ut=te.querySelector("img");Ut&&(Ut.style.height=jt,Ut.style.width=jt)}}let Fn=(xp=(bp=r.layout)==null?void 0:bp.header)==null?void 0:xp.showTitle,Zt=(wp=(vp=r.layout)==null?void 0:vp.header)==null?void 0:wp.showSubtitle;if(Me&&(Me.style.display=Fn===!1?"none":""),Ne&&(Ne.style.display=Zt===!1?"none":""),A){((Ap=(Cp=r.layout)==null?void 0:Cp.header)==null?void 0:Ap.showCloseButton)===!1?A.style.display="none":A.style.display="";let Ct=(Sp=me.closeButtonSize)!=null?Sp:"32px",Ut=(Tp=me.closeButtonPlacement)!=null?Tp:"inline";A.style.height=Ct,A.style.width=Ct;let{closeButtonWrapper:ot}=qe,Mt=Ut==="top-right",ln=ot==null?void 0:ot.classList.contains("persona-absolute");if(ot&&Mt!==ln)if(ot.remove(),Mt)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Se.style.position="relative",Se.appendChild(ot);else{let st=(Mp=(Ep=me.clearChat)==null?void 0:Ep.placement)!=null?Mp:"inline",cn=(Lp=(kp=me.clearChat)==null?void 0:kp.enabled)!=null?Lp:!0;ot.className=cn&&st==="inline"?"":"persona-ml-auto";let Pn=Se.querySelector(".persona-border-b-persona-divider");Pn&&Pn.appendChild(ot)}if(A.style.color=me.closeButtonColor||Mn.actionIconColor,me.closeButtonBackgroundColor?(A.style.backgroundColor=me.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let st=me.closeButtonBorderWidth||"0px",cn=me.closeButtonBorderColor||"transparent";A.style.border=`${st} solid ${cn}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");me.closeButtonBorderRadius?(A.style.borderRadius=me.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(A.style.paddingLeft=me.closeButtonPaddingX,A.style.paddingRight=me.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),me.closeButtonPaddingY?(A.style.paddingTop=me.closeButtonPaddingY,A.style.paddingBottom=me.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let bn=(Pp=me.closeButtonIconName)!=null?Pp:"x",fr=(Ip=me.closeButtonIconText)!=null?Ip:"\xD7";A.innerHTML="";let En=ge(bn,"28px","currentColor",1);En?A.appendChild(En):A.textContent=fr;let Qt=(Rp=me.closeButtonTooltipText)!=null?Rp:"Close chat",jn=(Wp=me.closeButtonShowTooltip)!=null?Wp:!0;if(A.setAttribute("aria-label",Qt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),jn&&Qt)){let st=null,cn=()=>{if(st||!A)return;let qo=A.ownerDocument,Vs=qo.body;if(!Vs)return;st=Nr(qo,"div","persona-clear-chat-tooltip"),st.textContent=Qt;let Ks=Nr(qo,"div");Ks.className="persona-clear-chat-tooltip-arrow",st.appendChild(Ks);let zo=A.getBoundingClientRect();st.style.position="fixed",st.style.zIndex=String(To),st.style.left=`${zo.left+zo.width/2}px`,st.style.top=`${zo.top-8}px`,st.style.transform="translate(-50%, -100%)",Vs.appendChild(st)},Pn=()=>{st&&st.parentNode&&(st.parentNode.removeChild(st),st=null)};ot.addEventListener("mouseenter",cn),ot.addEventListener("mouseleave",Pn),A.addEventListener("focus",cn),A.addEventListener("blur",Pn),ot._cleanupTooltip=()=>{Pn(),ot&&(ot.removeEventListener("mouseenter",cn),ot.removeEventListener("mouseleave",Pn)),A&&(A.removeEventListener("focus",cn),A.removeEventListener("blur",Pn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Tt}=qe;if(Je){let ne=(Hp=me.clearChat)!=null?Hp:{},Ct=(Bp=ne.enabled)!=null?Bp:!0,Ut=(Np=(Dp=r.layout)==null?void 0:Dp.header)==null?void 0:Np.showClearChat,ot=Ut!==void 0?Ut:Ct,Mt=(Op=ne.placement)!=null?Op:"inline";if(Tt){Tt.style.display=ot?"":"none";let{closeButtonWrapper:ln}=qe;!H()&&ln&&!ln.classList.contains("persona-absolute")&&(ot?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let bn=Mt==="top-right",fr=Tt.classList.contains("persona-absolute");if(!H()&&bn!==fr&&ot){if(Tt.remove(),bn)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",Se.style.position="relative",Se.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let Qt=Se.querySelector(".persona-border-b-persona-divider"),jn=qe.closeButtonWrapper;Qt&&jn&&jn.parentElement===Qt?Qt.insertBefore(Tt,jn):Qt&&Qt.appendChild(Tt)}let En=qe.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(bn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ot){if(!H()){let st=(Fp=ne.size)!=null?Fp:"32px";Je.style.height=st,Je.style.width=st}let ln=(_p=ne.iconName)!=null?_p:"refresh-cw",bn=($p=ne.iconColor)!=null?$p:"";Je.style.color=bn||Mn.actionIconColor,Je.innerHTML="";let fr=H()?"14px":"20px",En=ge(ln,fr,"currentColor",2);if(En&&Je.appendChild(En),ne.backgroundColor?(Je.style.backgroundColor=ne.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let st=ne.borderWidth||"0px",cn=ne.borderColor||"transparent";Je.style.border=`${st} solid ${cn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");ne.borderRadius?(Je.style.borderRadius=ne.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),ne.paddingX?(Je.style.paddingLeft=ne.paddingX,Je.style.paddingRight=ne.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),ne.paddingY?(Je.style.paddingTop=ne.paddingY,Je.style.paddingBottom=ne.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(jp=ne.tooltipText)!=null?jp:"Clear chat",jn=(Up=ne.showTooltip)!=null?Up:!0;if(Je.setAttribute("aria-label",Qt),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),jn&&Qt)){let st=null,cn=()=>{if(st||!Je)return;let qo=Je.ownerDocument,Vs=qo.body;if(!Vs)return;st=Nr(qo,"div","persona-clear-chat-tooltip"),st.textContent=Qt;let Ks=Nr(qo,"div");Ks.className="persona-clear-chat-tooltip-arrow",st.appendChild(Ks);let zo=Je.getBoundingClientRect();st.style.position="fixed",st.style.zIndex=String(To),st.style.left=`${zo.left+zo.width/2}px`,st.style.top=`${zo.top-8}px`,st.style.transform="translate(-50%, -100%)",Vs.appendChild(st)},Pn=()=>{st&&st.parentNode&&(st.parentNode.removeChild(st),st=null)};Tt.addEventListener("mouseenter",cn),Tt.addEventListener("mouseleave",Pn),Je.addEventListener("focus",cn),Je.addEventListener("blur",Pn),Tt._cleanupTooltip=()=>{Pn(),Tt&&(Tt.removeEventListener("mouseenter",cn),Tt.removeEventListener("mouseleave",Pn)),Je&&(Je.removeEventListener("focus",cn),Je.removeEventListener("blur",Pn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Si],Zn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Rs.message,Rs.messageAndClick];L=Ti({parsers:nn,handlers:Zn,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),Z=Vg(r,L,pe),$.updateConfig(r),Fs(nt,$.getMessages(),Z),as(),uc(),Ni($.isStreaming());let _n=((qp=r.voiceRecognition)==null?void 0:qp.enabled)===!0,_o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((Vp=(zp=r.voiceRecognition)==null?void 0:zp.provider)==null?void 0:Vp.type)==="runtype";if(_n&&(_o||$o))if(!B||!be){let ne=Uf(r.voiceRecognition,r.sendButton);ne&&(B=ne.micButton,be=ne.micButtonWrapper,Pt.insertBefore(be,wn),B.addEventListener("click",Ia),B.disabled=$.isStreaming())}else{let ne=(Kp=r.voiceRecognition)!=null?Kp:{},Ct=(Gp=r.sendButton)!=null?Gp:{},Ut=(Jp=ne.iconName)!=null?Jp:"mic",ot=(Xp=Ct.size)!=null?Xp:"40px",Mt=(Qp=ne.iconSize)!=null?Qp:ot,ln=parseFloat(Mt)||24;B.style.width=Mt,B.style.height=Mt,B.style.minWidth=Mt,B.style.minHeight=Mt;let bn=(Zp=(Yp=ne.iconColor)!=null?Yp:Ct.textColor)!=null?Zp:"currentColor";B.innerHTML="";let fr=ge(Ut,ln,bn,2);fr?B.appendChild(fr):B.textContent="\u{1F3A4}";let En=(eu=ne.backgroundColor)!=null?eu:Ct.backgroundColor;En?B.style.backgroundColor=En:B.style.backgroundColor="",bn?B.style.color=bn:B.style.color="var(--persona-text, #111827)",ne.borderWidth?(B.style.borderWidth=ne.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),ne.borderColor?B.style.borderColor=ne.borderColor:B.style.borderColor="",ne.paddingX?(B.style.paddingLeft=ne.paddingX,B.style.paddingRight=ne.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),ne.paddingY?(B.style.paddingTop=ne.paddingY,B.style.paddingBottom=ne.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Qt=be==null?void 0:be.querySelector(".persona-send-button-tooltip"),jn=(tu=ne.tooltipText)!=null?tu:"Start voice recognition";if(((nu=ne.showTooltip)!=null?nu:!1)&&jn)if(Qt)Qt.textContent=jn,Qt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=jn,be==null||be.insertBefore(cn,B)}else Qt&&(Qt.style.display="none");be.style.display="",B.disabled=$.isStreaming()}else B&&be&&(be.style.display="none",((ou=(ru=r.voiceRecognition)==null?void 0:ru.provider)==null?void 0:ou.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Wr&&go());if(((su=r.attachments)==null?void 0:su.enabled)===!0)if(!xt||!_e){let ne=(au=r.attachments)!=null?au:{},Ut=(lu=((iu=r.sendButton)!=null?iu:{}).size)!=null?lu:"40px";Rt||(Rt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Rt.style.display="none",bt.insertBefore(Rt,ee)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((cu=ne.allowedTypes)!=null?cu:Zr).join(","),Ye.multiple=((du=ne.maxFiles)!=null?du:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),bt.insertBefore(Ye,ee)),xt=y("div","persona-send-button-wrapper"),_e=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),_e.type="button",_e.setAttribute("aria-label",(pu=ne.buttonTooltipText)!=null?pu:"Attach file");let ot=(uu=ne.buttonIconName)!=null?uu:"paperclip",Mt=Ut,ln=parseFloat(Mt)||40,bn=Math.round(ln*.6);_e.style.width=Mt,_e.style.height=Mt,_e.style.minWidth=Mt,_e.style.minHeight=Mt,_e.style.fontSize="18px",_e.style.lineHeight="1",_e.style.backgroundColor="transparent",_e.style.color="var(--persona-primary, #111827)",_e.style.border="none",_e.style.borderRadius="6px",_e.style.transition="background-color 0.15s ease",_e.addEventListener("mouseenter",()=>{_e.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),_e.addEventListener("mouseleave",()=>{_e.style.backgroundColor="transparent"});let fr=ge(ot,bn,"currentColor",1.5);fr?_e.appendChild(fr):_e.textContent="\u{1F4CE}",_e.addEventListener("click",jn=>{jn.preventDefault(),Ye==null||Ye.click()}),xt.appendChild(_e);let En=(mu=ne.buttonTooltipText)!=null?mu:"Attach file",Qt=y("div","persona-send-button-tooltip");Qt.textContent=En,xt.appendChild(Qt),at.append(xt),!vt&&Ye&&Rt&&(vt=Ts.fromConfig(ne),vt.setPreviewsContainer(Rt),Ye.addEventListener("change",async()=>{vt&&(Ye!=null&&Ye.files)&&(await vt.handleFileSelect(Ye.files),Ye.value="")})),Se.querySelector(".persona-attachment-drop-overlay")||Se.appendChild(Kg(ne.dropOverlay))}else{xt.style.display="";let ne=(gu=r.attachments)!=null?gu:{};Ye&&(Ye.accept=((fu=ne.allowedTypes)!=null?fu:Zr).join(","),Ye.multiple=((hu=ne.maxFiles)!=null?hu:4)>1),vt&&vt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else xt&&(xt.style.display="none"),vt&&vt.clearAttachments(),(yu=Se.querySelector(".persona-attachment-drop-overlay"))==null||yu.remove();let Gt=(bu=r.sendButton)!=null?bu:{},jo=(xu=Gt.useIcon)!=null?xu:!1,ho=(vu=Gt.iconText)!=null?vu:"\u2191",yo=Gt.iconName,Qr=(wu=Gt.tooltipText)!=null?wu:"Send message",Uo=(Cu=Gt.showTooltip)!=null?Cu:!1,gr=(Au=Gt.size)!=null?Au:"40px",Hr=Gt.backgroundColor,Qe=Gt.textColor;if(jo){if(je.style.width=gr,je.style.height=gr,je.style.minWidth=gr,je.style.minHeight=gr,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",Qe?je.style.color=Qe:je.style.color="var(--persona-button-primary-fg, #ffffff)",yo){let ne=parseFloat(gr)||24,Ct=(Qe==null?void 0:Qe.trim())||"currentColor",Ut=ge(yo,ne,Ct,2);Ut?je.appendChild(Ut):je.textContent=ho}else je.textContent=ho;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Hr?(je.style.backgroundColor=Hr,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(Tu=(Su=r.copy)==null?void 0:Su.sendButtonLabel)!=null?Tu:"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",Hr?(je.style.backgroundColor=Hr,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),Qe?je.style.color=Qe: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 Ht=wn==null?void 0:wn.querySelector(".persona-send-button-tooltip");if(Uo&&Qr)if(Ht)Ht.textContent=Qr,Ht.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Qr,wn==null||wn.insertBefore(ne,je)}else Ht&&(Ht.style.display="none");let zt=(Pu=(Eu=r.layout)==null?void 0:Eu.contentMaxWidth)!=null?Pu:H()?(Lu=(ku=(Mu=r.launcher)==null?void 0:Mu.composerBar)==null?void 0:ku.contentMaxWidth)!=null?Lu:"720px":void 0;zt?(nt.style.maxWidth=zt,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",bt&&(bt.style.maxWidth=zt,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Lt&&(Lt.style.maxWidth=zt,Lt.style.marginLeft="auto",Lt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""),Lt&&(Lt.style.maxWidth="",Lt.style.marginLeft="",Lt.style.marginRight=""));let Bt=(Iu=r.statusIndicator)!=null?Iu:{},Jt=(Ru=Bt.visible)!=null?Ru:!0;if(fn.style.display=Jt?"":"none",$){let ne=$.getStatus();Ot(fn,(Ut=>{var ot,Mt,ln,bn;return Ut==="idle"?(ot=Bt.idleText)!=null?ot:xn.idle:Ut==="connecting"?(Mt=Bt.connectingText)!=null?Mt:xn.connecting:Ut==="connected"?(ln=Bt.connectedText)!=null?ln:xn.connected:Ut==="error"?(bn=Bt.errorText)!=null?bn:xn.error:xn[Ut]})(ne),Bt,ne)}fn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=Bt.align==="left"?"persona-text-left":Bt.align==="center"?"persona-text-center":"persona-text-right";fn.classList.add(Et)},open(){O()&&$t(!0,"api")},close(){O()&&$t(!1,"api")},toggle(){O()&&$t(!N,"api")},clearChat(){Cn=!1,$.clearMessages(),Lr.clear(),uo();try{localStorage.removeItem(Ws),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ws}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ws)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),l!=null&&l.clear)try{let m=l.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},L.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),He==null||He.update()},setMessage(c){return!ee||$.isStreaming()?!1:(!N&&O()&&$t(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ee.value.trim();return m?(!N&&O()&&$t(!0,"system"),ee.value="",ee.style.height="auto",$.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return $.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!N&&O()&&$t(!0,"system"),re.manuallyDeactivated=!1,Dn(),$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),pt("user"),$.isVoiceActive()&&us()})),!0):Wr?!0:xc()?(!N&&O()&&$t(!0,"system"),re.manuallyDeactivated=!1,Dn(),La("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{re.active=!1,re.manuallyDeactivated=!0,Dn(),pt("user"),Xr()}),!0):!1:Wr?(re.manuallyDeactivated=!0,Dn(),go("user"),!0):!1},injectMessage(c){return!N&&O()&&$t(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!N&&O()&&$t(!0,"system");let m=$.injectAssistantMessage(c);return Y&&(Y=!1,ke&&(clearTimeout(ke),ke=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!N&&O()&&$t(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!N&&O()&&$t(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!N&&O()&&$t(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!N&&O()&&$t(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!N&&O()&&$t(!0,"system"),$.injectTestEvent(c)},async connectStream(c,m){return $.connectStream(c,m)},__pushEventStreamEvent(c){V&&(X==null||X.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!oe||!V||Ur()},hideEventStream(){K&&cr()},isEventStreamVisible(){return K},showArtifacts(){or(r)&&(Cn=!1,Er(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){or(r)&&(Cn=!0,Er())},upsertArtifact(c){return or(r)?(Cn=!1,$.upsertArtifact(c)):null},selectArtifact(c){or(r)&&$.selectArtifact(c)},clearArtifacts(){or(r)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return k&&!N&&!H()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,m,h){let S=$.getMessages().find(W=>{var q;return W.variant==="approval"&&((q=W.approval)==null?void 0:q.id)===c});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${c}`);if(S.approval.toolType==="webmcp"){$.resolveWebMcpApproval(S.id,m);return}return $.resolveApproval(S.approval,m,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(c){x(c)},on(c,m){return i.on(c,m)},off(c,m){i.off(c,m)},isOpen(){return O()&&N},isVoiceActive(){return re.active},toggleReadAloud(c){$.toggleReadAloud(c)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(c){return $.getReadAloudState(c)},onReadAloudChange(c){return $.onReadAloudChange(c)},getState(){return{open:O()&&N,launcherEnabled:k,voiceActive:re.active,streaming:$.isStreaming()}},showCSATFeedback(c){!N&&O()&&$t(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=Ul({onSubmit:async(b,S)=>{var W;$.isClientTokenMode()&&await $.submitCSATFeedback(b,S),(W=c==null?void 0:c.onSubmit)==null||W.call(c,b,S)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!N&&O()&&$t(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=ql({onSubmit:async(b,S)=>{var W;$.isClientTokenMode()&&await $.submitNPSFeedback(b,S),(W=c==null?void 0:c.onSubmit)==null||W.call(c,b,S)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return $.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return $.submitNPSFeedback(c,m)},destroy(){Fo!=null&&(clearInterval(Fo),Fo=null),it.forEach(c=>c()),ye.remove(),dt==null||dt.remove(),Yt==null||Yt.destroy(),an==null||an.remove(),kr&&A.removeEventListener("click",kr)}};if((((kd=n==null?void 0:n.debugTools)!=null?kd:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,it.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),it.push(()=>{window.removeEventListener("persona:focusInput",m)}),oe){let _=de=>{let le=de.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&tn.showEventStream()},D=de=>{let le=de.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),it.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.showArtifacts()},b=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.hideArtifacts()},S=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||D!=null&&D.artifact&&tn.upsertArtifact(D.artifact)},W=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||typeof(D==null?void 0:D.id)=="string"&&tn.selectArtifact(D.id)},q=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",q),it.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",q)})}let Yn=xw(r.persistState);if(Yn&&O()){let c=vw(Yn.storage),m=`${Yn.keyPrefix}widget-open`,h=`${Yn.keyPrefix}widget-voice`,b=`${Yn.keyPrefix}widget-voice-mode`;if(c){let S=((Ld=Yn.persist)==null?void 0:Ld.openState)&&c.getItem(m)==="true",W=((Pd=Yn.persist)==null?void 0:Pd.voiceState)&&c.getItem(h)==="true",q=((Id=Yn.persist)==null?void 0:Id.voiceState)&&c.getItem(b)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var _;if(W||q)tn.startVoiceRecognition();else if((_=Yn.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(Rd=Yn.persist)!=null&&Rd.openState&&(i.on("widget:opened",()=>{c.setItem(m,"true")}),i.on("widget:closed",()=>{c.setItem(m,"false")})),(Wd=Yn.persist)!=null&&Wd.voiceState&&(i.on("voice:state",_=>{c.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{c.setItem(b,_.viaVoice?"true":"false")})),Yn.clearOnChatClear){let _=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(b)},D=()=>_();window.addEventListener("persona:clear-chat",D),it.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return g&&O()&&setTimeout(()=>{tn.open()},0),ds(),Ma||Ou().then(()=>{$&&(is++,Lr.clear(),Fs(nt,$.getMessages(),Z))}).catch(()=>{}),tn};var ww=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Cw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Aw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Sw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},Gg=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Xl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Jg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Xl(e)},Kl=e=>{e.style.transition=""},Gl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Jl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Tw=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Ew=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Xg=(e,t,n,r,o,s,a)=>{var v,x,E,T,L,k;let i=rr(s),d=i.reveal==="push";Tw(e,t,n,r,d),Ew(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",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 l=e.ownerDocument.defaultView,p=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(T=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?T:640,g=l!=null?l.innerWidth<=u:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gl(t),Kl(r),Jg(r),Jl(n),Mi(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((k=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?k:vn),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",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Jg(r),Cw(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gl(t),Kl(r),Jl(n),Mi(o,r);let M=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":P;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=M,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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Kl(r),Xl(r),Mi(o,r);let M=ww(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",R=i.side==="right"?a?-M:0:a?0:-M;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=`${P+M}px`,t.style.transition=C,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Gl(t),Xl(r),Jl(n),Mi(o,r);let M=i.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",R=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",Aw(r,i.maxHeight),r.style.overflow=M||R?"hidden":"visible",r.style.transition=C,M&&(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")}},Mw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Gg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Gg(n,r)},destroy(){n.remove()}}},kw=(e,t)=>{var k,M,P,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.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=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(M=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||M?(C=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},v=()=>{f(),rr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Xg(a,i,d,l,p,t,u)}),g.observe(a))},x=!1,E=()=>{Xg(a,i,d,l,p,t,u),v(),u&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,Sw(a,rr(t)))},T=a.ownerDocument.defaultView,L=()=>{E()};return T==null||T.addEventListener("resize",L),rr(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),E(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let F=R.launcherEnabled?R.open:!0;u!==F&&(u=F,E())},updateConfig(R){var F,j;t=R,((j=(F=t==null?void 0:t.launcher)==null?void 0:F.enabled)!=null?j:!0)===!1&&(u=!0),E()},destroy(){T==null||T.removeEventListener("resize",L),f(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},ki=(e,t)=>dn(t)?kw(e,t):Mw(e,t);var Ql={},Lw=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Pw=()=>{try{if(typeof Ql!="undefined"&&Ql.url)return new URL("../widget.css",Ql.url).href}catch{}return null},Qg=(e,t)=>{let n=Pw(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Yg=e=>{var E;let t=Lw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=ki(t,o),a,i=[],d=(T,L)=>{var C,R;let M=!((R=(C=L==null?void 0:L.launcher)==null?void 0:C.enabled)!=null?R:!0)||dn(L),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),M&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let F=T.attachShadow({mode:"open"});F.appendChild(P),Qg(F,r)}else T.appendChild(P),Qg(T,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let T=d(s.host,o);a=Vl(T,o,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(E=e.onChatReady)==null||E.call(e);let f=T=>{g(),s.destroy(),s=ki(t,T),o=T,u()},v={update(T){var R,F,j,H,O,N;let L={...o,...T,launcher:{...(R=o==null?void 0:o.launcher)!=null?R:{},...(F=T==null?void 0:T.launcher)!=null?F:{},dock:{...(H=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?H:{},...(N=(O=T==null?void 0:T.launcher)==null?void 0:O.dock)!=null?N:{}}}},k=dn(o),M=dn(L),P=Mo(o),C=Mo(L);if(k!==M||P!==C){f(L);return}o=L,s.updateConfig(o),a.update(T),l()},destroy(){g(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(T,L,k){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,k);let M=a[L];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var rf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Iw=new Set(["button","a","input","select","textarea","details","summary"]),Rw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Yl=/\b(product|card|item|listing|result)\b/i,ec=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ww=3e3,Hw=100;function of(e){let t=typeof e.className=="string"?e.className:"";if(Yl.test(t)||e.id&&Yl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Yl.test(r.value))return!0}return!1}function sf(e){var t;return ec.test(((t=e.textContent)!=null?t:"").trim())}function af(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Bw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Zg(e){let t=e.match(ec);return t?t[0]:null}function ef(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Dw(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Nw="commerce-card",Ow="result-card";function tf(e){return!of(e)||!sf(e)||!af(e)&&!Bw(e)?0:5200}function nf(e){var r;return!of(e)||sf(e)||!af(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var lf=[{id:Nw,scoreElement(e){return tf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||ec.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(tf(e)===0)return null;let{title:n,href:r}=ef(e),o=(p=(l=Zg(((d=e.textContent)!=null?d:"").trim()))!=null?l:Zg(t.text))!=null?p:"",s=Dw(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
112
+ `)}},{id:Ow,scoreElement(e){return nf(e)},formatSummary(e,t){if(nf(e)===0)return null;let{title:n,href:r}=ef(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
+ `)}}];function Fw(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function _w(e){var p,u,g,f,v,x,E,T,L,k,M,P,C;let t=(p=e.options)!=null?p:{},n=(g=(u=t.maxElements)!=null?u:e.maxElements)!=null?g:80,r=(v=(f=t.excludeSelector)!=null?f:e.excludeSelector)!=null?v:".persona-host",o=(E=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?E:200,s=(L=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?L:!0,a=(k=t.root)!=null?k:e.root,i=(M=t.mode)!=null?M:"structured",d=(P=t.maxCandidates)!=null?P:Math.max(500,n*10),l=(C=e.rules)!=null?C:lf;return i==="simple"&&e.rules&&e.rules.length>0?(Fw(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Zl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var $w=["data-testid","data-product","data-action","data-id","data-name","data-type"];function jw(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Iw.has(t)||n&&Rw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function cf(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Uw(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function df(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Zl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of $w){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Zl(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>Zl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function qw(e){return e==="static"?Hw:Ww}function pf(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:df(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:jw(e),attributes:Uw(e)}}function zw(e,t,n,r){let o=qw(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function Vw(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function Kw(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(rf.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!cf(l)){i=a.nextNode();continue}let u=pf(l,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!g&&!f){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=zw(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:x}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;Vw(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,n);f&&(p=f)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function Gw(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(rf.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!cf(d)){s=o.nextNode();continue}let p=pf(d,e.maxTextLength),u=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!u&&!g){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Jw(e={}){var r;let t=_w(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Gw(t,n):Kw(t,n):[]}var Li=100;function Xw(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
114
114
  ${a.map(i=>`- ${i.split(`
115
115
  `).join(`
116
116
  `)}`).join(`
117
- `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Si)}" (clickable)`);r.push(`Interactive elements:
117
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Li)}" (clickable)`);r.push(`Interactive elements:
118
118
  ${a.join(`
119
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Si)}" (navigable)`);r.push(`Navigation links:
119
+ `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Li)}" (navigable)`);r.push(`Navigation links:
120
120
  ${a.join(`
121
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Si)}" (input)`);r.push(`Form inputs:
121
+ `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Li)}" (input)`);r.push(`Form inputs:
122
122
  ${a.join(`
123
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Si)}"`);r.push(`Content:
123
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Li)}"`);r.push(`Content:
124
124
  ${a.join(`
125
125
  `)}`)}return r.join(`
126
126
 
127
- `)}function Rw(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Ww(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Hw(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Br(e.colors.primary,.95),100:Br(e.colors.primary,.9),200:Br(e.colors.primary,.8),300:Br(e.colors.primary,.7),400:Br(e.colors.primary,.6),500:e.colors.primary,600:Br(e.colors.primary,.8),700:Br(e.colors.primary,.7),800:Br(e.colors.primary,.6),900:Br(e.colors.primary,.5),950:Br(e.colors.primary,.45)}}),{...t,palette:n}}}}function Bw(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Dw(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Br(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Nw(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Ow={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Xg={components:{panel:{borderRadius:"0",shadow:"none"}}},Qg={id:"shop",label:"Shopping Assistant",config:{theme:Ow,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:sr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Yg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Xg}},Zg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Xg}},ef={shop:Qg,minimal:Yg,fullscreen:Zg};function Fw(e){return ef[e]}var _w=Ng;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function $w(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var tf=`({ text, message }: any) => {
127
+ `)}function Qw(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Yw(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Zw(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:_r(e.colors.primary,.95),100:_r(e.colors.primary,.9),200:_r(e.colors.primary,.8),300:_r(e.colors.primary,.7),400:_r(e.colors.primary,.6),500:e.colors.primary,600:_r(e.colors.primary,.8),700:_r(e.colors.primary,.7),800:_r(e.colors.primary,.6),900:_r(e.colors.primary,.5),950:_r(e.colors.primary,.45)}}),{...t,palette:n}}}}function eC(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function tC(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function _r(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function nC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var rC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},uf={components:{panel:{borderRadius:"0",shadow:"none"}}},mf={id:"shop",label:"Shopping Assistant",config:{theme:rC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:nr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},gf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:uf}},ff={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:uf}},hf={shop:mf,minimal:gf,fullscreen:ff};function oC(e){return hf[e]}var sC=Yg;function eo(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function aC(e){if(e)return{getHeaders:eo(e.getHeaders),onFeedback:eo(e.onFeedback),onCopy:eo(e.onCopy),requestMiddleware:eo(e.requestMiddleware),actionHandlers:eo(e.actionHandlers),actionParsers:eo(e.actionParsers),postprocessMessage:eo(e.postprocessMessage),contextProviders:eo(e.contextProviders),streamParser:eo(e.streamParser)}}var yf=`({ text, message }: any) => {
128
128
  const jsonSource = (message as any).rawContent || text || message.content;
129
129
  if (!jsonSource || typeof jsonSource !== 'string') return null;
130
130
  let cleanJson = jsonSource
@@ -137,7 +137,7 @@ ${a.join(`
137
137
  if (parsed.action) return { type: parsed.action, payload: parsed };
138
138
  } catch (e) { return null; }
139
139
  return null;
140
- }`,nf=`function(ctx) {
140
+ }`,bf=`function(ctx) {
141
141
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
142
142
  if (!jsonSource || typeof jsonSource !== 'string') return null;
143
143
  var cleanJson = jsonSource
@@ -150,7 +150,7 @@ ${a.join(`
150
150
  if (parsed.action) return { type: parsed.action, payload: parsed };
151
151
  } catch (e) { return null; }
152
152
  return null;
153
- }`,rf=`(action: any, context: any) => {
153
+ }`,xf=`(action: any, context: any) => {
154
154
  if (action.type !== 'nav_then_click') return;
155
155
  const payload = action.payload || action.raw || {};
156
156
  const url = payload?.page;
@@ -167,7 +167,7 @@ ${a.join(`
167
167
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
168
168
  window.location.href = targetUrl;
169
169
  return { handled: true, displayText: text };
170
- }`,of=`function(action, context) {
170
+ }`,vf=`function(action, context) {
171
171
  if (action.type !== 'nav_then_click') return;
172
172
  var payload = action.payload || action.raw || {};
173
173
  var url = payload.page;
@@ -184,26 +184,26 @@ ${a.join(`
184
184
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
185
185
  window.location.href = targetUrl;
186
186
  return { handled: true, displayText: text };
187
- }`,jw=`(parsed: any) => {
187
+ }`,iC=`(parsed: any) => {
188
188
  if (!parsed || typeof parsed !== 'object') return null;
189
189
  if (parsed.action === 'nav_then_click') return 'Navigating...';
190
190
  if (parsed.action === 'message') return parsed.text || '';
191
191
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
192
192
  return parsed.text || null;
193
- }`,Uw=`function(parsed) {
193
+ }`,lC=`function(parsed) {
194
194
  if (!parsed || typeof parsed !== 'object') return null;
195
195
  if (parsed.action === 'nav_then_click') return 'Navigating...';
196
196
  if (parsed.action === 'message') return parsed.text || '';
197
197
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
198
198
  return parsed.text || null;
199
- }`;function qw(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Ti(e){var t,n;return(n=(t=e.parserType)!=null?t:qw(e.streamParser))!=null?n:"plain"}function Ei(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function Mi(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function ki(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Li(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Gl(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function sf(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),sf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function wo(e,t,n,r){n&&(e.push(`${r}${t}: {`),sf(e,n,`${r} `),e.push(`${r}},`))}function ba(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function zw(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:$w(n.hooks)}:void 0;return t==="esm"?Vw(r,o):t==="script-installer"?Jw(r,o):t==="script-advanced"?Qw(r,o):t==="react-component"?Kw(r,o):t==="react-advanced"?Gw(r,o):Xw(r,o)}function Vw(e,t){let n=t==null?void 0:t.hooks,r=Ti(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ba(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&wo(s,"theme",e.theme," "),e.launcher&&wo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ei(e," ")),s.push(...Mi(e," ",n)),s.push(...ki(e," ")),s.push(...Li(e," ")),s.push(...Gl(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
200
- `)}function Kw(e,t){let n=t==null?void 0:t.hooks,r=Ti(e),o=r!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${ba(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&wo(s,"theme",e.theme," "),e.launcher&&wo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ei(e," ")),s.push(...Mi(e," ",n)),s.push(...ki(e," ")),s.push(...Li(e," ")),s.push(...Gl(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
201
- `)}function Gw(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${ba(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&wo(r,"theme",e.theme," "),e.launcher&&wo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ei(e," ")),r.push(...Mi(e," ",n)),r.push(...ki(e," ")),r.push(...Li(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${jw}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${tf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${tf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${rf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${rf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
202
- `)}function af(e){var o;let t=Ti(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function Jw(e,t){let n=af(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/install.global.js" data-config='${s}'></script>`}function Xw(e,t){let n=t==null?void 0:t.hooks,r=Ti(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${ba(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&wo(s,"theme",e.theme," "),e.launcher&&wo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ei(e," ")),s.push(...Mi(e," ",n)),s.push(...ki(e," ")),s.push(...Li(e," ")),s.push(...Gl(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
203
- `)}function Qw(e,t){let n=t==null?void 0:t.hooks,r=af(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
199
+ }`;function cC(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Pi(e){var t,n;return(n=(t=e.parserType)!=null?t:cC(e.streamParser))!=null?n:"plain"}function Ii(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function Ri(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Wi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Hi(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function tc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function wf(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),wf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function Po(e,t,n,r){n&&(e.push(`${r}${t}: {`),wf(e,n,`${r} `),e.push(`${r}},`))}function Ea(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function dC(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:aC(n.hooks)}:void 0;return t==="esm"?pC(r,o):t==="script-installer"?gC(r,o):t==="script-advanced"?hC(r,o):t==="react-component"?uC(r,o):t==="react-advanced"?mC(r,o):fC(r,o)}function pC(e,t){let n=t==null?void 0:t.hooks,r=Pi(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ii(e," ")),s.push(...Ri(e," ",n)),s.push(...Wi(e," ")),s.push(...Hi(e," ")),s.push(...tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
200
+ `)}function uC(e,t){let n=t==null?void 0:t.hooks,r=Pi(e),o=r!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ii(e," ")),s.push(...Ri(e," ",n)),s.push(...Wi(e," ")),s.push(...Hi(e," ")),s.push(...tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
201
+ `)}function mC(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(r,"theme",e.theme," "),e.launcher&&Po(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ii(e," ")),r.push(...Ri(e," ",n)),r.push(...Wi(e," ")),r.push(...Hi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${iC}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${yf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${yf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${xf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${xf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
202
+ `)}function Cf(e){var o;let t=Pi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function gC(e,t){let n=Cf(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist/install.global.js" data-config='${s}'></script>`}function fC(e,t){let n=t==null?void 0:t.hooks,r=Pi(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ea(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ii(e," ")),s.push(...Ri(e," ",n)),s.push(...Wi(e," ")),s.push(...Hi(e," ")),s.push(...tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
203
+ `)}function hC(e,t){let n=t==null?void 0:t.hooks,r=Cf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
204
204
  `).map((a,i)=>i===0?a:" "+a).join(`
205
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${Uw});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${nf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${nf}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${of}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${of}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${ba(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
206
- `)}var lf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},cf=.1,df=.15,pf=1.5,Jl=24,uf=40,Yw=`
205
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${lC});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bf}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${vf}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${vf}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ea(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
206
+ `)}var Af={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Sf=.1,Tf=.15,Ef=1.5,nc=24,Mf=40,yC=`
207
207
  /* \u2500\u2500 Root \u2500\u2500 */
208
208
  .persona-dc-root {
209
209
  display: flex;
@@ -354,7 +354,7 @@ ${a.join(`
354
354
  .persona-dc-stage {
355
355
  height: 550px;
356
356
  min-height: 400px;
357
- padding: ${Jl}px;
357
+ padding: ${nc}px;
358
358
  overflow: auto;
359
359
  background: #f0f1f3;
360
360
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -444,5 +444,5 @@ ${a.join(`
444
444
  min-height: 300px;
445
445
  }
446
446
  }
447
- `;function Zw(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Yw,document.head.appendChild(e)}function eC(e,t){let n=e.clientWidth-Jl*2-uf,r=e.clientHeight-Jl*2-uf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function tC(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function nC(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Zw();let p=Math.max(0,Math.min(r,n.length-1)),u=o,g=s,f=null,v=1,x=!1,E=y("div","persona-dc-root"),T=y("div","persona-dc-toolbar"),L=y("div","persona-dc-toolbar-lead"),k=y("div","persona-dc-toolbar-trail"),M=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>X(-1)}),P=y("div");P.style.position="relative";let C=y("button","persona-dc-title-btn");C.type="button",C.setAttribute("aria-expanded","false"),C.setAttribute("aria-haspopup","listbox");let R=y("span","persona-dc-title-text"),F=y("span","persona-dc-title-chevron"),j=me("chevron-down",12,"currentColor",2);j&&F.appendChild(j),C.append(R,F);let W=y("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let O=!1;function N(){W.innerHTML="";for(let ge=0;ge<n.length;ge++){let Ve=n[ge],et=y("button","persona-dc-dropdown-item");et.type="button",et.setAttribute("role","option"),et.setAttribute("aria-current",ge===p?"true":"false");let $t=y("span");if($t.textContent=Ve.title,et.appendChild($t),Ve.description){let Xe=y("span","persona-dc-dropdown-desc");Xe.textContent=Ve.description,et.appendChild(Xe)}et.addEventListener("click",()=>{Ee(),We(ge)}),W.appendChild(et)}}function Y(){O=!O,W.style.display=O?"":"none",C.setAttribute("aria-expanded",O?"true":"false"),O&&N()}function Ee(){O&&(O=!1,W.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",ge=>{ge.stopPropagation(),Y()});let de=()=>Ee();document.addEventListener("click",de),P.append(C,W);let Z=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>X(1)}),Ce=y("span","persona-dc-counter");L.append(M,P,Z,Ce);let ke=null;i&&(ke=ai({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ge=>{u=ge,oe.dataset.device=u,f=null,K()}}),k.appendChild(ke.element));let re=null;if(a){let ge=y("div","persona-dc-zoom-controls"),Ve=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.max(df,Xe-cf),K()}});re=y("span","persona-dc-zoom-level"),re.title="Reset to 100%",re.style.cursor="pointer",re.addEventListener("click",()=>{f=1,K()});let et=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.min(pf,Xe+cf),K()}}),$t=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,K()}});ge.append(Ve,re,et,$t),k.appendChild(ge)}if(d){let ge=y("div","persona-dc-separator");k.appendChild(ge);let Ve=ai({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:et=>{g=et,oe.dataset.colorScheme=g,He()}});k.appendChild(Ve.element)}let we=y("div","persona-dc-separator");k.appendChild(we);let le=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(le),T.append(L,k);let se=y("div","persona-dc-stage"),oe=y("div","persona-dc-iframe-wrapper");oe.dataset.device=u,oe.dataset.colorScheme=g;let be=y("iframe","persona-dc-iframe");be.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),be.setAttribute("loading","lazy"),be.title=n[p].title,oe.appendChild(be),se.appendChild(oe),E.append(T,se),e.appendChild(E);function He(){var ge;try{let Ve=(ge=be.contentDocument)==null?void 0:ge.body;if(!Ve)return;g==="dark"?Ve.classList.add("theme-dark"):Ve.classList.remove("theme-dark")}catch{}}be.addEventListener("load",()=>He());function V(){let ge=n[p];R.textContent=ge.title,Ce.textContent=`${p+1} / ${n.length}`,be.title=ge.title}function X(ge){let Ve=((p+ge)%n.length+n.length)%n.length;We(Ve)}function We(ge){ge<0||ge>=n.length||(p=ge,be.src=n[p].url,V(),l==null||l(p,n[p]))}function K(){var et;if(x)return;let ge=(et=lf[u])!=null?et:lf.desktop;v=eC(se,ge);let Ve=Math.max(df,Math.min(pf,f!=null?f:v));tC(oe,be,ge,Ve,u),re&&(re.textContent=`${Math.round(Ve*100)}%`)}let pe=new ResizeObserver(()=>K());pe.observe(se),V(),be.src=n[p].url,requestAnimationFrame(()=>K());function $e(){x||(x=!0,pe.disconnect(),document.removeEventListener("click",de),E.remove())}return{element:E,goTo:We,next:()=>X(1),prev:()=>X(-1),getIndex:()=>p,setDevice(ge){u=ge,oe.dataset.device=ge,ke==null||ke.setSelected(ge),f=null,K()},setColorScheme(ge){g=ge,oe.dataset.colorScheme=ge},setZoom(ge){f=ge,K()},destroy:$e}}export{tm as ASK_USER_QUESTION_CLIENT_TOOL,em as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Pa as ASK_USER_QUESTION_TOOL_NAME,fs as AgentWidgetClient,ta as AgentWidgetSession,xs as AttachmentManager,Uo as BrowserSpeechEngine,Mm as DEFAULT_COMPONENTS,sl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Tm as DEFAULT_PALETTE,Em as DEFAULT_SEMANTIC,Ot as DEFAULT_WIDGET_CONFIG,ef as PRESETS,Zg as PRESET_FULLSCREEN,Yg as PRESET_MINIMAL,Qg as PRESET_SHOP,bs as ReadAloudController,Vi as SUGGEST_REPLIES_CLIENT_TOOL,Qu as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Hr as SUGGEST_REPLIES_TOOL_NAME,gx as THEME_ZONES,fr as VERSION,Rr as WEBMCP_TOOL_PREFIX,js as WebMcpBridge,Rw as accessibilityPlugin,Ww as animationsPlugin,qo as applyThemeVariables,ws as attachHeaderToContainer,Hw as brandPlugin,ma as buildComposer,zm as buildDefaultHeader,xo as buildHeader,ua as buildHeaderWithLayout,Vm as buildMinimalHeader,Ba as builtInClientToolsForDispatch,Pw as collectEnrichedPageContext,vo as componentRegistry,vi as createActionManager,Fl as createAgentExperience,Eh as createAskUserQuestionBubble,nl as createBestAvailableVoiceProvider,Xx as createBubbleWithLayout,Dl as createCSATFeedback,fl as createComboButton,Jv as createComponentMiddleware,Rl as createComponentStreamParser,ku as createDefaultSanitizer,nC as createDemoCarousel,Of as createDirectivePostprocessor,Vo as createDropdownMenu,Ph as createFlexibleJsonStreamParser,Gt as createIconButton,$h as createImagePart,Yi as createJsonStreamParser,si as createLabelButton,Il as createLocalStorageAdapter,ka as createMarkdownProcessor,us as createMarkdownProcessorFromConfig,ng as createMessageActions,Nl as createNPSFeedback,Xi as createPlainTextParser,Nw as createPlugin,Qi as createRegexJsonParser,ga as createStandardBubble,ja as createTextPart,ra as createTheme,cl as createThemeObserver,ai as createToggleGroup,Cs as createTypingIndicator,jo as createVoiceProvider,Ai as createWidgetHostLayout,Zi as createXmlParser,_w as default,Es as defaultActionHandlers,xi as defaultJsonActionParser,Vg as defaultParseRules,Ga as detectColorScheme,Ff as directivePostprocessor,Ks as ensureAskUserQuestionSheet,Vr as escapeHtml,Bl as extractComponentDirectiveFromMessage,jh as fileToImagePart,Iw as formatEnrichedContext,hs as generateAssistantMessageId,zw as generateCodeSnippet,Dh as generateMessageId,Gg as generateStableSelector,Qs as generateUserMessageId,oa as getActiveTheme,Im as getColorScheme,Oh as getDisplayText,Km as getHeaderLayout,_h as getImageParts,Fw as getPreset,Hl as hasComponentDirective,Fh as hasImages,hl as headerLayouts,Dw as highContrastPlugin,Ng as initAgentWidget,po as isAskUserQuestionMessage,Gv as isComponentDirectiveType,cn as isDockedMountMode,Ha as isSuggestRepliesMessage,qa as isVoiceSupported,Oo as isWebMcpToolName,Gi as latestAgentSuggestions,Sx as listRegisteredStreamAnimations,Tu as markdownPostprocessor,al as mergeWithDefaults,Nh as normalizeContent,uo as parseAskUserQuestionPayload,Yu as parseSuggestRepliesPayload,Zs as pickBestVoice,bi as pluginRegistry,Bw as reducedMotionPlugin,Cx as registerStreamAnimationPlugin,_o as removeAskUserQuestionSheet,Wl as renderComponentDirective,tg as renderLoadingIndicatorWithFallback,me as renderLucideIcon,ar as resolveDockConfig,$s as resolveSanitizer,il as resolveTokens,_i as stripWebMcpPrefix,ll as themeToCssVariables,Ax as unregisterStreamAnimationPlugin,Uh as validateImageFile,km as validateTheme};
447
+ `;function bC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=yC,document.head.appendChild(e)}function xC(e,t){let n=e.clientWidth-nc*2-Mf,r=e.clientHeight-nc*2-Mf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function vC(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function wC(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");bC();let p=Math.max(0,Math.min(r,n.length-1)),u=o,g=s,f=null,v=1,x=!1,E=y("div","persona-dc-root"),T=y("div","persona-dc-toolbar"),L=y("div","persona-dc-toolbar-lead"),k=y("div","persona-dc-toolbar-trail"),M=Kt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>X(-1)}),P=y("div");P.style.position="relative";let C=y("button","persona-dc-title-btn");C.type="button",C.setAttribute("aria-expanded","false"),C.setAttribute("aria-haspopup","listbox");let R=y("span","persona-dc-title-text"),F=y("span","persona-dc-title-chevron"),j=ge("chevron-down",12,"currentColor",2);j&&F.appendChild(j),C.append(R,F);let H=y("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let O=!1;function N(){H.innerHTML="";for(let fe=0;fe<n.length;fe++){let Ve=n[fe],et=y("button","persona-dc-dropdown-item");et.type="button",et.setAttribute("role","option"),et.setAttribute("aria-current",fe===p?"true":"false");let Ot=y("span");if(Ot.textContent=Ve.title,et.appendChild(Ot),Ve.description){let Xe=y("span","persona-dc-dropdown-desc");Xe.textContent=Ve.description,et.appendChild(Xe)}et.addEventListener("click",()=>{ke(),He(fe)}),H.appendChild(et)}}function Y(){O=!O,H.style.display=O?"":"none",C.setAttribute("aria-expanded",O?"true":"false"),O&&N()}function ke(){O&&(O=!1,H.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",fe=>{fe.stopPropagation(),Y()});let pe=()=>ke();document.addEventListener("click",pe),P.append(C,H);let Z=Kt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>X(1)}),Te=y("span","persona-dc-counter");L.append(M,P,Z,Te);let Le=null;i&&(Le=pi({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:fe=>{u=fe,ae.dataset.device=u,f=null,K()}}),k.appendChild(Le.element));let oe=null;if(a){let fe=y("div","persona-dc-zoom-controls"),Ve=Kt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.max(Tf,Xe-Sf),K()}});oe=y("span","persona-dc-zoom-level"),oe.title="Reset to 100%",oe.style.cursor="pointer",oe.addEventListener("click",()=>{f=1,K()});let et=Kt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.min(Ef,Xe+Sf),K()}}),Ot=Kt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,K()}});fe.append(Ve,oe,et,Ot),k.appendChild(fe)}if(d){let fe=y("div","persona-dc-separator");k.appendChild(fe);let Ve=pi({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:et=>{g=et,ae.dataset.colorScheme=g,Be()}});k.appendChild(Ve.element)}let Ae=y("div","persona-dc-separator");k.appendChild(Ae);let se=Kt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(se),T.append(L,k);let ie=y("div","persona-dc-stage"),ae=y("div","persona-dc-iframe-wrapper");ae.dataset.device=u,ae.dataset.colorScheme=g;let xe=y("iframe","persona-dc-iframe");xe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),xe.setAttribute("loading","lazy"),xe.title=n[p].title,ae.appendChild(xe),ie.appendChild(ae),E.append(T,ie),e.appendChild(E);function Be(){var fe;try{let Ve=(fe=xe.contentDocument)==null?void 0:fe.body;if(!Ve)return;g==="dark"?Ve.classList.add("theme-dark"):Ve.classList.remove("theme-dark")}catch{}}xe.addEventListener("load",()=>Be());function V(){let fe=n[p];R.textContent=fe.title,Te.textContent=`${p+1} / ${n.length}`,xe.title=fe.title}function X(fe){let Ve=((p+fe)%n.length+n.length)%n.length;He(Ve)}function He(fe){fe<0||fe>=n.length||(p=fe,xe.src=n[p].url,V(),l==null||l(p,n[p]))}function K(){var et;if(x)return;let fe=(et=Af[u])!=null?et:Af.desktop;v=xC(ie,fe);let Ve=Math.max(Tf,Math.min(Ef,f!=null?f:v));vC(ae,xe,fe,Ve,u),oe&&(oe.textContent=`${Math.round(Ve*100)}%`)}let ue=new ResizeObserver(()=>K());ue.observe(ie),V(),xe.src=n[p].url,requestAnimationFrame(()=>K());function $e(){x||(x=!0,ue.disconnect(),document.removeEventListener("click",pe),E.remove())}return{element:E,goTo:He,next:()=>X(1),prev:()=>X(-1),getIndex:()=>p,setDevice(fe){u=fe,ae.dataset.device=fe,Le==null||Le.setSelected(fe),f=null,K()},setColorScheme(fe){g=fe,ae.dataset.colorScheme=fe},setZoom(fe){f=fe,K()},destroy:$e}}export{hm as ASK_USER_QUESTION_CLIENT_TOOL,fm as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Ba as ASK_USER_QUESTION_TOOL_NAME,ws as AgentWidgetClient,ca as AgentWidgetSession,Ts as AttachmentManager,Yo as BrowserSpeechEngine,jm as DEFAULT_COMPONENTS,ul as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,nr as DEFAULT_FLOATING_LAUNCHER_WIDTH,_m as DEFAULT_PALETTE,$m as DEFAULT_SEMANTIC,Dt as DEFAULT_WIDGET_CONFIG,hf as PRESETS,ff as PRESET_FULLSCREEN,gf as PRESET_MINIMAL,mf as PRESET_SHOP,Ss as ReadAloudController,Zi as SUGGEST_REPLIES_CLIENT_TOOL,um as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Or as SUGGEST_REPLIES_TOOL_NAME,Wx as THEME_ZONES,yr as VERSION,Dr as WEBMCP_TOOL_PREFIX,Xs as WebMcpBridge,Qw as accessibilityPlugin,Yw as animationsPlugin,Zo as applyThemeVariables,Ms as attachHeaderToContainer,Zw as brandPlugin,wa as buildComposer,ag as buildDefaultHeader,ko as buildHeader,va as buildHeaderWithLayout,ig as buildMinimalHeader,_a as builtInClientToolsForDispatch,Jw as collectEnrichedPageContext,Lo as componentRegistry,Ti as createActionManager,Vl as createAgentExperience,zh as createAskUserQuestionBubble,cl as createBestAvailableVoiceProvider,fv as createBubbleWithLayout,Ul as createCSATFeedback,Cl as createComboButton,gw as createComponentMiddleware,Fl as createComponentStreamParser,Uu as createDefaultSanitizer,wC as createDemoCarousel,rh as createDirectivePostprocessor,es as createDropdownMenu,Jh as createFlexibleJsonStreamParser,Kt as createIconButton,ay as createImagePart,sl as createJsonStreamParser,di as createLabelButton,Ol as createLocalStorageAdapter,Wa as createMarkdownProcessor,bs as createMarkdownProcessorFromConfig,yg as createMessageActions,ql as createNPSFeedback,rl as createPlainTextParser,nC as createPlugin,ol as createRegexJsonParser,Ca as createStandardBubble,Ka as createTextPart,pa as createTheme,hl as createThemeObserver,pi as createToggleGroup,ks as createTypingIndicator,Qo as createVoiceProvider,ki as createWidgetHostLayout,al as createXmlParser,sC as default,Rs as defaultActionHandlers,Si as defaultJsonActionParser,lf as defaultParseRules,Za as detectColorScheme,oh as directivePostprocessor,ta as ensureAskUserQuestionSheet,Yr as escapeHtml,jl as extractComponentDirectiveFromMessage,iy as fileToImagePart,Xw as formatEnrichedContext,Cs as generateAssistantMessageId,dC as generateCodeSnippet,ty as generateMessageId,df as generateStableSelector,sa as generateUserMessageId,ua as getActiveTheme,Vm as getColorScheme,ry as getDisplayText,lg as getHeaderLayout,sy as getImageParts,oC as getPreset,$l as hasComponentDirective,oy as hasImages,Al as headerLayouts,tC as highContrastPlugin,Yg as initAgentWidget,xo as isAskUserQuestionMessage,mw as isComponentDirectiveType,dn as isDockedMountMode,Fa as isSuggestRepliesMessage,Ja as isVoiceSupported,Ko as isWebMcpToolName,tl as latestAgentSuggestions,Ux as listRegisteredStreamAnimations,_u as markdownPostprocessor,ml as mergeWithDefaults,ny as normalizeContent,vo as parseAskUserQuestionPayload,mm as parseSuggestRepliesPayload,ia as pickBestVoice,Ai as pluginRegistry,eC as reducedMotionPlugin,$x as registerStreamAnimationPlugin,Jo as removeAskUserQuestionSheet,_l as renderComponentDirective,hg as renderLoadingIndicatorWithFallback,ge as renderLucideIcon,rr as resolveDockConfig,Js as resolveSanitizer,gl as resolveTokens,Ki as stripWebMcpPrefix,fl as themeToCssVariables,jx as unregisterStreamAnimationPlugin,ly as validateImageFile,Um as validateTheme};
448
448
  //# sourceMappingURL=index.js.map