@runtypelabs/persona 4.0.0 → 4.2.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,20 +1,22 @@
1
- var hf=Object.defineProperty;var Ds=(e,t)=>()=>(e&&(t=e(e=0)),t);var gu=(e,t)=>{for(var n in t)hf(e,n,{get:t[n],enumerable:!0})};var fu={};gu(fu,{DOMPurify:()=>bf,Marked:()=>yf});import{Marked as yf}from"marked";import bf from"dompurify";var hu=Ds(()=>{"use strict"});var ms,Yi=Ds(()=>{"use strict";ms=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 s;this.sampleRate=t;let r=Math.max(0,(s=n.prebufferMs)!=null?s: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 s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let 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 s=n.createBufferSource();s.buffer=r,s.connect(n.destination);let o=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=o:this.nextStartTime<o&&(this.nextStartTime=o,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}}});function Wh(e){return e.replace(/\/+$/,"")}async function Hh(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 $a,sm=Ds(()=>{"use strict";Yi();$a=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 ms(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 s,o,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${Wh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(s=n.voice)!=null?s:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await Hh(p));let m=p.body.getReader();for(;;){let{done:f,value:g}=await m.read();if(t!==this.generation){await m.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(o=this.opts).onError)==null||a.call(o,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var ja,am=Ds(()=>{"use strict";ja=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 s;r=!0,(s=n.onStart)==null||s.call(n)},onEnd:()=>{var s;return(s=n.onEnd)==null?void 0:s.call(n)},onError:s=>{var o,a,i;if(r){(o=n.onError)==null||o.call(n,s);return}(i=(a=this.options).onFallback)==null||i.call(a,s),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,s;(n=(t=this.primary).destroy)==null||n.call(t),(s=(r=this.fallback).destroy)==null||s.call(r)}}});var im={};gu(im,{FallbackSpeechEngine:()=>ja,RuntypeSpeechEngine:()=>$a});var lm=Ds(()=>{"use strict";sm();am()});import{Marked as xf}from"marked";import vf from"dompurify";var yu=null,as=null,ss=null;var bu=e=>{as=e},xu=()=>as?Promise.resolve(as):ss||(yu?(ss=yu().then(e=>(as=e,e)),ss):(ss=Promise.resolve().then(()=>(hu(),fu)).then(e=>(as=e,e)),ss)),Bo=()=>as;bu({Marked:xf,DOMPurify:vf});var wf=e=>{if(e)return e},Aa=e=>{let t=null;return n=>{var s,o;let r=Bo();if(!r)return qr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(s=i==null?void 0:i.gfm)!=null?s:!0,breaks:(o=i==null?void 0:i.breaks)!=null?o:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=wf(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},is=e=>e?Aa({markedOptions:e.options,renderer:e.renderer}):Aa(),Cf=Aa(),wu=e=>Cf(e),qr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Cu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),vu=e=>`%%FORM_PLACEHOLDER_${e}%%`,Su=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=vu(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=vu(t.length);return t.push({token:o,type:s}),o}),n},Sf=e=>{let t=is(e);return n=>{let r=[],s=Su(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Cu(i)}"></div>`;o=o.replace(d,p)}),o}},Af=e=>{let t=[],n=Su(e,t),r=wu(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Cu(o)}"></div>`;r=r.replace(a,d)}),r};var Tf={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"]},Ef=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Au=()=>{let e=null;return t=>{let n=Bo();if(!n)return qr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(s,o)=>{if(o.attrName==="src"||o.attrName==="href"){let a=o.attrValue;a.toLowerCase().startsWith("data:")&&!Ef.test(a)&&(o.attrValue="",o.keepAttr=!1)}})}return e.sanitize(t,Tf)}},Ns=e=>e===!1?null:typeof e=="function"?e:Au();var lo="webmcp:",Bi=new Map,Tu=e=>{var t;Bi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Bi.set(n.name,r)}},Di=e=>Bi.get(Ni(e)),Ta={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Eu=null;function ku(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,s;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(s=n.origin)!=null?s:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Mf(t.join(""))}`}function Mu(e,t){let n=3735928559^t,r=1103547991^t;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);n=Math.imul(n^o,2654435761),r=Math.imul(r^o,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 Mf(e){let t=Mu(e,0).toString(36),n=Mu(e,2654435761).toString(36);return`${t}.${n}`}var Os=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(s){return Ta.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}Tu(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Lf(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return gr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let x=typeof document!="undefined"&&!!document.modelContext;return gr(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Ni(t),a;try{a=await s.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return gr(`Failed to read WebMCP registry: ${v}`)}Tu(a);let i=a.find(x=>x.name===o);if(!i)return gr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return gr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let d=Di(o),c={toolName:o,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return gr("User declined the tool call.");if(r!=null&&r.aborted)return gr("Aborted by cancel()");let p=new AbortController,m=!1,f=setTimeout(()=>{m=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let x=await s.executeTool(i,Wf(n),{signal:p.signal});return Pf(x)}catch(x){if(m)return gr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return gr(v)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}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}(Eu?await Eu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ta.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,Ta.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:If;try{return await n(t)}catch(s){return Ta.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>kf(t,r))}},Ni=e=>e.startsWith(lo)?e.slice(lo.length):e,Do=e=>e.startsWith(lo),kf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Lf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Pf=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:Hf(t)}]}},gr=e=>({isError:!0,content:[{type:"text",text:e}]}),If=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Rf(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var Lf=Object.defineProperty;var _s=(e,t)=>()=>(e&&(t=e(e=0)),t);var yu=(e,t)=>{for(var n in t)Lf(e,n,{get:t[n],enumerable:!0})};var bu={};yu(bu,{DOMPurify:()=>If,Marked:()=>Pf});import{Marked as Pf}from"marked";import If from"dompurify";var xu=_s(()=>{"use strict"});var bs,el=_s(()=>{"use strict";bs=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 Jh(e){return e.replace(/\/+$/,"")}async function Qh(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 qa,um=_s(()=>{"use strict";el();qa=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 bs(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 f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let l=`${Jh(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 Qh(p));let u=p.body.getReader();for(;;){let{done:f,value:g}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}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 za,mm=_s(()=>{"use strict";za=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 gm={};yu(gm,{FallbackSpeechEngine:()=>za,RuntypeSpeechEngine:()=>qa});var fm=_s(()=>{"use strict";um();mm()});import{Marked as Rf}from"marked";import Wf from"dompurify";var vu=null,us=null,ps=null;var wu=e=>{us=e},Cu=()=>us?Promise.resolve(us):ps||(vu?(ps=vu().then(e=>(us=e,e)),ps):(ps=Promise.resolve().then(()=>(xu(),bu)).then(e=>(us=e,e)),ps)),Oo=()=>us;wu({Marked:Rf,DOMPurify:Wf});var Hf=e=>{if(e)return e},Ma=e=>{let t=null;return n=>{var o,s;let r=Oo();if(!r)return Kr(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=Hf(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},ms=e=>e?Ma({markedOptions:e.options,renderer:e.renderer}):Ma(),Bf=Ma(),Su=e=>Bf(e),Kr=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;"),Au=e=>`%%FORM_PLACEHOLDER_${e}%%`,Tu=(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=Au(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=Au(t.length);return t.push({token:s,type:o}),s}),n},Df=e=>{let t=ms(e);return n=>{let r=[],o=Tu(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}},Nf=e=>{let t=[],n=Tu(e,t),r=Su(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 Of={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"]},Ff=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Mu=()=>{let e=null;return t=>{let n=Oo();if(!n)return Kr(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:")&&!Ff.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Of)}},$s=e=>e===!1?null:typeof e=="function"?e:Mu();var ku=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Lu=e=>e.includes("|"),Pu=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())},_f=e=>`| ${e.join(" | ")} |`,$f=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,jf=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Iu=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(!Lu(o)||ku.test(o)||!ku.test(s))continue;let a=Pu(o).length;if(a<1)continue;let i=$f(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()===""||!Lu(l))break;let p=_f(jf(Pu(l),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
+ `):e};var Wr="webmcp:",Oi=new Map,Ru=e=>{var t;Oi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Oi.set(n.name,r)}},Us=e=>Oi.get(Fi(e)),ka={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Wu=null;function Bu(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}:${Uf(t.join(""))}`}function Hu(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 Uf(e){let t=Hu(e,0).toString(36),n=Hu(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 ka.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Ru(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=zf(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=Fi(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}`)}Ru(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=Us(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,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let v=await o.executeTool(i,Jf(n),{signal:p.signal});return Vf(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(f),r&&r.removeEventListener("abort",g)}}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}(Wu?await Wu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ka.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,ka.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:Kf;try{return await n(t)}catch(o){return ka.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=>qf(t,r))}},Fi=e=>e.startsWith(Wr)?e.slice(Wr.length):e,Fo=e=>e.startsWith(Wr),qf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},zf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Vf=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:Qf(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),Kf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Gf(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
4
 
3
5
  Arguments:
4
6
  ${t}`:"")+(e.description?`
5
7
 
6
- ${e.description}`:"");return window.confirm(n)},Rf=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)}},Wf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Hf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Bf,ARR as Df,OBJ as Nf,STR as Of}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Pr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Tt=(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[o,a]of Object.entries(t.attrs))r.setAttribute(o,a);if(t.style){let o=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(o[i]=d)}}let s=n.filter(o=>o!=null);return s.length>0&&r.append(...s),r},Fs=(...e)=>e.filter(Boolean).join(" ");var Ea="ask_user_question",_s=8,ls="data-persona-ask-sheet-for",Ff="Other",_f="Other\u2026",Pu="Type your own answer here",Iu="Send",$f="Next",jf="Back",Uf="Submit all",qf="Skip",zf=3,Oi="data-ask-current-index",Fi="data-ask-question-count",Ru="data-ask-answers",_i="data-ask-grouped",Wu="data-ask-layout",Vf=e=>e.layout==="pills"?"pills":"rows",Kf=e=>e.getAttribute(Wu)==="pills"?"pills":"rows",Lu=!1,Hu=e=>e.replace(/["\\]/g,"\\$&"),co=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ea,Ma=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},po=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 s=r.join(""),o=Bf(s,Of|Nf|Df);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},$s=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>_s&&!Lu&&(Lu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${_s}.`)),t.slice(0,_s)},Gf=e=>{var t;return(t=$s(e)[0])!=null?t:null},Jf=(e,t)=>{var n;return(n=$s(e)[t])!=null?n:null},Bu=(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))},Du=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=y("span","persona-ask-row-check");r.appendChild(s)}else{let s=y("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},Qf=(e,t,n,r)=>{let o=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.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 c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}o.appendChild(a);let d=Du(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Xf=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},Yf=(e,t,n,r)=>{var p,m,f;let o=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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<zf;g++)o.appendChild(Xf(r));return o}if(d.forEach((g,x)=>{o.appendChild(Qf(g,x,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Ff:_f;if(r==="rows"){let x=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),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:Pu,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(m=t.freeTextLabel)!=null?m:g),v.appendChild(E),x.appendChild(v);let C=Du(r,a,d.length);C&&x.appendChild(C),o.appendChild(x)}else{let x=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:g,o.appendChild(x)}}return o},Nu=(e,t)=>{var o,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 s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:Pu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),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:Iu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Zf=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:Iu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},eh=(e,t,n)=>{var c,p,m,f;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 s=y("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(c=n.backLabel)!=null?c:jf,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=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:qf,a.setAttribute("data-ask-user-action","skip"),o.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?(m=n.submitAllLabel)!=null?m:Uf:(f=n.nextLabel)!=null?f:$f,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},No=e=>{let t=e.getAttribute(Ru);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Ou=(e,t)=>{e.setAttribute(Ru,JSON.stringify(t))},or=e=>{var n;let t=Number((n=e.getAttribute(Oi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},th=(e,t)=>{e.setAttribute(Oi,String(Math.max(0,Math.floor(t))))},cs=e=>{var n;let t=Number((n=e.getAttribute(Fi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},uo=e=>e.getAttribute(_i)==="true",nh=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},rh=(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)))},ka=(e,t)=>{let{payload:n}=po(t),r=$s(n),s=No(e),o={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(s,d)&&(o[c]=s[d]))}),o},Fu=e=>{let t=No(e),n=or(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var m;let c=(m=d.getAttribute("data-option-label"))!=null?m:"",p=s.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),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=""},_u=e=>{if(!uo(e))return;let t=No(e),n=or(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},$i=(e,t,n)=>{let r=Ma(n),s=Kf(e),{payload:o,complete:a}=po(t),i=uo(e),d=or(e),c=cs(e),p=i?Jf(o,d):Gf(o),m=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let I=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=I,x.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=Yf(p,r,a,s);v.replaceWith(I)}if(s!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(Nu(r,s))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!E?e.appendChild(Zf(r)):(!m||i)&&E&&E.remove(),e.setAttribute("data-multi-select",m?"true":"false");let C=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=eh(d,c,r);C?C.replaceWith(I):e.appendChild(I)}else C&&C.remove();Fu(e),_u(e)},oh=(e,t,n)=>{let r=Ma(t),s=Vf(r),o=e.toolCall.id,a=$s(n),i=Math.max(1,a.length),d=i>1,c=nh(e,a),p=d?rh(e,i):0,m=y("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ls,o),m.setAttribute("data-tool-call-id",o),m.setAttribute("data-message-id",e.id),m.setAttribute(Fi,String(i)),m.setAttribute(Oi,String(p)),m.setAttribute(_i,d?"true":"false"),m.setAttribute(Wu,s),Ou(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Bu(m,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),m.appendChild(f);let E=y("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),m.appendChild(E),s!=="rows"&&m.appendChild(Nu(r,s)),$i(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},sh=(e,t,n)=>{let{payload:r}=po(t),s=Math.max(1,$s(r).length);s>cs(e)&&(e.setAttribute(Fi,String(s)),s>1&&!uo(e)&&e.setAttribute(_i,"true")),$i(e,t,n)},ah=(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=Ma(t);Bu(n,r);let s=y("span","persona-ask-stub-label"),{complete:o}=po(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},js=(e,t,n)=>{if(!n||!co(e)||Ma(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${ls}]`).forEach(c=>{c.getAttribute(ls)!==s&&c.remove()});let a=n.querySelector(`[${ls}="${Hu(s)}"]`);if(a){sh(a,e,t);return}let{payload:i}=po(e),d=oh(e,t,i);n.appendChild(d)},Oo=(e,t)=>{if(!e)return;let n=t?`[${ls}="${Hu(t)}"]`:`[${ls}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},ji=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),mo=(e,t)=>{let n=No(e),r=or(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Ou(e,n),Fu(e),_u(e)},La=(e,t,n,r)=>{let s=cs(e),o=Math.max(0,Math.min(s-1,r));th(e,o),$i(e,t,n)};var Ir="suggest_replies";var $u={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},Ui={name:Ir,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:$u,origin:"sdk",annotations:{readOnlyHint:!0}},qi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Pa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Ir},ju=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(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.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},zi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Pa(r))continue;let s=ju((t=r.toolCall)==null?void 0:t.args);return s.length>0?s:null}return null},Uu=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 qu={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:_s,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},zu={name:Ea,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:qu,origin:"sdk",annotations:{readOnlyHint:!0}},Ia=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(zu),Uu(e)&&t.push(Ui),t};import{parse as Vu,STR as Ku,OBJ as Gu}from"partial-json";var Ra=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ds=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)}},ih=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Ju=e=>e.status==="complete"?ih(e):e.status==="pending"?"Waiting":"",lh=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o: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 Qu=e=>e.status==="complete"?lh(e):"Using tool...",Wa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},qs=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Wa(t)},Ha=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Wa(t)},Vi=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=qs(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ba=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Us(r,n.slice(o,a.index),[]),a[1]!==void 0?Us(r,a[1],["bold"]):a[2]!==void 0?Us(r,a[2],["italic"]):a[3]!==void 0&&Us(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Us(r,n.slice(o),[]),r},Us=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},ch=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},zs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ki=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gi=()=>{var t;let e=ch();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)}},Ji=()=>{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 s=Vu(n,Ku|Gu);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ra(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ra(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},dh=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ra(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ra(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=Vu(o,Ku|Gu),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Qi=()=>{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 Xu="4.0.0";var fr=Xu;var uh="https://api.runtype.com/v1/dispatch",Da="https://api.runtype.com";function mh(e){var o,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 s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Xi=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 gh(e){switch(e){case"json":return Ji;case"regex-json":return Gi;case"xml":return Qi;default:return Ki}}var Yu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function fh(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 s=Yu(n);if(!Yu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=zs(e);return zs(t)!==null&&a===null?t:e}var ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:uh,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:gh(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new Os(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}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Da}/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 o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.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$/,""))||Da}/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 s={...t,...this.config.clientToken&&{token:this.config.clientToken}},o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(s)});if(!o.ok){let d=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.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.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,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(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,m={sessionId:d.sessionId,messages:t.messages.filter(Xi).map(M=>{var P,S,W;return{id:M.id,role:M.role,content:(W=(S=(P=M.contentParts)!=null?P:M.llmContent)!=null?S:M.rawContent)!=null?W:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),x=g?ku(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=g&&v&&this.lastSentClientToolsFingerprint===x,C=!1,I=null,N;for(let M=0;;M++){let S={...m,...g&&(C||!E)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),N=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(S),signal:r.signal}),N.status===409&&M===0&&g){let W=await N.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){C=!0,this.lastSentClientToolsFingerprint=null;continue}I=W!=null?W:{error:"Chat request failed"}}break}if(!N.ok){let M=I!=null?I:await N.json().catch(()=>({error:"Chat request failed"}));if(N.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(N.status===429){let S=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!N.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(N.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:r.signal},s)}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:o,body:JSON.stringify(s),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 s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:r.signal},s)}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:o,body:JSON.stringify(s),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 s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Da}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Da}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Xi).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ia(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(Xi).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return c-p}).map(i=>{var d,c,p;return{role:i.role,content:(p=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...Ia(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=m,s(m),m},c=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,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(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 rn,yr,hn,Ve;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=T=>{let ue=T.reasoning?{...T.reasoning,chunks:[...T.reasoning.chunks]}:void 0,Me=T.toolCall?{...T.toolCall,chunks:T.toolCall.chunks?[...T.toolCall.chunks]:void 0}:void 0,Te=T.tools?T.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...T,reasoning:ue,toolCall:Me,tools:Te}},m=T=>{if(T.role!=="assistant"||T.variant)return!0;let ue=Array.isArray(T.contentParts)&&T.contentParts.length>0,Me=typeof T.rawContent=="string"&&T.rawContent.trim()!=="";return typeof T.content=="string"&&T.content.trim()!==""||ue||Me||!!T.stopReason},f=T=>{m(T)&&n({type:"message",message:p(T)})},g=null,x=null,v={current:null},E={current:null},C=null,I="",N=new Map,M=new Map,P=new Map,S=new Map,W=new Map,B={lastId:null,byStep:new Map},D={lastId:null,byCall:new Map},k=T=>{if(T==null)return null;try{return String(T)}catch{return null}},j=T=>{var ue,Me,Te,Ie,tt;return k((tt=(Ie=(Te=(Me=(ue=T.stepId)!=null?ue:T.step_id)!=null?Me:T.step)!=null?Te:T.parentId)!=null?Ie:T.flowStepId)!=null?tt:T.flow_step_id)},z=T=>{var ue,Me,Te,Ie,tt,Je,pt;return k((pt=(Je=(tt=(Ie=(Te=(Me=(ue=T.callId)!=null?ue:T.call_id)!=null?Me:T.requestId)!=null?Te:T.request_id)!=null?Ie:T.toolCallId)!=null?tt:T.tool_call_id)!=null?Je:T.stepId)!=null?pt:T.step_id)},te=r,Pe=!1,je=()=>{if(g)return g;let T,ue=C;return!Pe&&te?(T=te,Pe=!0):te&&ue?T=`${te}_${ue}`:T=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:T,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(g),g},Se=(T,ue)=>{B.lastId=ue,T&&B.byStep.set(T,ue)},ke=(T,ue)=>{var tt;let Me=(tt=T.reasoningId)!=null?tt:T.id,Te=j(T);if(Me){let Je=String(Me);return Se(Te,Je),Je}if(Te){let Je=B.byStep.get(Te);if(Je)return B.lastId=Je,Je}if(B.lastId&&!ue)return B.lastId;if(!ue)return null;let Ie=`reason-${c()}`;return Se(Te,Ie),Ie},Fe=T=>{let ue=S.get(T);if(ue)return ue;let Me={id:`reason-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"streaming",chunks:[]}};return S.set(T,Me),f(Me),Me},he=(T,ue)=>{D.lastId=ue,T&&D.byCall.set(T,ue)},Be=new Set,ae=new Map,Q=new Set,ne=new Map,le=T=>{if(!T)return!1;let ue=T.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},re=(T,ue)=>{var tt;let Me=(tt=T.toolId)!=null?tt:T.id,Te=z(T);if(Me){let Je=String(Me);return he(Te,Je),Je}if(Te){let Je=D.byCall.get(Te);if(Je)return D.lastId=Je,Je}if(D.lastId&&!ue)return D.lastId;if(!ue)return null;let Ie=`tool-${c()}`;return he(Te,Ie),Ie},G=T=>{let ue=W.get(T);if(ue)return ue;let Me={id:`tool-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:T,status:"pending"}};return W.set(T,Me),f(Me),Me},ee=T=>{if(typeof T=="number"&&Number.isFinite(T))return T;if(typeof T=="string"){let ue=Number(T);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Me=Date.parse(T);if(!Number.isNaN(Me))return Me}return Date.now()},qe=T=>{if(typeof T=="string")return T;if(T==null)return"";try{return JSON.stringify(T)}catch{return String(T)}},J=new Map,ie=new Map,Re=new Map,ve=(T,ue,Me)=>{var pt;let Te=Re.get(T);Te||(Te=[],Re.set(T,Te));let Ie=0,tt=Te.length;for(;Ie<tt;){let It=Ie+tt>>>1;Te[It].seq<ue?Ie=It+1:tt=It}((pt=Te[Ie])==null?void 0:pt.seq)===ue?Te[Ie]={seq:ue,text:Me}:Te.splice(Ie,0,{seq:ue,text:Me});let Je="";for(let It=0;It<Te.length;It++)Je+=Te[It].text;return Je},Xe=(T,ue)=>{let Me=qe(ue),Te=ie.get(T.id),Ie=fh(Te,Me);T.rawContent=Ie;let tt=J.get(T.id),Je=V=>{var Ee;let pe=(Ee=T.content)!=null?Ee:"";V.trim()!==""&&(pe.trim().length===0||V.startsWith(pe)||V.trimStart().startsWith(pe.trim()))&&(T.content=V)},pt=()=>{var V;if(tt){let pe=(V=tt.close)==null?void 0:V.call(tt);pe instanceof Promise&&pe.catch(()=>{})}J.delete(T.id),ie.delete(T.id),T.streaming=!1,f(T)};if(!tt){Je(Me),pt();return}let It=zs(Ie);if(It!==null&&It.trim()!==""){Je(It),pt();return}let U=V=>{var bt;let pe=typeof V=="string"?V:(bt=V==null?void 0:V.text)!=null?bt:null;if(pe!==null&&pe.trim()!=="")return pe;let Ee=tt.getExtractedText();return Ee!==null&&Ee.trim()!==""?Ee:Me},st;try{st=tt.processChunk(Ie)}catch{Je(Me),pt();return}if(st instanceof Promise){st.then(V=>{Je(U(V)),pt()}).catch(()=>{Je(Me),pt()});return}Je(U(st)),pt()},Ke=null,Ne=(T,ue,Me,Te)=>{var It;T.rawContent=ue,J.has(T.id)||J.set(T.id,this.createStreamParser());let Ie=J.get(T.id),tt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(tt&&ie.set(T.id,ue),Ie.__isPlainTextParser===!0){T.content=Te!==void 0?ue:T.content+Me,ie.delete(T.id),J.delete(T.id),T.rawContent=void 0,f(T);return}let pt=Ie.processChunk(ue);if(pt instanceof Promise)pt.then(U=>{var V;let st=typeof U=="string"?U:(V=U==null?void 0:U.text)!=null?V:null;st!==null&&st.trim()!==""?(T.content=st,f(T)):!tt&&!ue.trim().startsWith("<")&&(T.content=Te!==void 0?ue:T.content+Me,ie.delete(T.id),J.delete(T.id),T.rawContent=void 0,f(T))}).catch(()=>{T.content=Te!==void 0?ue:T.content+Me,ie.delete(T.id),J.delete(T.id),T.rawContent=void 0,f(T)});else{let U=typeof pt=="string"?pt:(It=pt==null?void 0:pt.text)!=null?It:null;U!==null&&U.trim()!==""?(T.content=U,f(T)):!tt&&!ue.trim().startsWith("<")&&(T.content=Te!==void 0?ue:T.content+Me,ie.delete(T.id),J.delete(T.id),T.rawContent=void 0,f(T))}},ce=(T,ue)=>{var It,U;let Me=ue!=null?ue:T.content;if(Me==null||Me===""){T.streaming=!1,f(T);return}let Te=ie.get(T.id),Ie=Te!=null?Te:qe(Me);T.rawContent=Ie;let tt=J.get(T.id),Je=null,pt=!1;if(tt&&(Je=tt.getExtractedText(),Je===null&&(Je=zs(Ie)),Je===null)){let st=tt.processChunk(Ie);st instanceof Promise?(pt=!0,st.then(V=>{var Ee;let pe=typeof V=="string"?V:(Ee=V==null?void 0:V.text)!=null?Ee:null;pe!==null&&(T.content=pe,T.streaming=!1,J.delete(T.id),ie.delete(T.id),f(T))}).catch(()=>{})):Je=typeof st=="string"?st:(It=st==null?void 0:st.text)!=null?It:null}if(!pt){Je!==null&&Je.trim()!==""?T.content=Je:ie.has(T.id)||(T.content=qe(Me));let st=J.get(T.id);if(st){let V=(U=st.close)==null?void 0:U.call(st);V instanceof Promise&&V.catch(()=>{}),J.delete(T.id)}ie.delete(T.id),T.streaming=!1,f(T)}},et=(T,ue,Me)=>{let Te=M.get(T);if(Te)return Te;let Ie={id:`nested-${ue}-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:T,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return M.set(T,Ie),f(Ie),Ie},X=[],de,we=new Map,ze=0,Lt="agent",Ae=null,me=null,fn=new Map,Pt=(rn=this.config.iterationDisplay)!=null?rn:"separate";for(de=()=>{var T,ue,Me,Te,Ie,tt,Je,pt,It,U,st,V,pe,Ee,bt,Yt,Zt,un,Wt,nt,Rt,lt,Kt,Qn,Cn,en,Pn,br,xt,Dn,xr,Wr,lr,ht,vo,vr,wo,In,Vo,Gr,Hr,Jr,Qr,Co,So,Xr,wt,Nn,On,Sn,St,Xn,Yn,Fn,Yr,Br,Zr,_n,Ht,An,Zn,eo,Dr,to,wr,$n,ye,ct,Jt,on,Cr,As,Nr,Ao,Sr,F,Ko,Ar,Tr,Or,Er,cr,Go,ga,jn,Un,dr,pr,To,Fr,yn,Mr,Jo,Eo,Qo,fa,Xo,ha,Yo,ft,Ts,er,Rn,ya,ba;for(let no=0;no<X.length;no++){let rt=X[no].payloadType,w=X[no].payload;if(rt==="reasoning_start"){let $=typeof w.id=="string"?w.id:null,_=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if($&&_){N.set($,_),et($,_,"reasoning");continue}let K=(T=ke(w,!0))!=null?T:`reason-${c()}`,fe=Fe(K);fe.reasoning=(ue=fe.reasoning)!=null?ue:{id:K,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Te=fe.reasoning.startedAt)!=null?Te:ee((Me=w.startedAt)!=null?Me:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",f(fe)}else if(rt==="reasoning_delta"){let $=typeof w.id=="string"?w.id:null;if($&&N.has($)&&M.has($)){let _e=M.get($),Ye=(Je=(tt=(Ie=w.reasoningText)!=null?Ie:w.text)!=null?tt:w.delta)!=null?Je:"";Ye&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(Ye)),f(_e));continue}let _=(It=(pt=ke(w,!1))!=null?pt:ke(w,!0))!=null?It:`reason-${c()}`,K=Fe(_);K.reasoning=(U=K.reasoning)!=null?U:{id:_,status:"streaming",chunks:[]},K.reasoning.startedAt=(V=K.reasoning.startedAt)!=null?V:ee((st=w.startedAt)!=null?st:w.timestamp);let fe=(bt=(Ee=(pe=w.reasoningText)!=null?pe:w.text)!=null?Ee:w.delta)!=null?bt:"";if(fe&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let Ye=ve(_,_e,String(fe));K.reasoning.chunks=[Ye]}else K.reasoning.chunks.push(String(fe))}if(K.reasoning.status=w.done?"complete":"streaming",w.done){K.reasoning.completedAt=ee((Yt=w.completedAt)!=null?Yt:w.timestamp);let _e=(Zt=K.reasoning.startedAt)!=null?Zt:Date.now();K.reasoning.durationMs=Math.max(0,((un=K.reasoning.completedAt)!=null?un:Date.now())-_e)}K.streaming=K.reasoning.status!=="complete",f(K)}else if(rt==="reasoning_complete"){let $=typeof w.id=="string"?w.id:null;if($&&N.has($)&&M.has($)){let Ye=M.get($);if(Ye.reasoning){let Et=typeof w.text=="string"?w.text:"";Et&&Ye.reasoning.chunks.length===0&&Ye.reasoning.chunks.push(Et),Ye.reasoning.status="complete",Ye.streaming=!1,f(Ye)}N.delete($),M.delete($);continue}let _=(nt=(Wt=ke(w,!1))!=null?Wt:ke(w,!0))!=null?nt:`reason-${c()}`,K=typeof w.text=="string"?w.text:"";!S.get(_)&&(K||w.scope==="loop")&&Fe(_);let fe=S.get(_);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),K&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(K),fe.reasoning.status="complete",fe.reasoning.completedAt=ee((Rt=w.completedAt)!=null?Rt:w.timestamp);let Ye=(lt=fe.reasoning.startedAt)!=null?lt:Date.now();fe.reasoning.durationMs=Math.max(0,((Kt=fe.reasoning.completedAt)!=null?Kt:Date.now())-Ye),fe.streaming=!1,f(fe)}let _e=j(w);_e&&B.byStep.delete(_e)}else if(rt==="tool_start"){g&&(g.streaming=!1,f(g),g=null),typeof w.iteration=="number"&&(ze=w.iteration);let $=(Cn=(Qn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Qn:re(w,!0))!=null?Cn:`tool-${c()}`,_=(en=w.toolName)!=null?en:w.name;if(le(_)){Be.add($);continue}he(z(w),$);let K=G($),fe=(Pn=K.toolCall)!=null?Pn:{id:$,status:"pending"};fe.name=_!=null?_:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(xt=fe.startedAt)!=null?xt:ee((br=w.startedAt)!=null?br:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,K.toolCall=fe,K.streaming=!0,w.executionId&&(K.agentMetadata={executionId:w.executionId,iteration:w.iteration}),f(K)}else if(rt==="tool_output_delta"){let $=(xr=(Dn=re(w,!1))!=null?Dn:re(w,!0))!=null?xr:`tool-${c()}`;if(Be.has($))continue;let _=G($),K=(Wr=_.toolCall)!=null?Wr:{id:$,status:"running"};K.startedAt=(ht=K.startedAt)!=null?ht:ee((lr=w.startedAt)!=null?lr:w.timestamp);let fe=(wo=(vr=(vo=w.text)!=null?vo:w.delta)!=null?vr:w.message)!=null?wo:"";fe&&(K.chunks=(In=K.chunks)!=null?In:[],K.chunks.push(String(fe))),K.status="running",_.toolCall=K,_.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(_.agentMetadata=(Hr=_.agentMetadata)!=null?Hr:{executionId:(Vo=_e==null?void 0:_e.executionId)!=null?Vo:w.executionId,iteration:(Gr=_e==null?void 0:_e.iteration)!=null?Gr:w.iteration}),f(_)}else if(rt==="tool_complete"){let $=(Qr=(Jr=re(w,!1))!=null?Jr:re(w,!0))!=null?Qr:`tool-${c()}`;if(Be.has($)){Be.delete($);continue}let _=G($),K=(Co=_.toolCall)!=null?Co:{id:$,status:"running"};K.status="complete",w.result!==void 0&&(K.result=w.result),typeof w.duration=="number"&&(K.duration=w.duration),K.completedAt=ee((So=w.completedAt)!=null?So:w.timestamp);let fe=(Xr=w.duration)!=null?Xr:w.executionTime;if(typeof fe=="number")K.durationMs=fe;else{let Et=(wt=K.startedAt)!=null?wt:Date.now();K.durationMs=Math.max(0,((Nn=K.completedAt)!=null?Nn:Date.now())-Et)}_.toolCall=K,_.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(_.agentMetadata=(St=_.agentMetadata)!=null?St:{executionId:(On=_e==null?void 0:_e.executionId)!=null?On:w.executionId,iteration:(Sn=_e==null?void 0:_e.iteration)!=null?Sn:w.iteration}),f(_);let Ye=z(w);Ye&&D.byCall.delete(Ye)}else if(rt==="await"&&w.toolName){let $=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,_=(Xn=$!=null?$:w.toolId)!=null?Xn:`local-${c()}`,K=G(_),fe=w.toolName,_e=w.origin==="webmcp"&&!Do(fe)?`webmcp:${fe}`:fe,Ye=Do(_e),Et=(Yn=K.toolCall)!=null?Yn:{id:_,status:"pending"};Et.name=_e,Et.args=w.parameters,Et.status=Ye?"running":"complete",Et.chunks=(Fn=Et.chunks)!=null?Fn:[],Et.startedAt=(Zr=Et.startedAt)!=null?Zr:ee((Br=(Yr=w.startedAt)!=null?Yr:w.timestamp)!=null?Br:w.awaitedAt),Ye?(Et.completedAt=void 0,Et.duration=void 0,Et.durationMs=void 0):Et.completedAt=(_n=Et.completedAt)!=null?_n:Et.startedAt,K.toolCall=Et,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:(An=w.executionId)!=null?An:(Ht=K.agentMetadata)==null?void 0:Ht.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(K)}else if(rt==="text_start"){let $=typeof w.id=="string"?w.id:null,_=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if($&&_){N.set($,_);continue}let K=g;K&&(Lt==="flow"?(ce(K),Ke=K):(K.streaming=!1,f(K)),g=null),C=typeof w.id=="string"?w.id:C,I=""}else if(rt==="text_delta"){let $=typeof w.id=="string"?w.id:null,_=$?N.get($):void 0;if($&&_){let fe=typeof w.delta=="string"?w.delta:"",_e=((Zn=P.get($))!=null?Zn:"")+fe;if(P.set($,_e),_e.trim()==="")continue;let Ye=et($,_);Ye.agentMetadata={...Ye.agentMetadata,executionId:w.executionId,parentToolId:_},Ne(Ye,_e,fe,void 0);continue}if(C=typeof w.id=="string"?w.id:C,Lt==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(I+=fe,I.trim()==="")continue;let _e=je();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ne(_e,I,fe,void 0),x=_e;continue}let K=je();K.content+=(eo=w.delta)!=null?eo:"",K.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ae!=null?Ae:void 0,agentName:me==null?void 0:me.agentName},x=K,f(K)}else if(rt==="text_complete"){let $=typeof w.id=="string"?w.id:null;if($&&N.has($)){let K=M.get($);K&&ce(K),N.delete($),P.delete($),M.delete($);continue}let _=g;_&&(Lt==="flow"?(ce(_),Ke=_):(((Dr=_.content)!=null?Dr:"")===""&&typeof w.text=="string"&&(_.content=w.text),_.streaming=!1,f(_)),g=null),C=null,I=""}else if(rt==="step_complete"){let $=w.stepType,_=w.executionType;if($==="tool"||_==="context")continue;if(w.success===!1){let K=w.error,fe=typeof K=="string"&&K!==""?K:K!=null&&typeof K=="object"&&"message"in K?String((to=K.message)!=null?to:"Step failed"):"Step failed";n({type:"error",error:new Error(fe)});let _e=g;_e&&_e.streaming&&(_e.streaming=!1,f(_e)),n({type:"status",status:"idle"});continue}{let K=Ke;Ke=null;let fe=w.stopReason,_e=(wr=w.result)==null?void 0:wr.response;if(K)fe&&(K.stopReason=fe),_e!=null?Xe(K,_e):K.streaming!==!1&&(J.delete(K.id),ie.delete(K.id),K.streaming=!1,f(K));else{let Ye=_e!=null&&_e!=="";if(Ye||fe){let Et=je();fe&&(Et.stopReason=fe),Ye?ce(Et,_e):(Et.streaming=!1,f(Et))}}continue}}else if(rt==="execution_start")Lt=w.kind==="flow"?"flow":"agent",Lt==="agent"&&(me={executionId:w.executionId,agentId:($n=w.agentId)!=null?$n:"virtual",agentName:(ye=w.agentName)!=null?ye:"",status:"running",currentIteration:0,maxTurns:(ct=w.maxTurns)!=null?ct:1,startedAt:ee(w.startedAt)});else if(rt==="turn_start"){let $=typeof w.iteration=="number"?w.iteration:ze;if($!==ze){if(me&&(me.currentIteration=$),Pt==="separate"&&$>1){let _=g;_&&(_.streaming=!1,f(_),fn.set($-1,_),g=null)}ze=$}Ae=typeof w.id=="string"?w.id:null,x=null}else if(rt==="tool_input_delta"){let $=(Jt=w.toolCallId)!=null?Jt:D.lastId;if($){let _=W.get($);_!=null&&_.toolCall&&(_.toolCall.chunks=(on=_.toolCall.chunks)!=null?on:[],_.toolCall.chunks.push((Cr=w.delta)!=null?Cr:""),f(_))}}else{if(rt==="tool_input_complete")continue;if(rt==="turn_complete"){let $=w.stopReason,_=g!=null?g:x;if($&&_!==null){let K=w.id;(!K||((As=_.agentMetadata)==null?void 0:As.turnId)===K)&&(_.stopReason=$,f(_))}Ae===w.id&&(Ae=null)}else if(rt==="media_start"){let $=String(w.id);we.set($,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(rt==="media_delta"){let $=we.get(String(w.id));$&&typeof w.delta=="string"&&$.parts.push(w.delta)}else if(rt==="media_complete"){let $=String(w.id),_=we.get($);we.delete($);let K=(Ao=(Nr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Nr:_==null?void 0:_.mediaType)!=null?Ao:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:_&&_.parts.length>0?_.parts.join(""):void 0,Ye=null;if(fe)Ye={type:"media",data:fe,mediaType:K};else if(_e){let qn=K.toLowerCase();Ye={type:qn==="image"||qn.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:K}}let Et=(Sr=w.toolCallId)!=null?Sr:_==null?void 0:_.toolCallId,_r=Ye?[Ye]:[],Wn=[];for(let qn of _r){if(!qn||typeof qn!="object")continue;let mn=qn,ro=typeof mn.type=="string"?mn.type:void 0,$r=typeof mn.mediaType=="string"?mn.mediaType.toLowerCase():"",gn=null,Hn="";if(ro==="media"){let zn=typeof mn.data=="string"?mn.data:void 0;if(!zn)continue;Hn=$r.length>0?$r:"application/octet-stream",gn=`data:${Hn};base64,${zn}`}else if(ro==="image-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;Hn=$r,gn=zn}else if(ro==="file-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;Hn=$r,gn=zn}else continue;if(gn)if(ro==="image-url"||Hn.startsWith("image/"))Wn.push({type:"image",image:gn,...Hn.includes("/")?{mimeType:Hn}:{}});else if(Hn.startsWith("audio/"))Wn.push({type:"audio",audio:gn,mimeType:Hn});else if(Hn.startsWith("video/"))Wn.push({type:"video",video:gn,mimeType:Hn});else{let zn=Hn||"application/octet-stream";Wn.push({type:"file",data:gn,mimeType:zn,filename:mh(zn)})}}if(Wn.length>0){let qn=c(),mn=Et,$r={id:`agent-media-${typeof mn=="string"&&mn.length>0?`${mn}-${qn}`:String(qn)}`,role:"assistant",content:"",contentParts:Wn,createdAt:new Date().toISOString(),streaming:!1,sequence:qn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:ze}};f($r);let gn=g;gn&&(gn.streaming=!1,f(gn)),g=null,v.current=null}}else if(rt==="execution_complete"){let $=(F=w.kind)!=null?F:Lt;$==="agent"&&me&&(me.status=w.success?"complete":"error",me.completedAt=ee(w.completedAt),me.stopReason=w.stopReason);let _=g;_&&($==="flow"&&_.streaming!==!1?ce(_):(_.streaming=!1,f(_)),g=null),C=null,I="",Ke=null,n({type:"status",status:"idle"})}else if(rt==="execution_error"){let $=typeof w.error=="string"?w.error:(Ar=(Ko=w.error)==null?void 0:Ko.message)!=null?Ar:"Execution error";n({type:"error",error:new Error($)})}else if(rt!=="ping"){if(rt==="approval_start"){let $=(Tr=w.approvalId)!=null?Tr:`approval-${c()}`,_={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Or=me==null?void 0:me.agentId)!=null?Or:"virtual",executionId:(cr=(Er=w.executionId)!=null?Er:me==null?void 0:me.executionId)!=null?cr:"",toolName:(Go=w.toolName)!=null?Go:"",toolType:w.toolType,description:(jn=w.description)!=null?jn:`Execute ${(ga=w.toolName)!=null?ga:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f(_)}else if(rt==="step_await"&&w.awaitReason==="approval_required"){let $=(Un=w.approvalId)!=null?Un:`approval-${c()}`,_={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(dr=me==null?void 0:me.agentId)!=null?dr:"virtual",executionId:(To=(pr=w.executionId)!=null?pr:me==null?void 0:me.executionId)!=null?To:"",toolName:(Fr=w.toolName)!=null?Fr:"",toolType:w.toolType,description:(Mr=w.description)!=null?Mr:`Execute ${(yn=w.toolName)!=null?yn:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f(_)}else if(rt==="approval_complete"){let $=w.approvalId;if($){let K={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(Jo=w.decision)!=null?Jo:"approved",agentId:(Eo=me==null?void 0:me.agentId)!=null?Eo:"virtual",executionId:(fa=(Qo=w.executionId)!=null?Qo:me==null?void 0:me.executionId)!=null?fa:"",toolName:(Xo=w.toolName)!=null?Xo:"",description:(ha=w.description)!=null?ha:"",resolvedAt:Date.now()}};f(K)}}else if(rt==="artifact_start"||rt==="artifact_delta"||rt==="artifact_update"||rt==="artifact_complete"){if(rt==="artifact_start"){let $=w.artifactType,_=String(w.id),K=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:_,artifactType:$,title:K,component:typeof w.component=="string"?w.component:void 0}),ne.set(_,{markdown:"",title:K}),!Q.has(_)){Q.add(_);let fe={id:`artifact-ref-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:_,title:K,artifactType:$,status:"streaming"}})};ae.set(_,fe),f(fe)}}else if(rt==="artifact_delta"){let $=String(w.id),_=typeof w.delta=="string"?w.delta:String((Yo=w.delta)!=null?Yo:"");n({type:"artifact_delta",id:$,artDelta:_});let K=ne.get($);K&&(K.markdown+=_)}else if(rt==="artifact_update"){let $=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:$,component:typeof w.component=="string"?w.component:void 0})}else if(rt==="artifact_complete"){let $=String(w.id);n({type:"artifact_complete",id:$});let _=ae.get($);if(_){_.streaming=!1;try{let K=JSON.parse((ft=_.rawContent)!=null?ft:"{}");if(K.props){K.props.status="complete";let fe=ne.get($);fe!=null&&fe.markdown&&(K.props.markdown=fe.markdown)}_.rawContent=JSON.stringify(K)}catch{}ne.delete($),f(_),ae.delete($)}}}else if(rt==="transcript_insert"){let $=w.message;if(!$||typeof $!="object")continue;let _=String((Ts=$.id)!=null?Ts:`msg-${c()}`),K=$.role,_e={id:_,role:K==="user"?"user":K==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(f(_e),_e.rawContent)try{let Ye=JSON.parse(_e.rawContent),Et=(er=Ye==null?void 0:Ye.props)==null?void 0:er.artifactId;typeof Et=="string"&&Q.add(Et)}catch{}g=null,v.current=null,J.delete(_),ie.delete(_)}else if(rt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let $=typeof w.error=="string"?w.error:((Rn=w.error)==null?void 0:Rn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error($)});let _=g;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"})}}else if(rt==="step_error"||rt==="dispatch_error"||rt==="flow_error"){let $=null;if(w.error instanceof Error)$=w.error;else if(rt==="dispatch_error"){let _=(ya=w.message)!=null?ya:w.error;_!=null&&_!==""&&($=new Error(String(_)))}else{let _=w.error;typeof _=="string"&&_!==""?$=new Error(_):_!=null&&typeof _=="object"&&"message"in _&&($=new Error(String((ba=_.message)!=null?ba:_)))}if($){n({type:"error",error:$});let _=g;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"})}}}}}X.length=0};;){let{done:T,value:ue}=await s.read();if(T)break;a+=o.decode(ue,{stream:!0});let Me=a.split(`
8
+ ${e.description}`:"");return window.confirm(n)},Gf=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)}},Jf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Qf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Xf,ARR as Yf,OBJ as Zf,STR as eh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Hr=(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 La="ask_user_question",zs=8,gs="data-persona-ask-sheet-for",th="Other",nh="Other\u2026",Nu="Type your own answer here",Ou="Send",rh="Next",oh="Back",sh="Submit all",ah="Skip",ih=3,_i="data-ask-current-index",$i="data-ask-question-count",Fu="data-ask-answers",ji="data-ask-grouped",_u="data-ask-layout",lh=e=>e.layout==="pills"?"pills":"rows",ch=e=>e.getAttribute(_u)==="pills"?"pills":"rows",Du=!1,$u=e=>e.replace(/["\\]/g,"\\$&"),mo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===La,Pa=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},go=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=Xf(o,eh|Zf|Yf);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&&!Du&&(Du=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},dh=e=>{var t;return(t=Vs(e)[0])!=null?t:null},ph=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},ju=(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))},Uu=(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},uh=(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=Uu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},mh=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},gh=(e,t,n,r)=>{var p,u,f;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(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<ih;g++)s.appendChild(mh(r));return s}if(d.forEach((g,v)=>{s.appendChild(uh(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?th:nh;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(p=t.freeTextPlaceholder)!=null?p:Nu,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),x.appendChild(T),v.appendChild(x);let S=Uu(r,a,d.length);S&&v.appendChild(S),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=(f=t.freeTextLabel)!=null?f:g,s.appendChild(v)}}return s},qu=(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:Nu,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:Ou,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},fh=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:Ou,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},hh=(e,t,n)=>{var l,p,u,f;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:oh,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:ah,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:sh:(f=n.nextLabel)!=null?f:rh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},_o=e=>{let t=e.getAttribute(Fu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},zu=(e,t)=>{e.setAttribute(Fu,JSON.stringify(t))},sr=e=>{var n;let t=Number((n=e.getAttribute(_i))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},yh=(e,t)=>{e.setAttribute(_i,String(Math.max(0,Math.floor(t))))},fs=e=>{var n;let t=Number((n=e.getAttribute($i))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},fo=e=>e.getAttribute(ji)==="true",bh=(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},xh=(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)))},Ia=(e,t)=>{let{payload:n}=go(t),r=Vs(n),o=_o(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},Vu=e=>{let t=_o(e),n=sr(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=""},Ku=e=>{if(!fo(e))return;let t=_o(e),n=sr(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}},Ui=(e,t,n)=>{let r=Pa(n),o=ch(e),{payload:s,complete:a}=go(t),i=fo(e),d=sr(e),l=fs(e),p=i?ph(s,d):dh(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let k=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=k,v.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let k=gh(p,r,a,o);x.replaceWith(k)}if(o!=="rows"){let k=e.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(qu(r,o))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!T?e.appendChild(fh(r)):(!u||i)&&T&&T.remove(),e.setAttribute("data-multi-select",u?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let k=hh(d,l,r);S?S.replaceWith(k):e.appendChild(k)}else S&&S.remove();Vu(e),Ku(e)},vh=(e,t,n)=>{let r=Pa(t),o=lh(r),s=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=bh(e,a),p=d?xh(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(gs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute($i,String(i)),u.setAttribute(_i,String(p)),u.setAttribute(ji,d?"true":"false"),u.setAttribute(_u,o),zu(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`),ju(u,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),u.appendChild(f);let T=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),u.appendChild(T),o!=="rows"&&u.appendChild(qu(r,o)),Ui(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},wh=(e,t,n)=>{let{payload:r}=go(t),o=Math.max(1,Vs(r).length);o>fs(e)&&(e.setAttribute($i,String(o)),o>1&&!fo(e)&&e.setAttribute(ji,"true")),Ui(e,t,n)},Ch=(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=Pa(t);ju(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=go(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ks=(e,t,n)=>{if(!n||!mo(e)||Pa(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${gs}]`).forEach(l=>{l.getAttribute(gs)!==o&&l.remove()});let a=n.querySelector(`[${gs}="${$u(o)}"]`);if(a){wh(a,e,t);return}let{payload:i}=go(e),d=vh(e,t,i);n.appendChild(d)},$o=(e,t)=>{if(!e)return;let n=t?`[${gs}="${$u(t)}"]`:`[${gs}]`;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)})},qi=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),ho=(e,t)=>{let n=_o(e),r=sr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,zu(e,n),Vu(e),Ku(e)},Ra=(e,t,n,r)=>{let o=fs(e),s=Math.max(0,Math.min(o-1,r));yh(e,s),Ui(e,t,n)};var Br="suggest_replies";var Gu={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:Br,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:Gu,origin:"sdk",annotations:{readOnlyHint:!0}},Vi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Wa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Br},Ju=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},Ki=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Wa(r))continue;let o=Ju((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Qu=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 Xu={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},Yu={name:La,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:Xu,origin:"sdk",annotations:{readOnlyHint:!0}},Ha=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(Yu),Qu(e)&&t.push(zi),t};import{parse as Zu,STR as em,OBJ as tm}from"partial-json";var Ba=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),yo=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)}},Ah=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`},nm=e=>e.status==="complete"?Ah(e):e.status==="pending"?"Waiting":"",Sh=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 rm=e=>e.status==="complete"?Sh(e):"Using tool...",Da=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 Da(t)},Na=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 Da(t)},Gi=(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)},Oa=(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})},Eh=()=>{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
+ `).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()=>{}}},Qs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ji=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Eh();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)}},Xi=()=>{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=Zu(n,em|tm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Ba(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Ba(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Th=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ba(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ba(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=Zu(s,em|tm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Yi=()=>{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 om="4.2.0";var yr=om;var kh="https://api.runtype.com/v1/dispatch",Fa="https://api.runtype.com";function Lh(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 Zi=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 Ph(e){switch(e){case"json":return Xi;case"regex-json":return Qi;case"xml":return Yi;default:return Ji}}var sm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Ih(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=sm(n);if(!sm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Qs(e);return Qs(t)!==null&&a===null?t:e}var hs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=t.apiUrl)!=null?n:kh,this.headers={"Content-Type":"application/json","X-Persona-Version":yr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Ph(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}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Fa}/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 s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":yr},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Fa}/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.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(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 E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Zi).map(E=>{var L,C,R;return{id:E.id,role:E.role,content:(R=(C=(L=E.contentParts)!=null?L:E.llmContent)!=null?C:E.rawContent)!=null?R:E.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}},f=l.clientTools,g=!!(f&&f.length>0),v=g?Bu(f):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,T=g&&x&&this.lastSentClientToolsFingerprint===v,S=!1,k=null,M;for(let E=0;;E++){let C={...u,...g&&(S||!T)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":yr},body:JSON.stringify(C),signal:r.signal}),M.status===409&&E===0&&g){let R=await M.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}k=R!=null?R:{error:"Chat request failed"}}break}if(!M.ok){let E=k!=null?k:await M.json().catch(()=>({error:"Chat request failed"}));if(M.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(M.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let L=new Error(E.error||"Failed to send message");throw n({type:"error",error:L}),L}if(!M.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(M.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$/,""))||Fa}/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(/\/+$/,""))||Fa}/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 s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Zi).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ha(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var s,a;let r={messages:t.slice().filter(Zi).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ha(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,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 un,Dt,Yt,Nr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=H=>{let V=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,pe=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Be=H.tools?H.tools.map(je=>({...je,chunks:je.chunks?[...je.chunks]:void 0})):void 0;return{...H,reasoning:V,toolCall:pe,tools:Be}},u=H=>{if(H.role!=="assistant"||H.variant)return!0;let V=Array.isArray(H.contentParts)&&H.contentParts.length>0,pe=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||V||pe||!!H.stopReason},f=H=>{u(H)&&n({type:"message",message:p(H)})},g=null,v=null,x={current:null},T={current:null},S=null,k="",M=new Map,E=new Map,L=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=H=>{if(H==null)return null;try{return String(H)}catch{return null}},O=H=>{var V,pe,Be,je,De;return W((De=(je=(Be=(pe=(V=H.stepId)!=null?V:H.step_id)!=null?pe:H.step)!=null?Be:H.parentId)!=null?je:H.flowStepId)!=null?De:H.flow_step_id)},N=H=>{var V,pe,Be,je,De,Le,it;return W((it=(Le=(De=(je=(Be=(pe=(V=H.callId)!=null?V:H.call_id)!=null?pe:H.requestId)!=null?Be:H.request_id)!=null?je:H.toolCallId)!=null?De:H.tool_call_id)!=null?Le:H.stepId)!=null?it:H.step_id)},Z=r,Ae=!1,de=()=>{if(g)return g;let H,V=S;return!Ae&&Z?(H=Z,Ae=!0):Z&&V?H=`${Z}_${V}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:H,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},ee=(H,V)=>{F.lastId=V,H&&F.byStep.set(H,V)},xe=(H,V)=>{var De;let pe=(De=H.reasoningId)!=null?De:H.id,Be=O(H);if(pe){let Le=String(pe);return ee(Be,Le),Le}if(Be){let Le=F.byStep.get(Be);if(Le)return F.lastId=Le,Le}if(F.lastId&&!V)return F.lastId;if(!V)return null;let je=`reason-${l()}`;return ee(Be,je),je},Te=H=>{let V=C.get(H);if(V)return V;let pe={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:H,status:"streaming",chunks:[]}};return C.set(H,pe),f(pe),pe},ne=(H,V)=>{j.lastId=V,H&&j.byCall.set(H,V)},be=new Set,le=new Map,oe=new Set,re=new Map,We=H=>{if(!H)return!1;let V=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return V==="emit_artifact_markdown"||V==="emit_artifact_component"},Oe=(H,V)=>{var De;let pe=(De=H.toolId)!=null?De:H.id,Be=N(H);if(pe){let Le=String(pe);return ne(Be,Le),Le}if(Be){let Le=j.byCall.get(Be);if(Le)return j.lastId=Le,Le}if(j.lastId&&!V)return j.lastId;if(!V)return null;let je=`tool-${l()}`;return ne(Be,je),je},K=H=>{let V=R.get(H);if(V)return V;let pe={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:H,status:"pending"}};return R.set(H,pe),f(pe),pe},G=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let V=Number(H);if(!Number.isNaN(V)&&Number.isFinite(V))return V;let pe=Date.parse(H);if(!Number.isNaN(pe))return pe}return Date.now()},ve=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},X=new Map,ie=new Map,Re=new Map,ge=(H,V,pe)=>{var it;let Be=Re.get(H);Be||(Be=[],Re.set(H,Be));let je=0,De=Be.length;for(;je<De;){let It=je+De>>>1;Be[It].seq<V?je=It+1:De=It}((it=Be[je])==null?void 0:it.seq)===V?Be[je]={seq:V,text:pe}:Be.splice(je,0,{seq:V,text:pe});let Le="";for(let It=0;It<Be.length;It++)Le+=Be[It].text;return Le},Ge=(H,V)=>{let pe=ve(V),Be=ie.get(H.id),je=Ih(Be,pe);H.rawContent=je;let De=X.get(H.id),Le=P=>{var Me;let ce=(Me=H.content)!=null?Me:"";P.trim()!==""&&(ce.trim().length===0||P.startsWith(ce)||P.trimStart().startsWith(ce.trim()))&&(H.content=P)},it=()=>{var P;if(De){let ce=(P=De.close)==null?void 0:P.call(De);ce instanceof Promise&&ce.catch(()=>{})}X.delete(H.id),ie.delete(H.id),H.streaming=!1,f(H)};if(!De){Le(pe),it();return}let It=Qs(je);if(It!==null&&It.trim()!==""){Le(It),it();return}let ht=P=>{var Et;let ce=typeof P=="string"?P:(Et=P==null?void 0:P.text)!=null?Et:null;if(ce!==null&&ce.trim()!=="")return ce;let Me=De.getExtractedText();return Me!==null&&Me.trim()!==""?Me:pe},Rt;try{Rt=De.processChunk(je)}catch{Le(pe),it();return}if(Rt instanceof Promise){Rt.then(P=>{Le(ht(P)),it()}).catch(()=>{Le(pe),it()});return}Le(ht(Rt)),it()},nt=null,Pt=(H,V,pe,Be)=>{var It;H.rawContent=V,X.has(H.id)||X.set(H.id,this.createStreamParser());let je=X.get(H.id),De=V.trim().startsWith("{")||V.trim().startsWith("[");if(De&&ie.set(H.id,V),je.__isPlainTextParser===!0){H.content=Be!==void 0?V:H.content+pe,ie.delete(H.id),X.delete(H.id),H.rawContent=void 0,f(H);return}let it=je.processChunk(V);if(it instanceof Promise)it.then(ht=>{var P;let Rt=typeof ht=="string"?ht:(P=ht==null?void 0:ht.text)!=null?P:null;Rt!==null&&Rt.trim()!==""?(H.content=Rt,f(H)):!De&&!V.trim().startsWith("<")&&(H.content=Be!==void 0?V:H.content+pe,ie.delete(H.id),X.delete(H.id),H.rawContent=void 0,f(H))}).catch(()=>{H.content=Be!==void 0?V:H.content+pe,ie.delete(H.id),X.delete(H.id),H.rawContent=void 0,f(H)});else{let ht=typeof it=="string"?it:(It=it==null?void 0:it.text)!=null?It:null;ht!==null&&ht.trim()!==""?(H.content=ht,f(H)):!De&&!V.trim().startsWith("<")&&(H.content=Be!==void 0?V:H.content+pe,ie.delete(H.id),X.delete(H.id),H.rawContent=void 0,f(H))}},Ye=(H,V)=>{var It,ht;let pe=V!=null?V:H.content;if(pe==null||pe===""){H.streaming=!1,f(H);return}let Be=ie.get(H.id),je=Be!=null?Be:ve(pe);H.rawContent=je;let De=X.get(H.id),Le=null,it=!1;if(De&&(Le=De.getExtractedText(),Le===null&&(Le=Qs(je)),Le===null)){let Rt=De.processChunk(je);Rt instanceof Promise?(it=!0,Rt.then(P=>{var Me;let ce=typeof P=="string"?P:(Me=P==null?void 0:P.text)!=null?Me:null;ce!==null&&(H.content=ce,H.streaming=!1,X.delete(H.id),ie.delete(H.id),f(H))}).catch(()=>{})):Le=typeof Rt=="string"?Rt:(It=Rt==null?void 0:Rt.text)!=null?It:null}if(!it){Le!==null&&Le.trim()!==""?H.content=Le:ie.has(H.id)||(H.content=ve(pe));let Rt=X.get(H.id);if(Rt){let P=(ht=Rt.close)==null?void 0:ht.call(Rt);P instanceof Promise&&P.catch(()=>{}),X.delete(H.id)}ie.delete(H.id),H.streaming=!1,f(H)}},_e=(H,V,pe)=>{let Be=E.get(H);if(Be)return Be;let je={id:`nested-${V}-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...pe?{variant:pe}:{},...pe==="reasoning"?{reasoning:{id:H,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:V}};return E.set(H,je),f(je),je},J=[],Ve,ze=new Map,we=0,Se="agent",Ze=null,Qe=null,Ee=new Map,$e=(un=this.config.iterationDisplay)!=null?un:"separate";for(Ve=()=>{var H,V,pe,Be,je,De,Le,it,It,ht,Rt,P,ce,Me,Et,et,Ut,bn,bt,xt,Wt,vt,mn,$t,On,En,Tn,xn,Mn,cr,wt,xr,vr,Or,dr,pt,So,wr,Eo,Hn,Xo,Xr,Fr,Yr,Zr,To,Mo,eo,yt,Fn,_n,kn,Ct,Xn,Yn,$n,to,_r,no,jn,Ht,Ln,Zn,ro,$r,oo,he,Bn,Cr,ut,sn,an,Ar,Ls,jr,ko,Sr,$,Yo,Er,Tr,Ur,Mr,pr,Zo,xa,Un,qn,ur,mr,Lo,qr,vn,kr,es,Po,ts,va,ns,wa,rs,dt,Ps,er,Dn;for(let os=0;os<J.length;os++){let st=J[os].payloadType,w=J[os].payload;if(st==="reasoning_start"){let q=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(q&&U){M.set(q,U),_e(q,U,"reasoning");continue}let Q=(H=xe(w,!0))!=null?H:`reason-${l()}`,fe=Te(Q);fe.reasoning=(V=fe.reasoning)!=null?V:{id:Q,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Be=fe.reasoning.startedAt)!=null?Be:G((pe=w.startedAt)!=null?pe:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",f(fe)}else if(st==="reasoning_delta"){let q=typeof w.id=="string"?w.id:null;if(q&&M.has(q)&&E.has(q)){let Fe=E.get(q),mt=(Le=(De=(je=w.reasoningText)!=null?je:w.text)!=null?De:w.delta)!=null?Le:"";mt&&w.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(mt)),f(Fe));continue}let U=(It=(it=xe(w,!1))!=null?it:xe(w,!0))!=null?It:`reason-${l()}`,Q=Te(U);Q.reasoning=(ht=Q.reasoning)!=null?ht:{id:U,status:"streaming",chunks:[]},Q.reasoning.startedAt=(P=Q.reasoning.startedAt)!=null?P:G((Rt=w.startedAt)!=null?Rt:w.timestamp);let fe=(Et=(Me=(ce=w.reasoningText)!=null?ce:w.text)!=null?Me:w.delta)!=null?Et:"";if(fe&&w.hidden!==!0){let Fe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Fe!==void 0){let mt=ge(U,Fe,String(fe));Q.reasoning.chunks=[mt]}else Q.reasoning.chunks.push(String(fe))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=G((et=w.completedAt)!=null?et:w.timestamp);let Fe=(Ut=Q.reasoning.startedAt)!=null?Ut:Date.now();Q.reasoning.durationMs=Math.max(0,((bn=Q.reasoning.completedAt)!=null?bn:Date.now())-Fe)}Q.streaming=Q.reasoning.status!=="complete",f(Q)}else if(st==="reasoning_complete"){let q=typeof w.id=="string"?w.id:null;if(q&&M.has(q)&&E.has(q)){let mt=E.get(q);if(mt.reasoning){let Lt=typeof w.text=="string"?w.text:"";Lt&&mt.reasoning.chunks.length===0&&mt.reasoning.chunks.push(Lt),mt.reasoning.status="complete",mt.streaming=!1,f(mt)}M.delete(q),E.delete(q);continue}let U=(xt=(bt=xe(w,!1))!=null?bt:xe(w,!0))!=null?xt:`reason-${l()}`,Q=typeof w.text=="string"?w.text:"";!C.get(U)&&(Q||w.scope==="loop")&&Te(U);let fe=C.get(U);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),Q&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(Q),fe.reasoning.status="complete",fe.reasoning.completedAt=G((Wt=w.completedAt)!=null?Wt:w.timestamp);let mt=(vt=fe.reasoning.startedAt)!=null?vt:Date.now();fe.reasoning.durationMs=Math.max(0,((mn=fe.reasoning.completedAt)!=null?mn:Date.now())-mt),fe.streaming=!1,f(fe)}let Fe=O(w);Fe&&F.byStep.delete(Fe)}else if(st==="tool_start"){g&&(g.streaming=!1,f(g),g=null),typeof w.iteration=="number"&&(we=w.iteration);let q=(On=($t=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?$t:Oe(w,!0))!=null?On:`tool-${l()}`,U=(En=w.toolName)!=null?En:w.name;if(We(U)){be.add(q);continue}ne(N(w),q);let Q=K(q),fe=(Tn=Q.toolCall)!=null?Tn:{id:q,status:"pending"};fe.name=U!=null?U:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(Mn=fe.startedAt)!=null?Mn:G((xn=w.startedAt)!=null?xn:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,Q.toolCall=fe,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),f(Q)}else if(st==="tool_output_delta"){let q=(wt=(cr=Oe(w,!1))!=null?cr:Oe(w,!0))!=null?wt:`tool-${l()}`;if(be.has(q))continue;let U=K(q),Q=(xr=U.toolCall)!=null?xr:{id:q,status:"running"};Q.startedAt=(Or=Q.startedAt)!=null?Or:G((vr=w.startedAt)!=null?vr:w.timestamp);let fe=(So=(pt=(dr=w.text)!=null?dr:w.delta)!=null?pt:w.message)!=null?So:"";fe&&(Q.chunks=(wr=Q.chunks)!=null?wr:[],Q.chunks.push(String(fe))),Q.status="running",U.toolCall=Q,U.streaming=!0;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Xo=U.agentMetadata)!=null?Xo:{executionId:(Eo=Fe==null?void 0:Fe.executionId)!=null?Eo:w.executionId,iteration:(Hn=Fe==null?void 0:Fe.iteration)!=null?Hn:w.iteration}),f(U)}else if(st==="tool_complete"){let q=(Fr=(Xr=Oe(w,!1))!=null?Xr:Oe(w,!0))!=null?Fr:`tool-${l()}`;if(be.has(q)){be.delete(q);continue}let U=K(q),Q=(Yr=U.toolCall)!=null?Yr:{id:q,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=G((Zr=w.completedAt)!=null?Zr:w.timestamp);let fe=(To=w.duration)!=null?To:w.executionTime;if(typeof fe=="number")Q.durationMs=fe;else{let Lt=(Mo=Q.startedAt)!=null?Mo:Date.now();Q.durationMs=Math.max(0,((eo=Q.completedAt)!=null?eo:Date.now())-Lt)}U.toolCall=Q,U.streaming=!1;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(_n=U.agentMetadata)!=null?_n:{executionId:(yt=Fe==null?void 0:Fe.executionId)!=null?yt:w.executionId,iteration:(Fn=Fe==null?void 0:Fe.iteration)!=null?Fn:w.iteration}),f(U);let mt=N(w);mt&&j.byCall.delete(mt)}else if(st==="await"&&w.toolName){let q=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(kn=q!=null?q:w.toolId)!=null?kn:`local-${l()}`,Q=K(U),fe=w.toolName,Fe=w.origin==="webmcp"&&!Fo(fe)?`webmcp:${fe}`:fe,mt=Fo(Fe),Lt=(Ct=Q.toolCall)!=null?Ct:{id:U,status:"pending"};Lt.name=Fe,Lt.args=w.parameters,Lt.status=mt?"running":"complete",Lt.chunks=(Xn=Lt.chunks)!=null?Xn:[],Lt.startedAt=(to=Lt.startedAt)!=null?to:G(($n=(Yn=w.startedAt)!=null?Yn:w.timestamp)!=null?$n:w.awaitedAt),mt?(Lt.completedAt=void 0,Lt.duration=void 0,Lt.durationMs=void 0):Lt.completedAt=(_r=Lt.completedAt)!=null?_r:Lt.startedAt,Q.toolCall=Lt,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(jn=w.executionId)!=null?jn:(no=Q.agentMetadata)==null?void 0:no.executionId,awaitingLocalTool:!0,...q?{webMcpToolCallId:q}:{}},f(Q)}else if(st==="text_start"){let q=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(q&&U){M.set(q,U);continue}let Q=g;Q&&(Se==="flow"?(Ye(Q),nt=Q):(Q.streaming=!1,f(Q)),g=null),S=typeof w.id=="string"?w.id:S,k=""}else if(st==="text_delta"){let q=typeof w.id=="string"?w.id:null,U=q?M.get(q):void 0;if(q&&U){let fe=typeof w.delta=="string"?w.delta:"",Fe=((Ht=L.get(q))!=null?Ht:"")+fe;if(L.set(q,Fe),Fe.trim()==="")continue;let mt=_e(q,U);mt.agentMetadata={...mt.agentMetadata,executionId:w.executionId,parentToolId:U},Pt(mt,Fe,fe,void 0);continue}if(S=typeof w.id=="string"?w.id:S,Se==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(k+=fe,k.trim()==="")continue;let Fe=de();Fe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Pt(Fe,k,fe,void 0),v=Fe;continue}let Q=de();Q.content+=(Ln=w.delta)!=null?Ln:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ze!=null?Ze:void 0,agentName:Qe==null?void 0:Qe.agentName},v=Q,f(Q)}else if(st==="text_complete"){let q=typeof w.id=="string"?w.id:null;if(q&&M.has(q)){let Q=E.get(q);Q&&Ye(Q),M.delete(q),L.delete(q),E.delete(q);continue}let U=g;U&&(Se==="flow"?(Ye(U),nt=U):(((Zn=U.content)!=null?Zn:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,f(U)),g=null),S=null,k=""}else if(st==="step_complete"){let q=w.stepType,U=w.executionType;if(q==="tool"||U==="context")continue;if(w.success===!1){let Q=w.error,fe=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((ro=Q.message)!=null?ro:"Step failed"):"Step failed";n({type:"error",error:new Error(fe)});let Fe=g;Fe&&Fe.streaming&&(Fe.streaming=!1,f(Fe)),n({type:"status",status:"idle"});continue}{let Q=nt;nt=null;let fe=w.stopReason,Fe=($r=w.result)==null?void 0:$r.response;if(Q)fe&&(Q.stopReason=fe),Fe!=null?Ge(Q,Fe):Q.streaming!==!1&&(X.delete(Q.id),ie.delete(Q.id),Q.streaming=!1,f(Q));else{let mt=Fe!=null&&Fe!=="";if(mt||fe){let Lt=de();fe&&(Lt.stopReason=fe),mt?Ye(Lt,Fe):(Lt.streaming=!1,f(Lt))}}continue}}else if(st==="execution_start")Se=w.kind==="flow"?"flow":"agent",Se==="agent"&&(Qe={executionId:w.executionId,agentId:(oo=w.agentId)!=null?oo:"virtual",agentName:(he=w.agentName)!=null?he:"",status:"running",currentIteration:0,maxTurns:(Bn=w.maxTurns)!=null?Bn:1,startedAt:G(w.startedAt)});else if(st==="turn_start"){let q=typeof w.iteration=="number"?w.iteration:we;if(q!==we){if(Qe&&(Qe.currentIteration=q),$e==="separate"&&q>1){let U=g;U&&(U.streaming=!1,f(U),Ee.set(q-1,U),g=null)}we=q}Ze=typeof w.id=="string"?w.id:null,v=null}else if(st==="tool_input_delta"){let q=(Cr=w.toolCallId)!=null?Cr:j.lastId;if(q){let U=R.get(q);U!=null&&U.toolCall&&(U.toolCall.chunks=(ut=U.toolCall.chunks)!=null?ut:[],U.toolCall.chunks.push((sn=w.delta)!=null?sn:""),f(U))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let q=w.stopReason,U=g!=null?g:v;if(q&&U!==null){let Q=w.id;(!Q||((an=U.agentMetadata)==null?void 0:an.turnId)===Q)&&(U.stopReason=q,f(U))}Ze===w.id&&(Ze=null)}else if(st==="media_start"){let q=String(w.id);ze.set(q,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(st==="media_delta"){let q=ze.get(String(w.id));q&&typeof w.delta=="string"&&q.parts.push(w.delta)}else if(st==="media_complete"){let q=String(w.id),U=ze.get(q);ze.delete(q);let Q=(Ls=(Ar=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ar:U==null?void 0:U.mediaType)!=null?Ls:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Fe=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,mt=null;if(fe)mt={type:"media",data:fe,mediaType:Q};else if(Fe){let gn=Q.toLowerCase();mt={type:gn==="image"||gn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:Q}}let Lt=(jr=w.toolCallId)!=null?jr:U==null?void 0:U.toolCallId,zn=mt?[mt]:[],Lr=[];for(let gn of zn){if(!gn||typeof gn!="object")continue;let Zt=gn,so=typeof Zt.type=="string"?Zt.type:void 0,ao=typeof Zt.mediaType=="string"?Zt.mediaType.toLowerCase():"",Pn=null,In="";if(so==="media"){let wn=typeof Zt.data=="string"?Zt.data:void 0;if(!wn)continue;In=ao.length>0?ao:"application/octet-stream",Pn=`data:${In};base64,${wn}`}else if(so==="image-url"){let wn=typeof Zt.url=="string"?Zt.url:void 0;if(!wn)continue;In=ao,Pn=wn}else if(so==="file-url"){let wn=typeof Zt.url=="string"?Zt.url:void 0;if(!wn)continue;In=ao,Pn=wn}else continue;if(Pn)if(so==="image-url"||In.startsWith("image/"))Lr.push({type:"image",image:Pn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))Lr.push({type:"audio",audio:Pn,mimeType:In});else if(In.startsWith("video/"))Lr.push({type:"video",video:Pn,mimeType:In});else{let wn=In||"application/octet-stream";Lr.push({type:"file",data:Pn,mimeType:wn,filename:Lh(wn)})}}if(Lr.length>0){let gn=l(),Zt=Lt,ao={id:`agent-media-${typeof Zt=="string"&&Zt.length>0?`${Zt}-${gn}`:String(gn)}`,role:"assistant",content:"",contentParts:Lr,createdAt:new Date().toISOString(),streaming:!1,sequence:gn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};f(ao);let Pn=g;Pn&&(Pn.streaming=!1,f(Pn)),g=null,x.current=null}}else if(st==="execution_complete"){let q=(ko=w.kind)!=null?ko:Se;q==="agent"&&Qe&&(Qe.status=w.success?"complete":"error",Qe.completedAt=G(w.completedAt),Qe.stopReason=w.stopReason);let U=g;U&&(q==="flow"&&U.streaming!==!1?Ye(U):(U.streaming=!1,f(U)),g=null),S=null,k="",nt=null,n({type:"status",status:"idle"})}else if(st==="execution_error"){let q=typeof w.error=="string"?w.error:($=(Sr=w.error)==null?void 0:Sr.message)!=null?$:"Execution error";n({type:"error",error:new Error(q)})}else if(st!=="ping"){if(st==="approval_start"){let q=(Yo=w.approvalId)!=null?Yo:`approval-${l()}`,U={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(Er=Qe==null?void 0:Qe.agentId)!=null?Er:"virtual",executionId:(Ur=(Tr=w.executionId)!=null?Tr:Qe==null?void 0:Qe.executionId)!=null?Ur:"",toolName:(Mr=w.toolName)!=null?Mr:"",toolType:w.toolType,description:(Zo=w.description)!=null?Zo:`Execute ${(pr=w.toolName)!=null?pr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f(U)}else if(st==="step_await"&&w.awaitReason==="approval_required"){let q=(xa=w.approvalId)!=null?xa:`approval-${l()}`,U={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:"pending",agentId:(Un=Qe==null?void 0:Qe.agentId)!=null?Un:"virtual",executionId:(ur=(qn=w.executionId)!=null?qn:Qe==null?void 0:Qe.executionId)!=null?ur:"",toolName:(mr=w.toolName)!=null?mr:"",toolType:w.toolType,description:(qr=w.description)!=null?qr:`Execute ${(Lo=w.toolName)!=null?Lo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};f(U)}else if(st==="approval_complete"){let q=w.approvalId;if(q){let Q={id:`approval-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:q,status:(vn=w.decision)!=null?vn:"approved",agentId:(kr=Qe==null?void 0:Qe.agentId)!=null?kr:"virtual",executionId:(Po=(es=w.executionId)!=null?es:Qe==null?void 0:Qe.executionId)!=null?Po:"",toolName:(ts=w.toolName)!=null?ts:"",description:(va=w.description)!=null?va:"",resolvedAt:Date.now()}};f(Q)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let q=w.artifactType,U=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:q,title:Q,component:typeof w.component=="string"?w.component:void 0}),re.set(U,{markdown:"",title:Q}),!oe.has(U)){oe.add(U);let fe={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:Q,artifactType:q,status:"streaming"}})};le.set(U,fe),f(fe)}}else if(st==="artifact_delta"){let q=String(w.id),U=typeof w.delta=="string"?w.delta:String((ns=w.delta)!=null?ns:"");n({type:"artifact_delta",id:q,artDelta:U});let Q=re.get(q);Q&&(Q.markdown+=U)}else if(st==="artifact_update"){let q=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:q,component:typeof w.component=="string"?w.component:void 0})}else if(st==="artifact_complete"){let q=String(w.id);n({type:"artifact_complete",id:q});let U=le.get(q);if(U){U.streaming=!1;try{let Q=JSON.parse((wa=U.rawContent)!=null?wa:"{}");if(Q.props){Q.props.status="complete";let fe=re.get(q);fe!=null&&fe.markdown&&(Q.props.markdown=fe.markdown)}U.rawContent=JSON.stringify(Q)}catch{}re.delete(q),f(U),le.delete(q)}}}else if(st==="transcript_insert"){let q=w.message;if(!q||typeof q!="object")continue;let U=String((rs=q.id)!=null?rs:`msg-${l()}`),Q=q.role,Fe={id:U,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof q.content=="string"?q.content:"",rawContent:typeof q.rawContent=="string"?q.rawContent:void 0,createdAt:typeof q.createdAt=="string"?q.createdAt:new Date().toISOString(),streaming:q.streaming===!0,...typeof q.variant=="string"?{variant:q.variant}:{},sequence:l()};if(f(Fe),Fe.rawContent)try{let mt=JSON.parse(Fe.rawContent),Lt=(dt=mt==null?void 0:mt.props)==null?void 0:dt.artifactId;typeof Lt=="string"&&oe.add(Lt)}catch{}g=null,x.current=null,X.delete(U),ie.delete(U)}else if(st==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let q=typeof w.error=="string"?w.error:((Ps=w.error)==null?void 0:Ps.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(q)});let U=g;U&&U.streaming&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let q=null;if(w.error instanceof Error)q=w.error;else if(st==="dispatch_error"){let U=(er=w.message)!=null?er:w.error;U!=null&&U!==""&&(q=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?q=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(q=new Error(String((Dn=U.message)!=null?Dn:U)))}if(q){n({type:"error",error:q});let U=g;U&&U.streaming&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:H,value:V}=await o.read();if(H)break;a+=s.decode(V,{stream:!0});let pe=a.split(`
10
12
 
11
- `);a=(yr=Me.pop())!=null?yr:"";for(let Te of Me){let Ie=Te.split(`
12
- `),tt="message",Je="";for(let U of Ie)U.startsWith("event:")?tt=U.replace("event:","").trim():U.startsWith("data:")&&(Je+=U.replace("data:","").trim());if(!Je)continue;let pt;try{pt=JSON.parse(Je)}catch(U){n({type:"error",error:U instanceof Error?U:new Error("Failed to parse chat stream payload")});continue}let It=tt!=="message"?tt:(hn=pt.type)!=null?hn:"message";if((Ve=this.onSSEEvent)==null||Ve.call(this,It,pt),this.parseSSEEvent){v.current=g;let U=await this.handleCustomSSEEvent(pt,n,v,f,c,E);if(v.current&&v.current!==g&&(g=v.current),U)continue}X.push({payloadType:It,payload:pt}),de()}}de()}};function hh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Vs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function us(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Na="[Image]";function yh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function bh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function xh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function vh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Oa(e){return{type:"text",text:e}}function wh(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 Ch(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Sh(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 Zu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ah=["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=[...Zu,...Ah];function Th(e){return Zu.includes(e)||e.startsWith("image/")}function Fa(e){return Th(e.type)}async function em(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Fa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function tm(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 Eh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function nm(e,t){let n=Eh(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"}Yi();var rm=16e3,Mh=24e3,kh=4096,Lh=1380533830;function Ph(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Lh?new Uint8Array(e,44):new Uint8Array(e)}function Ih(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 Ks=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 o,a,i,d;if(this.callLive)return;let t=(o=this.config)==null?void 0:o.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 s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:rm,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,m=new p({sampleRate:rm});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ms(Mh);if(s!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),m.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${Ih(r)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(g,["runtype.bearer",n]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,c,x,s))},x.onmessage=v=>this.handleMessage(v,s),x.onerror=()=>{s===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(s===this.callGeneration){if(v.code!==1e3){let E=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,s){let o=t.createMediaStreamSource(n);this.sourceNode=o;let a=t.createScriptProcessor(kh,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let m=Math.max(-1,Math.min(1,d[p]));c[p]=m<0?m*32768:m*32767}r.send(c.buffer)},o.connect(a),a.connect(t.destination)}handleMessage(t,n){var s,o;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",(s=r.text)!=null?s:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(o=r.text)!=null?o:"",!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=Ph(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(s=>s(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Fo=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=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("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 _o(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ks(e.runtype);case"browser":if(!Fo.isSupported())throw new Error("Browser speech recognition not supported");return new Fo(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 Zi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return _o({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return _o({type:"runtype",runtype:e.runtype});if(Fo.isSupported())return _o({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function _a(e){try{return Zi(e),!0}catch{return!1}}function Gs(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 s=e.find(o=>o.name===r);if(s)return s}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var $o=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 s=new SpeechSynthesisUtterance(t.text),o=r.getVoices();if(t.voice){let i=o.find(d=>d.name===t.voice);i&&(s.voice=i)}else o.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(o):Gs(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},s.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(s),(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 gs=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,s;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"){(s=this.engine)==null||s.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var s;let r=++this.generation;(s=this.engine)==null||s.stop(),this.set(t,"loading");try{if(!this.engine){let o=await this.resolveEngine();if(r!==this.generation)return;if(!o){this.set(null,"idle");return}this.engine=o}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 el(e){if(!e)return"";let t=Rh(e);return om(t!==null?t:e)}function Rh(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 om(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=(Dt=pe.pop())!=null?Dt:"";for(let Be of pe){let je=Be.split(`
14
+ `),De="message",Le="";for(let ht of je)ht.startsWith("event:")?De=ht.replace("event:","").trim():ht.startsWith("data:")&&(Le+=ht.replace("data:","").trim());if(!Le)continue;let it;try{it=JSON.parse(Le)}catch(ht){n({type:"error",error:ht instanceof Error?ht:new Error("Failed to parse chat stream payload")});continue}let It=De!=="message"?De:(Yt=it.type)!=null?Yt:"message";if((Nr=this.onSSEEvent)==null||Nr.call(this,It,it),this.parseSSEEvent){x.current=g;let ht=await this.handleCustomSSEEvent(it,n,x,f,l,T);if(x.current&&x.current!==g&&(g=x.current),ht)continue}J.push({payloadType:It,payload:it}),Ve()}}Ve()}};function Rh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Xs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ys(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var _a="[Image]";function Wh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Hh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Bh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Dh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function $a(e){return{type:"text",text:e}}function Nh(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 Oh(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 Fh(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 am=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],_h=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Gr=[...am,..._h];function $h(e){return am.includes(e)||e.startsWith("image/")}function ja(e){return $h(e.type)}async function im(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;ja(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 lm(e,t=Gr,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 jh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function cm(e,t){let n=jh(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"}el();var dm=16e3,Uh=24e3,qh=4096,zh=1380533830;function Vh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===zh?new Uint8Array(e,44):new Uint8Array(e)}function Kh(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:dm,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:dm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new bs(Uh);if(o!==this.callGeneration){f.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${Kh(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(g,["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 T=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),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(qh,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=Vh(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 jo=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 Uo(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(!jo.isSupported())throw new Error("Browser speech recognition not supported");return new jo(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 tl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Uo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Uo({type:"runtype",runtype:e.runtype});if(jo.isSupported())return Uo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ua(e){try{return tl(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 qo=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 xs=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 nl(e){if(!e)return"";let t=Gh(e);return pm(t!==null?t:e)}function Gh(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 pm(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
15
  `),t=t.replace(/\n{2,}/g,`
14
- `),t.trim()}var cm=null;var tl=()=>cm?cm():Promise.resolve().then(()=>(lm(),im));var Bh=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Dh(e,t){return Bh.some(n=>e[n]!==t[n])}function dm(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 rl=()=>hm?hm():Promise.resolve().then(()=>(fm(),gm));var Xh=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Yh(e,t){return Xh.some(n=>e[n]!==t[n])}function ym(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}
15
17
 
16
- _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]}),pm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,um=e=>Do(e)||e===Ir,Qs=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 gs(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,s,o,a,i,d,c,p,m;if(t.type==="message"){this.upsertMessage(t.message);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Do(f.name)||f.name===Ir&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((s=t.message.agentMetadata)==null?void 0:s.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(o=t.message.agentMetadata)!=null&&o.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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(m=(p=this.callbacks).onError)==null||m.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,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ps(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var s,o,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(s=t.host)!=null?s:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||tl().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 _a((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,s,o,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=$o.isSupported()?new $o({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(o=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:o.runtype)==null?void 0:a.agentId,p=this.config.clientToken,m=t.browserFallback!==!1;if(d&&c&&p)return tl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:g})=>{let x=new f({host:d,agentId:c,clientToken:p,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return m&&n?new g(x,n,{onFallback:v=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${v.message}`)}):x});if(m&&n)return p&&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 s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=_o(s);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){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:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}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,s,o,a,i,d,c,p,m;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:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(o=(s=t.runtype)==null?void 0:s.clientToken)!=null?o:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((p=t.browser)==null?void 0:p.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.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(!Dh(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 ps(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:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:m}=t,g={id:a!=null?a:n==="user"?Vs():n==="assistant"?us():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(g),g}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:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:m=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:s==="user"?Vs():s==="assistant"?us():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,c={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(c),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,m,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let s=Vs(),o=us(),a={id:s,role:"user",content:r||Na,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:o},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let E=dm(x,this.config.errorMessage);if(E){let C={id:o,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(C)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(m=(p=this.callbacks).onError)==null||m.call(p,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=us();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(c){let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let m=dm(c,this.config.errorMessage);if(m){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.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=(o=this.callbacks).onError)==null||a.call(o,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 s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,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 s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,m,f,g,x;let s=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===s),i={id:s,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:o};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let E=null;if(v instanceof Response){if(!v.ok){let C=await v.json().catch(()=>null);throw new Error((f=C==null?void 0:C.error)!=null?f:`Approval request failed: ${v.status}`)}E=v.body}else v instanceof ReadableStream&&(E=v);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(v){let E=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(x=(g=this.callbacks).onError)==null||x.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,m,f,g,x,v,E,C,I,N,M,P;let r=this.messages.find(S=>S.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let s=(m=t.agentMetadata)==null?void 0:m.executionId,o=(f=t.toolCall)==null?void 0:f.name;if(!s||!o){(x=(g=this.callbacks).onError)==null||x.call(g,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 S=(v=t.toolCall)==null?void 0:v.args,W=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(W.length===1){let B=typeof((E=W[0])==null?void 0:E.question)=="string"?W[0].question:"";B&&(a={[B]:n})}}this.markAskUserQuestionResolved(t,a),(C=this.abortController)==null||C.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let S=typeof n=="string"?n:Object.entries(n).map(([W,B])=>`${W}: ${Array.isArray(B)?B.join(", "):B}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};c.forEach((W,B)=>{let D=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!D)return;let k=S[D],j=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${B}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${B}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(s,{[o]:n});if(!S.ok){let W=await S.json().catch(()=>null);throw new Error((N=W==null?void 0:W.error)!=null?N:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let W=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(P=(M=this.callbacks).onError)==null||P.call(M,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.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 s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var s,o;let n=this.messages.find(a=>a.id===t.id),r=[(s=n==null?void 0:n.toolCall)==null?void 0:s.startedAt,(o=t.toolCall)==null?void 0:o.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,s;if(((r=t.toolCall)==null?void 0:r.name)!==Ir)return!1;let n=this.messages.find(o=>o.id===t.id);return((s=(n!=null?n:t).agentMetadata)==null?void 0:s.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,s=Date.now(),o){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...o},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:s,duration:void 0,durationMs:Math.max(0,s-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,m;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var P,S,W,B,D,k,j;let g=(P=f.toolCall)==null?void 0:P.name,x=(S=f.toolCall)==null?void 0:S.id;if(!g||!x)return null;let v=`${t}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let E=this.markWebMcpToolRunning(f),C=(B=(W=f.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?B:g;if(g===Ir)return{dedupeKey:v,resumeKey:C,output:qi(),toolMessage:f,startedAt:E,completedAt:Date.now()};let I=new AbortController;this.webMcpResolveControllers.add(I),s.push(I);let N=this.client.executeWebMcpToolCall(g,(D=f.toolCall)==null?void 0:D.args,I.signal),M;if(!N)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await N}catch(z){let te=z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")||z.message.includes("abort"));return te||(j=(k=this.callbacks).onError)==null||j.call(k,z instanceof Error?z:new Error(String(z))),this.markWebMcpToolComplete(f,Js(te?"Aborted by cancel()":pm(z)),E),this.webMcpInflightKeys.delete(v),null}return I.signal.aborted?(this.markWebMcpToolComplete(f,Js("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:C,output:M,toolMessage:f,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let f={};for(let x of i)f[x.resumeKey]=x.output;let g=await this.client.resumeFlow(t,f,{signal:o.signal});if(!g.ok){let x=await g.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${g.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((c=x.toolMessage.toolCall)==null?void 0:c.name)===Ir?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(m=(p=this.callbacks).onError)==null||m.call(p,f instanceof Error?f:new Error(String(f)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,Js("Aborted by cancel()"),x.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of s)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,v,E,C,I,N,M,P,S,W,B,D;let n=(x=t.agentMetadata)==null?void 0:x.executionId,r=(v=t.toolCall)==null?void 0:v.name,s=(E=t.toolCall)==null?void 0:E.id;if(!n){(I=(C=this.callbacks).onError)==null||I.call(C,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!s){let k=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);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(k)}catch(j){(M=(N=this.callbacks).onError)==null||M.call(N,j instanceof Error?j:new Error(String(j)))}finally{this.webMcpInflightKeys.delete(k)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(o);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Ir,p=(P=t.toolCall)==null?void 0:P.args,m=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let k;if(c?k=qi():m?k=await m:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Js("Aborted by cancel()"),a);return}let j=(W=(S=t.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?W:r;f="resume",await this.resumeWithToolOutput(n,j,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o),this.markWebMcpToolComplete(t,k,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let j=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(f==="execute"||j||d.aborted)&&this.markWebMcpToolComplete(t,Js(j||d.aborted?"Aborted by cancel()":pm(k)),a),j||(D=(B=this.callbacks).onError)==null||D.call(B,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.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 s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};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 s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.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 s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s: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(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=el(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Gs(t)}toggleReadAloud(t){let n=this.messages.find(o=>o.id===t);if(!n||n.role!=="assistant")return;let r=el(n.content||"");if(!r.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:s==null?void 0:s.voice,rate:s==null?void 0:s.rate,pitch:s==null?void 0:s.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(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var p,m,f,g,x,v,E,C,I,N,M,P,S,W,B;if(o!==r)return s;let a={...s,...n};if(((p=s.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=s.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let D=s.approval,k=n.approval;a.approval={...D,...k,executionId:k.executionId||D.executionId,toolName:k.toolName||D.toolName,description:k.description||D.description,toolType:(g=k.toolType)!=null?g:D.toolType,reason:(x=k.reason)!=null?x:D.reason,parameters:(v=k.parameters)!=null?v:D.parameters}}let i=(E=n.toolCall)==null?void 0:E.name,d=(C=n.agentMetadata)==null?void 0:C.executionId,c=(I=n.toolCall)==null?void 0:I.id;if(i&&um(i)&&d&&c&&((N=n.agentMetadata)==null?void 0:N.awaitingLocalTool)===!0){let D=`${d}:${c}`,k=this.webMcpInflightKeys.has(D),j=this.webMcpResolvedKeys.has(D),z=(M=s.toolCall)==null?void 0:M.name,te=((P=s.agentMetadata)==null?void 0:P.executionId)===d&&((S=s.toolCall)==null?void 0:S.id)===c&&z!==void 0&&um(z)&&((W=s.toolCall)==null?void 0:W.status)==="complete";(k||j||te)&&(a.agentMetadata={...(B=a.agentMetadata)!=null?B:{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as Nh,ArrowDown as Oh,ArrowUp as Fh,ArrowUpRight as _h,Bot as $h,ChevronDown as jh,ChevronUp as Uh,ChevronRight as qh,ChevronLeft as zh,Check as Vh,Clipboard as Kh,ClipboardCopy as Gh,Copy as Jh,File as Qh,FileCode as Xh,FileSpreadsheet as Yh,FileText as Zh,ImagePlus as ey,Loader as ty,LoaderCircle as ny,Mic as ry,Paperclip as oy,RefreshCw as sy,Search as ay,Send as iy,ShieldAlert as ly,ShieldCheck as cy,ShieldX as dy,Square as py,ThumbsDown as uy,ThumbsUp as my,Upload as gy,Volume2 as fy,X as hy,User as yy,Mail as by,Phone as xy,Calendar as vy,Clock as wy,Building as Cy,MapPin as Sy,Lock as Ay,Key as Ty,CreditCard as Ey,AtSign as My,Hash as ky,Globe as Ly,Link as Py,CircleCheck as Iy,CircleX as Ry,TriangleAlert as Wy,Info as Hy,Ban as By,Shield as Dy,ArrowLeft as Ny,ArrowRight as Oy,ExternalLink as Fy,Ellipsis as _y,EllipsisVertical as $y,Menu as jy,House as Uy,Plus as qy,Minus as zy,Pencil as Vy,Trash as Ky,Trash2 as Gy,Save as Jy,Download as Qy,Share as Xy,Funnel as Yy,Settings as Zy,RotateCw as eb,Maximize as tb,Minimize as nb,ShoppingCart as rb,ShoppingBag as ob,Package as sb,Truck as ab,Tag as ib,Gift as lb,Receipt as cb,Wallet as db,Store as pb,DollarSign as ub,Percent as mb,Play as gb,Pause as fb,VolumeX as hb,Camera as yb,Image as bb,Film as xb,Headphones as vb,MessageCircle as wb,MessageSquare as Cb,Bell as Sb,Heart as Ab,Star as Tb,Eye as Eb,EyeOff as Mb,Bookmark as kb,CalendarDays as Lb,History as Pb,Timer as Ib,Folder as Rb,FolderOpen as Wb,Files as Hb,Sparkles as Bb,Zap as Db,Sun as Nb,Moon as Ob,Flag as Fb,Monitor as _b,Smartphone as $b}from"lucide";var jb={activity:Nh,"arrow-down":Oh,"arrow-up":Fh,"arrow-up-right":_h,bot:$h,"chevron-down":jh,"chevron-up":Uh,"chevron-right":qh,"chevron-left":zh,check:Vh,clipboard:Kh,"clipboard-copy":Gh,copy:Jh,file:Qh,"file-code":Xh,"file-spreadsheet":Yh,"file-text":Zh,"image-plus":ey,loader:ty,"loader-circle":ny,mic:ry,paperclip:oy,"refresh-cw":sy,search:ay,send:iy,"shield-alert":ly,"shield-check":cy,"shield-x":dy,square:py,"thumbs-down":uy,"thumbs-up":my,upload:gy,"volume-2":fy,x:hy,user:yy,mail:by,phone:xy,calendar:vy,clock:wy,building:Cy,"map-pin":Sy,lock:Ay,key:Ty,"credit-card":Ey,"at-sign":My,hash:ky,globe:Ly,link:Py,"circle-check":Iy,"circle-x":Ry,"triangle-alert":Wy,info:Hy,ban:By,shield:Dy,"arrow-left":Ny,"arrow-right":Oy,"external-link":Fy,ellipsis:_y,"ellipsis-vertical":$y,menu:jy,house:Uy,plus:qy,minus:zy,pencil:Vy,trash:Ky,"trash-2":Gy,save:Jy,download:Qy,share:Xy,funnel:Yy,settings:Zy,"rotate-cw":eb,maximize:tb,minimize:nb,"shopping-cart":rb,"shopping-bag":ob,package:sb,truck:ab,tag:ib,gift:lb,receipt:cb,wallet:db,store:pb,"dollar-sign":ub,percent:mb,play:gb,pause:fb,"volume-x":hb,camera:yb,image:bb,film:xb,headphones:vb,"message-circle":wb,"message-square":Cb,bell:Sb,heart:Ab,star:Tb,eye:Eb,"eye-off":Mb,bookmark:kb,"calendar-days":Lb,history:Pb,timer:Ib,folder:Rb,"folder-open":Wb,files:Hb,sparkles:Bb,zap:Db,sun:Nb,moon:Ob,flag:Fb,monitor:_b,smartphone:$b},xe=(e,t=24,n="currentColor",r=2)=>{let s=jb[e];return s?Ub(s,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 Ub(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}),s}var Ua={allowedTypes:zr,maxFileSize:10*1024*1024,maxFiles:4};function qb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function zb(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 fs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ua.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ua.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Ua.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:Ua.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,s,o,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=tm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,m);continue}try{let m=await em(c),f=Fa(c)?URL.createObjectURL(c):null,g={id:qb(),file:c,previewUrl:f,contentPart:m};this.attachments.push(g),this.renderPreview(g)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,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 s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.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=Fa(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=zb(t.file.type),d=xe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=nm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let s=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=xe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),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 mm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Xs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];mm(o)&&mm(s)?n[r]=Xs(o,s):n[r]=s}return n}var sr="min(440px, calc(100vw - 24px))",nl="440px",Vb={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,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Vb,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 gm(e,t){if(!(!e&&!t))return e?t?Xs(e,t):e:t}function rl(e){var t,n,r,s,o,a,i,d,c,p,m,f,g,x,v,E,C,I,N,M,P;return e?{...Ot,...e,theme:gm(Ot.theme,e.theme),darkTheme:gm(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,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ot.copy,...e.copy},sendButton:{...Ot.sendButton,...e.sendButton},statusIndicator:{...Ot.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ot.voiceRecognition,...e.voiceRecognition},features:(()=>{var ae,Q,ne,le,re,G,ee,qe,J,ie;let S=(ae=Ot.features)==null?void 0:ae.artifacts,W=(Q=e.features)==null?void 0:Q.artifacts,B=(ne=Ot.features)==null?void 0:ne.scrollToBottom,D=(le=e.features)==null?void 0:le.scrollToBottom,k=(re=Ot.features)==null?void 0:re.scrollBehavior,j=(G=e.features)==null?void 0:G.scrollBehavior,z=(ee=Ot.features)==null?void 0:ee.streamAnimation,te=(qe=e.features)==null?void 0:qe.streamAnimation,Pe=(J=Ot.features)==null?void 0:J.askUserQuestion,je=(ie=e.features)==null?void 0:ie.askUserQuestion,Se=S===void 0&&W===void 0?void 0:{...S,...W,layout:{...S==null?void 0:S.layout,...W==null?void 0:W.layout}},ke=B===void 0&&D===void 0?void 0:{...B,...D},Fe=k===void 0&&j===void 0?void 0:{...k,...j},he=z===void 0&&te===void 0?void 0:{...z,...te},Be=Pe===void 0&&je===void 0?void 0:{...Pe,...je,styles:{...Pe==null?void 0:Pe.styles,...je==null?void 0:je.styles}};return{...Ot.features,...e.features,...ke!==void 0?{scrollToBottom:ke}:{},...Fe!==void 0?{scrollBehavior:Fe}:{},...Se!==void 0?{artifacts:Se}:{},...he!==void 0?{streamAnimation:he}:{},...Be!==void 0?{askUserQuestion:Be}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o: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,...(c=e.layout)==null?void 0:c.messages,avatar:{...(m=(p=Ot.layout)==null?void 0:p.messages)==null?void 0:m.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(x=Ot.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(C=(E=e.layout)==null?void 0:E.messages)==null?void 0:C.timestamp}},slots:{...(I=Ot.layout)==null?void 0:I.slots,...(N=e.layout)==null?void 0:N.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 fm={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"}},hm={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"}},ym={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:nl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function hs(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?hs(e,r):r}function ol(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=hs(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function bm(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 xm(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=xm(o,s):n[r]=s}return n}function Kb(e,t){return t?xm(e,t):e}function Ys(e,t={}){var s,o,a,i,d,c,p,m,f,g,x,v,E;let n={palette:fm,semantic:hm,components:ym},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.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,...(c=e==null?void 0:e.palette)==null?void 0:c.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,...(f=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Kb(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let C=bm(r);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let C of t.plugins)r=C.transform(r);return r}function sl(e){var v,E,C,I,N,M,P,S,W,B,D,k,j,z,te,Pe,je,Se,ke,Fe,he,Be,ae,Q,ne,le,re,G,ee,qe,J,ie,Re,ve,Xe,Ke,Ne,ce,et,X,de,we,ze,Lt,Ae,me,fn,Pt,rn,yr,hn,Ve,T,ue,Me,Te,Ie,tt,Je,pt,It,U,st,V,pe,Ee,bt,Yt,Zt,un,Wt,nt,Rt,lt,Kt,Qn,Cn,en,Pn,br,xt,Dn,xr,Wr,lr,ht,vo,vr,wo,In,Vo,Gr,Hr,Jr,Qr,Co,So,Xr,wt,Nn,On,Sn,St,Xn,Yn,Fn,Yr,Br,Zr,_n,Ht,An,Zn,eo,Dr,to,wr,$n;let t=ol(e),n={};for(let[ye,ct]of Object.entries(t)){let Jt=ye.replace(/\./g,"-");n[`--persona-${Jt}`]=ct.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v: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"]=(C=n["--persona-semantic-colors-accent"])!=null?C:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(N=n["--persona-semantic-colors-background"])!=null?N: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"]=(S=n["--persona-semantic-colors-text-muted"])!=null?S:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(W=n["--persona-semantic-colors-text-inverse"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(B=n["--persona-semantic-colors-border"])!=null?B:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(D=n["--persona-semantic-colors-divider"])!=null?D:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(z=n["--persona-components-voice-processing-icon"])!=null?z:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(te=n["--persona-components-voice-speaking-icon"])!=null?te:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Pe=n["--persona-components-approval-requested-background"])!=null?Pe:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(je=n["--persona-components-approval-requested-border"])!=null?je:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Se=n["--persona-components-approval-requested-text"])!=null?Se:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ke=n["--persona-components-approval-requested-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-approval-approve-bg"]=(Fe=n["--persona-components-approval-approve-background"])!=null?Fe:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(he=n["--persona-components-approval-deny-background"])!=null?he:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Be=n["--persona-components-attachment-image-background"])!=null?Be:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(ae=n["--persona-components-attachment-image-border"])!=null?ae:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Q=n["--persona-semantic-typography-fontFamily"])!=null?Q:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ne=n["--persona-semantic-typography-fontSize"])!=null?ne:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(le=n["--persona-semantic-typography-fontWeight"])!=null?le:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(re=n["--persona-semantic-typography-lineHeight"])!=null?re: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"]=(G=n["--persona-palette-radius-sm"])!=null?G:"0.125rem",n["--persona-radius-md"]=(ee=n["--persona-palette-radius-md"])!=null?ee:"0.375rem",n["--persona-radius-lg"]=(qe=n["--persona-palette-radius-lg"])!=null?qe:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(ie=n["--persona-palette-radius-full"])!=null?ie:"9999px",n["--persona-launcher-radius"]=(ve=(Re=n["--persona-components-launcher-borderRadius"])!=null?Re:n["--persona-palette-radius-full"])!=null?ve:"9999px",n["--persona-launcher-bg"]=(Xe=n["--persona-components-launcher-background"])!=null?Xe:n["--persona-primary"],n["--persona-launcher-fg"]=(Ke=n["--persona-components-launcher-foreground"])!=null?Ke:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ne=n["--persona-components-launcher-border"])!=null?Ne:n["--persona-border"],n["--persona-button-primary-bg"]=(ce=n["--persona-components-button-primary-background"])!=null?ce:n["--persona-primary"],n["--persona-button-primary-fg"]=(et=n["--persona-components-button-primary-foreground"])!=null?et:n["--persona-text-inverse"],n["--persona-button-radius"]=(de=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?de:"9999px",n["--persona-panel-radius"]=(ze=(we=n["--persona-components-panel-borderRadius"])!=null?we:n["--persona-radius-xl"])!=null?ze:"0.75rem",n["--persona-panel-border"]=(Lt=n["--persona-components-panel-border"])!=null?Lt:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(me=(Ae=n["--persona-components-panel-shadow"])!=null?Ae:n["--persona-palette-shadows-xl"])!=null?me:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(fn=n["--persona-components-launcher-shadow"])!=null?fn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(rn=(Pt=n["--persona-components-input-borderRadius"])!=null?Pt:n["--persona-radius-lg"])!=null?rn:"0.5rem",n["--persona-message-user-radius"]=(hn=(yr=n["--persona-components-message-user-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?hn:"0.5rem",n["--persona-message-assistant-radius"]=(T=(Ve=n["--persona-components-message-assistant-borderRadius"])!=null?Ve:n["--persona-radius-lg"])!=null?T:"0.5rem",n["--persona-header-bg"]=(ue=n["--persona-components-header-background"])!=null?ue:n["--persona-surface"],n["--persona-header-border"]=(Me=n["--persona-components-header-border"])!=null?Me:n["--persona-divider"],n["--persona-header-icon-bg"]=(Te=n["--persona-components-header-iconBackground"])!=null?Te:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ie=n["--persona-components-header-iconForeground"])!=null?Ie:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(tt=n["--persona-components-header-titleForeground"])!=null?tt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Je=n["--persona-components-header-subtitleForeground"])!=null?Je:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(pt=n["--persona-components-header-actionIconForeground"])!=null?pt: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 s=(U=e.components)==null?void 0:U.introCard;n["--persona-intro-card-bg"]=(st=n["--persona-components-introCard-background"])!=null?st:n["--persona-surface"],n["--persona-intro-card-radius"]=(V=n["--persona-components-introCard-borderRadius"])!=null?V:"1rem",n["--persona-intro-card-padding"]=(pe=n["--persona-components-introCard-padding"])!=null?pe:"1.5rem",n["--persona-intro-card-shadow"]=(bt=(Ee=s==null?void 0:s.shadow)!=null?Ee:n["--persona-components-introCard-shadow"])!=null?bt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Yt=n["--persona-components-input-background"])!=null?Yt:n["--persona-surface"],n["--persona-input-placeholder"]=(Zt=n["--persona-components-input-placeholder"])!=null?Zt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(un=n["--persona-components-message-user-background"])!=null?un:n["--persona-accent"],n["--persona-message-user-text"]=(Wt=n["--persona-components-message-user-text"])!=null?Wt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(nt=n["--persona-components-message-user-shadow"])!=null?nt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Rt=n["--persona-components-message-assistant-background"])!=null?Rt:n["--persona-surface"],n["--persona-message-assistant-text"]=(lt=n["--persona-components-message-assistant-text"])!=null?lt:n["--persona-text"],n["--persona-message-assistant-border"]=(Kt=n["--persona-components-message-assistant-border"])!=null?Kt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Qn=n["--persona-components-message-assistant-shadow"])!=null?Qn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(en=(Cn=n["--persona-components-scrollToBottom-background"])!=null?Cn:n["--persona-button-primary-bg"])!=null?en:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(br=(Pn=n["--persona-components-scrollToBottom-foreground"])!=null?Pn:n["--persona-button-primary-fg"])!=null?br:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(xt=n["--persona-components-scrollToBottom-border"])!=null?xt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Dn=n["--persona-components-scrollToBottom-size"])!=null?Dn:"40px",n["--persona-scroll-to-bottom-radius"]=(lr=(Wr=(xr=n["--persona-components-scrollToBottom-borderRadius"])!=null?xr:n["--persona-button-radius"])!=null?Wr:n["--persona-radius-full"])!=null?lr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(vo=(ht=n["--persona-components-scrollToBottom-shadow"])!=null?ht:n["--persona-palette-shadows-sm"])!=null?vo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(wo=n["--persona-components-scrollToBottom-gap"])!=null?wo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Vo=(In=n["--persona-components-scrollToBottom-fontSize"])!=null?In:n["--persona-palette-typography-fontSize-sm"])!=null?Vo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Gr=n["--persona-components-scrollToBottom-iconSize"])!=null?Gr:"14px",n["--persona-tool-bubble-shadow"]=(Hr=n["--persona-components-toolBubble-shadow"])!=null?Hr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Jr=n["--persona-components-reasoningBubble-shadow"])!=null?Jr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Qr=n["--persona-components-composer-shadow"])!=null?Qr:"none",n["--persona-md-inline-code-bg"]=(Co=n["--persona-components-markdown-inlineCode-background"])!=null?Co:n["--persona-container"],n["--persona-md-inline-code-color"]=(So=n["--persona-components-markdown-inlineCode-foreground"])!=null?So:n["--persona-text"],n["--persona-md-link-color"]=(wt=(Xr=n["--persona-components-markdown-link-foreground"])!=null?Xr:n["--persona-accent"])!=null?wt:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Nn=n["--persona-components-markdown-codeBlock-background"])!=null?Nn:n["--persona-container"],n["--persona-md-code-block-border-color"]=(On=n["--persona-components-markdown-codeBlock-borderColor"])!=null?On:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Sn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Sn:"inherit",n["--persona-md-table-header-bg"]=(St=n["--persona-components-markdown-table-headerBackground"])!=null?St:n["--persona-container"],n["--persona-md-table-border-color"]=(Xn=n["--persona-components-markdown-table-borderColor"])!=null?Xn:n["--persona-border"],n["--persona-md-hr-color"]=(Yn=n["--persona-components-markdown-hr-color"])!=null?Yn:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Fn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Fn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Yr=n["--persona-components-markdown-blockquote-background"])!=null?Yr:"transparent",n["--persona-md-blockquote-text-color"]=(Br=n["--persona-components-markdown-blockquote-textColor"])!=null?Br:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Zr=n["--persona-components-collapsibleWidget-container"])!=null?Zr:n["--persona-surface"],n["--cw-surface"]=(_n=n["--persona-components-collapsibleWidget-surface"])!=null?_n:n["--persona-surface"],n["--cw-border"]=(Ht=n["--persona-components-collapsibleWidget-border"])!=null?Ht:n["--persona-border"],n["--persona-message-border"]=(An=n["--persona-components-message-border"])!=null?An:n["--persona-border"];let p=e.components,m=p==null?void 0:p.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let ye=x.toolbar;ye.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,n["--persona-dropdown-bg"]=(Zn=n["--persona-dropdown-bg"])!=null?Zn:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(eo=n["--persona-dropdown-border"])!=null?eo:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(Dr=n["--persona-dropdown-shadow"])!=null?Dr:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(to=n["--persona-dropdown-radius"])!=null?to:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(wr=n["--persona-dropdown-item-hover-bg"])!=null?wr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(x!=null&&x.tab){let ye=x.tab;ye.background&&(n["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(n["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(n["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(n["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(n["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(n["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(x!=null&&x.pane){let ye=x.pane;if(ye.toolbarBackground){let ct=($n=hs(e,ye.toolbarBackground))!=null?$n:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ct}}return n}var Gb={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 Jb={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"}}},vm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},qa=()=>{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"},Qb=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":qa()},wm=e=>Qb(e),Xb=e=>Ys(e),Yb=e=>{var n;let t=Ys(void 0,{validate:!1});return Ys({...e,palette:{...t.palette,colors:{...Jb.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Zs=e=>{let t=wm(e),n=vm(e==null?void 0:e.theme),r=vm(e==null?void 0:e.darkTheme);return t==="dark"?Yb(Xs(n!=null?n:{},r!=null?r:{})):Xb(n)},Zb=e=>sl(e),jo=(e,t)=>{let n=Zs(t),r=Zb(n);for(let[s,o]of Object.entries(r))e.style.setProperty(s,o)},al=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(qa())});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(qa());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 ex}from"idiomorph";var za=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;ex.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Cm=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Va={index:-1,draft:""};function Sm(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Va}}}function Am(e,t){var n,r,s,o,a,i,d,c,p,m,f,g,x,v,E,C,I,N,M,P,S,W,B,D,k,j,z,te,Pe,je,Se,ke,Fe,he,Be,ae,Q,ne;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",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=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(m=e.approval)==null?void 0:m.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(E=(v=e.toolCall)==null?void 0:v.name)!=null?E:"",(N=(I=(C=e.toolCall)==null?void 0:C.chunks)==null?void 0:I.length)!=null?N:0,(W=(S=(P=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?W:"",typeof((B=e.toolCall)==null?void 0:B.args)=="string"?e.toolCall.args.length:(D=e.toolCall)!=null&&D.args?JSON.stringify(e.toolCall.args).length:0,(z=(j=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:j.length)!=null?z:0,(Se=(je=(Pe=(te=e.reasoning)==null?void 0:te.chunks)==null?void 0:Pe[e.reasoning.chunks.length-1])==null?void 0:je.length)!=null?Se:0,(Be=(he=(Fe=(ke=e.reasoning)==null?void 0:ke.chunks)==null?void 0:Fe[e.reasoning.chunks.length-1])==null?void 0:he.slice(-32))!=null?Be:"",(Q=(ae=e.contentParts)==null?void 0:ae.length)!=null?Q:0,(ne=e.stopReason)!=null?ne:"",t].join("\0")}function Tm(){return new Map}function Em(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Mm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function km(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ka(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Vr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Uo(e,t){return Vr(e)-e.scrollTop<=t}function Ga(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:n}:!t&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Ja(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}function Lm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Pm(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 Im(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,go=wn+1;var ea={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},tx=["pre","code","a","script","style"],Qa=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:ea.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ea.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ea.speed,duration:(s=e==null?void 0:e.duration)!=null?s:ea.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:ea.buffer}},Wm=[{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"}],ta=new Map;for(let e of Wm)ta.set(e.name,e);var nx=e=>{ta.set(e.name,e)},rx=e=>{Wm.some(t=>t.name===e)||ta.delete(e)},ox=()=>Array.from(ta.keys()),na=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=ta.get(e))!=null?r:null},Xa=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
17
- `);return o<0?"":e.slice(0,o)}return e},sx=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},ax=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},il=/\s/,ix=(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},lx=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(il.test(o[i])){let c=i;for(;c<o.length&&il.test(o[c]);)c+=1;a.appendChild(r.createTextNode(o.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<o.length&&!il.test(o[p]);)c.appendChild(sx(r,o[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}s.replaceChild(a,e)},cx=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(ax(r,c,t,n.value)),n.value+=1));s.replaceChild(a,e)},ra=(e,t,n,r)=>{var m,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((m=r==null?void 0:r.skipTags)!=null?m:tx).map(g=>g.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)ix(d,o)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?lx:cx;for(let g of i)p(g,n,c);return s.innerHTML},Ya=(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},oa=(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},Rm=new WeakMap,dx=(e,t)=>{var o;if(!e.styles)return;let n=Rm.get(t);if(n||(n=new Set,Rm.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 s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},ll=new WeakMap,px=(e,t)=>{if(!e.onAttach)return;let n=ll.get(t);if(n||(n=new Map,ll.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Hm=e=>{let t=ll.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},cl=(e,t)=>{dx(e,t),px(e,t)};function dl(e,t=wn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.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=s}}var sa=0,fo=null;function pl(e=document){var n;if(sa++,sa===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;fo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,sa=Math.max(0,sa-1),sa===0&&fo)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=fo.originalOverflow,s.style.position=fo.originalPosition,s.style.top=fo.originalTop,s.style.width=fo.originalWidth,o.scrollTo(0,fo.scrollY),fo=null}}}var aa={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"},ho=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,s,o,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:aa.side,width:(s=t==null?void 0:t.width)!=null?s:aa.width,animate:(o=t==null?void 0:t.animate)!=null?o:aa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:aa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:aa.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 ux="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Za=(e,t={})=>{var E,C,I,N,M,P;let{showClose:n=!0,wrapperClassName:r=ux,buttonSize:s,iconSize:o="28px"}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=(C=s!=null?s:a.closeButtonSize)!=null?C:"32px",d=y("div",r),c=(I=a.closeButtonTooltipText)!=null?I:"Close chat",p=(N=a.closeButtonShowTooltip)!=null?N:!0,m=(M=a.closeButtonIconName)!=null?M:"x",f=(P=a.closeButtonIconText)!=null?P:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Tt("button",{className:Fs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Ln.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=xe(m,o,"currentColor",1);if(v?(v.style.display="block",x.appendChild(v)):x.textContent=f,d.appendChild(x),p&&c){let S=null,W=()=>{if(S)return;let D=x.ownerDocument,k=D.body;if(!k)return;S=Pr(D,"div","persona-clear-chat-tooltip"),S.textContent=c;let j=Pr(D,"div");j.className="persona-clear-chat-tooltip-arrow",S.appendChild(j);let z=x.getBoundingClientRect();S.style.position="fixed",S.style.zIndex=String(go),S.style.left=`${z.left+z.width/2}px`,S.style.top=`${z.top-8}px`,S.style.transform="translate(-50%, -100%)",k.appendChild(S)},B=()=>{S&&S.parentNode&&(S.parentNode.removeChild(S),S=null)};d.addEventListener("mouseenter",W),d.addEventListener("mouseleave",B),x.addEventListener("focus",W),x.addEventListener("blur",B),d._cleanupTooltip=()=>{B(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",B),x.removeEventListener("focus",W),x.removeEventListener("blur",B)}}return{button:x,wrapper:d}},mx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ei=(e,t={})=>{var S,W,B,D,k,j,z,te,Pe,je,Se,ke,Fe;let{wrapperClassName:n=mx,buttonSize:r,iconSize:s="20px"}=t,a=(W=((S=e==null?void 0:e.launcher)!=null?S:{}).clearChat)!=null?W:{},i=(B=r!=null?r:a.size)!=null?B:"32px",d=(D=a.iconName)!=null?D:"refresh-cw",c=(k=a.iconColor)!=null?k:"",p=(j=a.backgroundColor)!=null?j:"",m=(z=a.borderWidth)!=null?z:"",f=(te=a.borderColor)!=null?te:"",g=(Pe=a.borderRadius)!=null?Pe:"",x=(je=a.paddingX)!=null?je:"",v=(Se=a.paddingY)!=null?Se:"",E=(ke=a.tooltipText)!=null?ke:"Clear chat",C=(Fe=a.showTooltip)!=null?Fe:!0,I=y("div",n),N=!!(m||f),M=Tt("button",{className:Fs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!N&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:c||Ln.actionIconColor,backgroundColor:p||void 0,border:N?`${m||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),P=xe(d,s,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),I.appendChild(M),C&&E){let he=null,Be=()=>{if(he)return;let Q=M.ownerDocument,ne=Q.body;if(!ne)return;he=Pr(Q,"div","persona-clear-chat-tooltip"),he.textContent=E;let le=Pr(Q,"div");le.className="persona-clear-chat-tooltip-arrow",he.appendChild(le);let re=M.getBoundingClientRect();he.style.position="fixed",he.style.zIndex=String(go),he.style.left=`${re.left+re.width/2}px`,he.style.top=`${re.top-8}px`,he.style.transform="translate(-50%, -100%)",ne.appendChild(he)},ae=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};I.addEventListener("mouseenter",Be),I.addEventListener("mouseleave",ae),M.addEventListener("focus",Be),M.addEventListener("blur",ae),I._cleanupTooltip=()=>{ae(),I.removeEventListener("mouseenter",Be),I.removeEventListener("mouseleave",ae),M.removeEventListener("focus",Be),M.removeEventListener("blur",ae)}}return{button:M,wrapper:I}};var Ln={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},yo=e=>{var P,S,W,B,D,k,j,z,te,Pe,je,Se,ke,Fe,he,Be;let{config:t,showClose:n=!0}=e,r=Tt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),s=(P=t==null?void 0:t.launcher)!=null?P:{},o=(S=s.headerIconSize)!=null?S:"48px",a=(W=s.closeButtonPlacement)!=null?W:"inline",i=(B=s.headerIconHidden)!=null?B:!1,d=s.headerIconName,c=Tt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:o,width:o,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 ae=parseFloat(o)||24,Q=xe(d,ae*.6,"currentColor",1);Q?c.replaceChildren(Q):c.textContent=(k=(D=t==null?void 0:t.launcher)==null?void 0:D.agentIconText)!=null?k:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let ae=y("img");ae.src=t.launcher.iconUrl,ae.alt="",ae.className="persona-rounded-xl persona-object-cover",ae.style.height=o,ae.style.width=o,c.replaceChildren(ae)}else c.textContent=(te=(z=t==null?void 0:t.launcher)==null?void 0:z.agentIconText)!=null?te:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Tt("span",{className:"persona-text-base persona-font-semibold",text:(je=(Pe=t==null?void 0:t.launcher)==null?void 0:Pe.title)!=null?je:"Chat Assistant",style:{color:Ln.titleColor}}),f=Tt("span",{className:"persona-text-xs",text:(ke=(Se=t==null?void 0:t.launcher)==null?void 0:Se.subtitle)!=null?ke:"Here to help you get answers fast",style:{color:Ln.subtitleColor}});p.append(m,f),i?r.append(p):r.append(c,p);let g=(Fe=s.clearChat)!=null?Fe:{},x=(he=g.enabled)!=null?he:!0,v=(Be=g.placement)!=null?Be:"inline",E=null,C=null;if(x){let Q=ei(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=Q.button,C=Q.wrapper,v==="top-right"&&(C.style.right="48px"),v==="inline"&&r.appendChild(C)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:N,wrapper:M}=Za(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:f,closeButton:N,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:C}},ys=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function qo(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(go)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let E=xe(g.icon,16,"currentColor",1.5);E&&x.appendChild(E)}let v=document.createElement("span");v.textContent=g.label,x.appendChild(v),x.addEventListener("click",E=>{E.stopPropagation(),p(),n(g.id)}),a.appendChild(x)}let i=null;function d(){if(!o)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!r.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:m,destroy:f}}function qt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=xe(t,r!=null?r:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,m]of Object.entries(i))d.setAttribute(p,m);return d}function ti(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=xe(t,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let m=y("span");if(m.textContent=n,p.appendChild(m),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function ni(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=y("div","persona-toggle-group"+(s?" "+s:""));o.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 m;p.icon?m=qt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(m=y("button","persona-icon-btn"),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:m}),o.appendChild(m)}function c(p){a=p,d()}return{element:o,setSelected:c}}function ul(e){var g,x;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let m=xe(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,E;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(E=d.border)!=null?E:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=qo({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),s(v)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let E=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Bm=e=>{var r;let t=yo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function gx(e,t,n){var r,s,o;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",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=xe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=y("div","persona-relative");d.appendChild(i);let c=qo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Dm=e=>{var I,N,M,P,S,W,B,D,k;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},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=s==null?void 0:s.titleMenu,c,p;if(d)c=ul({label:(N=a.title)!=null?N:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Ln.titleColor,p=(M=c.querySelector(".persona-combo-btn-label"))!=null?M:c;else{if(c=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=Ln.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(p),gx(c,s==null?void 0:s.trailingActions,(S=s==null?void 0:s.onAction)!=null?S:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let z=s.onTitleClick;c.addEventListener("click",te=>{te.target.closest("button")||z()}),c.addEventListener("keydown",te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),z())})}let j=s==null?void 0:s.titleRowHover;j&&(c.style.borderRadius=(W=j.borderRadius)!=null?W:"10px",c.style.padding=(B=j.padding)!=null?B:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var z,te;c.style.backgroundColor=(z=j.background)!=null?z:"",c.style.borderColor=(te=j.border)!=null?te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(D=a.closeButtonSize)!=null?D:"32px",f=y("div",""),g=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");g.style.height=m,g.style.width=m,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Ln.actionIconColor;let x=(k=a.closeButtonIconName)!=null?k:"x",v=xe(x,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let E=y("div");E.style.display="none";let C=y("span");return C.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:C,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},ml={default:Bm,minimal:Dm},Nm=e=>{var t;return(t=ml[e])!=null?t:ml.default},ia=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=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 m=y("span"),f=y("span"),g=y("button");g.style.display="none";let x=y("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:m,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=Nm(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&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var ri=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 s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());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:o}},oi=e=>{var P,S,W,B,D,k,j,z,te,Pe,je,Se;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(S=t.useIcon)!=null?S:!1,r=(W=t.iconText)!=null?W:"\u2191",s=t.iconName,o=(B=t.stopIconName)!=null?B:"square",a=(D=t.tooltipText)!=null?D:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=(z=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?z:"Send",c=(Pe=(te=e==null?void 0:e.copy)==null?void 0:te.stopButtonLabel)!=null?Pe:"Stop",p=(je=t.showTooltip)!=null?je:!1,m=(Se=t.size)!=null?Se:"40px",f=t.backgroundColor,g=t.textColor,x=y("div","persona-send-button-wrapper"),v=Tt("button",{className:Fs("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&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||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,C=null;if(n){let ke=parseFloat(m)||24,Fe=(g==null?void 0:g.trim())||"currentColor";s?(E=xe(s,ke,Fe,2),E?v.appendChild(E):v.textContent=r):v.textContent=r,C=xe(o,ke,Fe,2)}else v.textContent=d;let I=null;p&&a&&(I=y("div","persona-send-button-tooltip"),I.textContent=a,x.appendChild(I)),v.setAttribute("aria-label",a),x.appendChild(v);let N="send";return{button:v,wrapper:x,setMode:ke=>{if(ke===N)return;N=ke;let Fe=ke==="stop"?i:a;if(v.setAttribute("aria-label",Fe),I&&(I.textContent=Fe),n){if(E&&C){let he=ke==="stop"?C:E;v.replaceChildren(he)}}else v.textContent=ke==="stop"?c:d}}},si=e=>{var I,N,M,P,S,W,B,D,k,j,z,te;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((N=t.provider)==null?void 0:N.type)==="runtype";if(!(r||s))return null;let a=(P=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(S=t.iconName)!=null?S:"mic",d=(W=t.iconSize)!=null?W:a,c=parseFloat(d)||24,p=(D=t.backgroundColor)!=null?D:(B=e==null?void 0:e.sendButton)==null?void 0:B.backgroundColor,m=(j=t.iconColor)!=null?j:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor,f=y("div","persona-send-button-wrapper"),g=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"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}}),v=xe(i,c,m||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let E=(z=t.tooltipText)!=null?z:"Start voice recognition";if(((te=t.showTooltip)!=null?te:!1)&&E){let Pe=y("div","persona-send-button-tooltip");Pe.textContent=E,f.appendChild(Pe)}return{button:g,wrapper:f}},ai=e=>{var x,v,E,C,I,N,M,P;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let n=(E=(v=e==null?void 0:e.sendButton)==null?void 0:v.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 s=y("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=((C=t.allowedTypes)!=null?C:zr).join(","),s.multiple=((I=t.maxFiles)!=null?I:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=(N=t.buttonIconName)!=null?N:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(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 m=xe(o,d,"currentColor",1.5);m?p.appendChild(m):p.textContent="\u{1F4CE}",p.addEventListener("click",S=>{S.preventDefault(),s.click()}),c.appendChild(p);let f=(P=t.buttonTooltipText)!=null?P:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:s,previewsContainer:r}},ii=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 s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=o,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=o;return r},li=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var la=e=>{var x,v,E,C,I,N;let{config:t}=e,n=Tt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=li(),s=Tt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:o,attachAutoResize:a}=ri(t);a();let i=oi(t),d=si(t),c=ai(t),p=ii(t);c&&(c.previewsContainer.style.gap="8px",s.append(c.previewsContainer,c.input)),s.append(o);let m=Tt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),m.append(f,g),s.append(m),s.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!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&o.focus()}),n.append(r,s,p),{footer:n,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,attachmentInput:(I=c==null?void 0:c.input)!=null?I:null,attachmentPreviewsContainer:(N=c==null?void 0:c.previewsContainer)!=null?N:null,actionsRow:m,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Om=()=>{let e=Tt("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=xe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),s=y("span","persona-pill-peek__caret"),o=xe("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},Fm=e=>{var x,v,E,C,I,N;let{config:t}=e,n=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=li();r.style.display="none";let s=ii(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=ri(t);o.style.maxHeight="100px",a();let i=oi(t),d=si(t),c=ai(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Tt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.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!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&o.focus()}),c&&p.append(c.input),p.append(m,o,f),c&&n.append(c.previewsContainer),n.append(p,r,s);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:s,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(C=c==null?void 0:c.wrapper)!=null?C:null,attachmentInput:(I=c==null?void 0:c.input)!=null?I:null,attachmentPreviewsContainer:(N=c==null?void 0:c.previewsContainer)!=null?N:null,actionsRow:g,leftActions:m,rightActions:f,setSendButtonMode:i.setMode}};var _m=e=>{var p,m,f,g,x,v,E,C,I,N,M,P,S,W,B,D,k;let t=(m=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?m:!0,n=dn(e);if(ho(e)){let j=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},z=y("div","persona-widget-wrapper persona-fixed persona-transition");z.setAttribute("data-persona-composer-bar",""),z.dataset.state="collapsed",z.dataset.expandedSize=(x=j.expandedSize)!=null?x:"anchored",z.style.zIndex=String((E=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?E:wn);let te=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");te.style.width="100%",z.appendChild(te);let Pe=y("div","persona-widget-pill-root");return Pe.setAttribute("data-persona-composer-bar",""),Pe.dataset.state="collapsed",Pe.dataset.expandedSize=(C=j.expandedSize)!=null?C:"anchored",Pe.style.zIndex=String((N=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?N:wn),{wrapper:z,panel:te,pillRoot:Pe}}if(n){let j=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),z=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(z),{wrapper:j,panel:z}}if(!t){let j=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),z=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),te=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?P:"100%";return j.style.width=te,z.style.width="100%",j.appendChild(z),{wrapper:j,panel:z}}let s=(S=e==null?void 0:e.launcher)!=null?S:{},o=s.position&&hr[s.position]?hr[s.position]:hr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((B=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?B:wn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?k:e==null?void 0:e.launcherWidth,c=d!=null?d:sr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},fx=(e,t)=>{var M,P,S,W,B,D,k,j,z;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:s}=Za(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(S=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?S:!0,a=null,i=null;if(o){let te=ei(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=te.button,i=te.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Tt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(B=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?B:"Hello \u{1F44B}"}),m=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),f=Tt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,m),g=y("div","persona-flex persona-flex-col persona-gap-3"),x=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;x&&(g.style.maxWidth=x,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((z=e==null?void 0:e.copy)==null?void 0:z.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let E=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),C=Fm({config:e}),{root:I,textNode:N}=Om();return n.append(d,s,c,E),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:E,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode,peekBanner:I,peekTextNode:N}},$m=(e,t=!0)=>{var E,C,I,N,M,P,S,W,B;if(ho(e))return fx(e,t);let n=Tt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(E=e==null?void 0:e.layout)==null?void 0:E.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=r?ia(e,r,{showClose:t}):yo({config:e,showClose:t}),a=Tt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),d=Tt("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."}),c=Tt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{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"),m=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;m&&(p.style.maxWidth=m,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((W=e==null?void 0:e.copy)==null?void 0:W.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=la({config:e}),x=((B=e==null?void 0:e.layout)==null?void 0:B.showFooter)!==!1;s?ys(n,o,e):(o.header.style.display="none",ys(n,o,e)),n.append(a);let v=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:d,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var gl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
18
+ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]}),bm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,xm=e=>Fo(e)||e===Br,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 xs(()=>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 f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Fo(f.name)||f.name===Br&&((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&&g&&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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(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 hs(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||rl().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 Ua((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;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=qo.isSupported()?new qo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,l=(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,p=this.config.clientToken,u=t.browserFallback!==!1;if(d&&l&&p)return rl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:g})=>{let v=new f({host:d,agentId:l,clientToken:p,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return u&&n?new g(v,n,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(u&&n)return p&&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=Uo(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;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:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=t.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(l=t.runtype)==null?void 0:l.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((p=t.browser)==null?void 0:p.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.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(!Yh(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 hs(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,g={id:a!=null?a:n==="user"?Xs():n==="assistant"?ys():`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(g),g}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:f,rawContent:g}=r,x={id:d!=null?d:o==="user"?Xs():o==="assistant"?ys():`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},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};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,f,g;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=Xs(),s=ys(),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 T=ym(v,this.config.errorMessage);if(T){let S={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(S)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=ys();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=ym(l,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}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,f,g,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 T=null;if(x instanceof Response){if(!x.ok){let S=await x.json().catch(()=>null);throw new Error((f=S==null?void 0:S.error)!=null?f:`Approval request failed: ${x.status}`)}T=x.body}else x instanceof ReadableStream&&(T=x);T?await this.connectStream(T,{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 T=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(v=(g=this.callbacks).onError)==null||v.call(g,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,f,g,v,x,T,S,k,M,E,L;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=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(v=(g=this.callbacks).onError)==null||v.call(g,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((T=R[0])==null?void 0:T.question)=="string"?R[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(t,a),(S=this.abortController)==null||S.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(k=t.toolCall)==null?void 0:k.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((M=R==null?void 0:R.error)!=null?M:`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||(L=(E=this.callbacks).onError)==null||L.call(E,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)!==Br)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 f=>{var L,C,R,F,j,W,O;let g=(L=f.toolCall)==null?void 0:L.name,v=(C=f.toolCall)==null?void 0:C.id;if(!g||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(x),r.push(x);let T=this.markWebMcpToolRunning(f),S=(F=(R=f.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?F:g;if(g===Br)return{dedupeKey:x,resumeKey:S,output:Vi(),toolMessage:f,startedAt:T,completedAt:Date.now()};let k=new AbortController;this.webMcpResolveControllers.add(k),o.push(k);let M=this.client.executeWebMcpToolCall(g,(j=f.toolCall)==null?void 0:j.args,k.signal),E;if(!M)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await M}catch(N){let Z=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return Z||(O=(W=this.callbacks).onError)==null||O.call(W,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(f,ea(Z?"Aborted by cancel()":bm(N)),T),this.webMcpInflightKeys.delete(x),null}return k.signal.aborted?(this.markWebMcpToolComplete(f,ea("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:S,output:E,toolMessage:f,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let f={};for(let v of i)f[v.resumeKey]=v.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let v=await g.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${g.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)===Br?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ea("Aborted by cancel()"),v.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,T,S,k,M,E,L,C,R,F,j;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(T=t.toolCall)==null?void 0:T.id;if(!n){(k=(S=this.callbacks).onError)==null||k.call(S,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){(E=(M=this.callbacks).onError)==null||E.call(M,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===Br,p=(L=t.toolCall)==null?void 0:L.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let W;if(l?W=Vi():u?W=await u:W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=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;f="resume",await this.resumeWithToolOutput(n,O,W,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,W,a,g,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"));(f==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,ea(O||d.aborted?"Aborted by cancel()":bm(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=nl(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=nl(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,f,g,v,x,T,S,k,M,E,L,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={...(f=a.agentMetadata)!=null?f: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:(g=W.toolType)!=null?g:j.toolType,reason:(v=W.reason)!=null?v:j.reason,parameters:(x=W.parameters)!=null?x:j.parameters}}let i=(T=n.toolCall)==null?void 0:T.name,d=(S=n.agentMetadata)==null?void 0:S.executionId,l=(k=n.toolCall)==null?void 0:k.id;if(i&&xm(i)&&d&&l&&((M=n.agentMetadata)==null?void 0:M.awaitingLocalTool)===!0){let j=`${d}:${l}`,W=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),N=(E=o.toolCall)==null?void 0:E.name,Z=((L=o.agentMetadata)==null?void 0:L.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===l&&N!==void 0&&xm(N)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(W||O||Z)&&(a.agentMetadata={...(F=a.agentMetadata)!=null?F:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(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 Zh,ArrowDown as ey,ArrowUp as ty,ArrowUpRight as ny,Bot as ry,ChevronDown as oy,ChevronUp as sy,ChevronRight as ay,ChevronLeft as iy,Check as ly,Clipboard as cy,ClipboardCopy as dy,Copy as py,File as uy,FileCode as my,FileSpreadsheet as gy,FileText as fy,ImagePlus as hy,Loader as yy,LoaderCircle as by,Mic as xy,Paperclip as vy,RefreshCw as wy,Search as Cy,Send as Ay,ShieldAlert as Sy,ShieldCheck as Ey,ShieldX as Ty,Square as My,ThumbsDown as ky,ThumbsUp as Ly,Upload as Py,Volume2 as Iy,X as Ry,User as Wy,Mail as Hy,Phone as By,Calendar as Dy,Clock as Ny,Building as Oy,MapPin as Fy,Lock as _y,Key as $y,CreditCard as jy,AtSign as Uy,Hash as qy,Globe as zy,Link as Vy,CircleCheck as Ky,CircleX as Gy,TriangleAlert as Jy,Info as Qy,Ban as Xy,Shield as Yy,ArrowLeft as Zy,ArrowRight as eb,ExternalLink as tb,Ellipsis as nb,EllipsisVertical as rb,Menu as ob,House as sb,Plus as ab,Minus as ib,Pencil as lb,Trash as cb,Trash2 as db,Save as pb,Download as ub,Share as mb,Funnel as gb,Settings as fb,RotateCw as hb,Maximize as yb,Minimize as bb,ShoppingCart as xb,ShoppingBag as vb,Package as wb,Truck as Cb,Tag as Ab,Gift as Sb,Receipt as Eb,Wallet as Tb,Store as Mb,DollarSign as kb,Percent as Lb,Play as Pb,Pause as Ib,VolumeX as Rb,Camera as Wb,Image as Hb,Film as Bb,Headphones as Db,MessageCircle as Nb,MessageSquare as Ob,Bell as Fb,Heart as _b,Star as $b,Eye as jb,EyeOff as Ub,Bookmark as qb,CalendarDays as zb,History as Vb,Timer as Kb,Folder as Gb,FolderOpen as Jb,Files as Qb,Sparkles as Xb,Zap as Yb,Sun as Zb,Moon as ex,Flag as tx,Monitor as nx,Smartphone as rx}from"lucide";var ox={activity:Zh,"arrow-down":ey,"arrow-up":ty,"arrow-up-right":ny,bot:ry,"chevron-down":oy,"chevron-up":sy,"chevron-right":ay,"chevron-left":iy,check:ly,clipboard:cy,"clipboard-copy":dy,copy:py,file:uy,"file-code":my,"file-spreadsheet":gy,"file-text":fy,"image-plus":hy,loader:yy,"loader-circle":by,mic:xy,paperclip:vy,"refresh-cw":wy,search:Cy,send:Ay,"shield-alert":Sy,"shield-check":Ey,"shield-x":Ty,square:My,"thumbs-down":ky,"thumbs-up":Ly,upload:Py,"volume-2":Iy,x:Ry,user:Wy,mail:Hy,phone:By,calendar:Dy,clock:Ny,building:Oy,"map-pin":Fy,lock:_y,key:$y,"credit-card":jy,"at-sign":Uy,hash:qy,globe:zy,link:Vy,"circle-check":Ky,"circle-x":Gy,"triangle-alert":Jy,info:Qy,ban:Xy,shield:Yy,"arrow-left":Zy,"arrow-right":eb,"external-link":tb,ellipsis:nb,"ellipsis-vertical":rb,menu:ob,house:sb,plus:ab,minus:ib,pencil:lb,trash:cb,"trash-2":db,save:pb,download:ub,share:mb,funnel:gb,settings:fb,"rotate-cw":hb,maximize:yb,minimize:bb,"shopping-cart":xb,"shopping-bag":vb,package:wb,truck:Cb,tag:Ab,gift:Sb,receipt:Eb,wallet:Tb,store:Mb,"dollar-sign":kb,percent:Lb,play:Pb,pause:Ib,"volume-x":Rb,camera:Wb,image:Hb,film:Bb,headphones:Db,"message-circle":Nb,"message-square":Ob,bell:Fb,heart:_b,star:$b,eye:jb,"eye-off":Ub,bookmark:qb,"calendar-days":zb,history:Vb,timer:Kb,folder:Gb,"folder-open":Jb,files:Qb,sparkles:Xb,zap:Yb,sun:Zb,moon:ex,flag:tx,monitor:nx,smartphone:rx},me=(e,t=24,n="currentColor",r=2)=>{let o=ox[e];return o?sx(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 sx(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 Va={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function ax(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ix(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 vs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Va.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Va.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Va.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:Va.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=lm(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 im(l),f=ja(l)?URL.createObjectURL(l):null,g={id:ax(),file:l,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}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=ja(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",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=ix(t.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=cm(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 vm=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];vm(s)&&vm(o)?n[r]=na(s,o):n[r]=o}return n}var ar="min(440px, calc(100vw - 24px))",ol="440px",lx={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:ar,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)"},_t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:lx,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 wm(e,t){if(!(!e&&!t))return e?t?na(e,t):e:t}function sl(e){var t,n,r,o,s,a,i,d,l,p,u,f,g,v,x,T,S,k,M,E,L;return e?{..._t,...e,theme:wm(_t.theme,e.theme),darkTheme:wm(_t.darkTheme,e.darkTheme),launcher:{..._t.launcher,...e.launcher,dock:{...(t=_t.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=_t.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{..._t.copy,...e.copy},sendButton:{..._t.sendButton,...e.sendButton},statusIndicator:{..._t.statusIndicator,...e.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...e.voiceRecognition},features:(()=>{var le,oe,re,We,Oe,K,G,ve,X,ie;let C=(le=_t.features)==null?void 0:le.artifacts,R=(oe=e.features)==null?void 0:oe.artifacts,F=(re=_t.features)==null?void 0:re.scrollToBottom,j=(We=e.features)==null?void 0:We.scrollToBottom,W=(Oe=_t.features)==null?void 0:Oe.scrollBehavior,O=(K=e.features)==null?void 0:K.scrollBehavior,N=(G=_t.features)==null?void 0:G.streamAnimation,Z=(ve=e.features)==null?void 0:ve.streamAnimation,Ae=(X=_t.features)==null?void 0:X.askUserQuestion,de=(ie=e.features)==null?void 0:ie.askUserQuestion,ee=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},xe=F===void 0&&j===void 0?void 0:{...F,...j},Te=W===void 0&&O===void 0?void 0:{...W,...O},ne=N===void 0&&Z===void 0?void 0:{...N,...Z},be=Ae===void 0&&de===void 0?void 0:{...Ae,...de,styles:{...Ae==null?void 0:Ae.styles,...de==null?void 0:de.styles}};return{..._t.features,...e.features,...xe!==void 0?{scrollToBottom:xe}:{},...Te!==void 0?{scrollBehavior:Te}:{},...ee!==void 0?{artifacts:ee}:{},...ne!==void 0?{streamAnimation:ne}:{},...be!==void 0?{askUserQuestion:be}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{..._t.layout,...e.layout,header:{...(a=_t.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=_t.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=_t.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(x=(v=_t.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(S=(T=e.layout)==null?void 0:T.messages)==null?void 0:S.timestamp}},slots:{...(k=_t.layout)==null?void 0:k.slots,...(M=e.layout)==null?void 0:M.slots}},markdown:{..._t.markdown,...e.markdown,options:{...(E=_t.markdown)==null?void 0:E.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{..._t.messageActions,...e.messageActions}}:_t}var Cm={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"}},Am={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"}},Sm={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:ar,maxWidth:ol,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 ws(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."))?ws(e,r):r}function al(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=ws(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 Em(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 Tm(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]=Tm(s,o):n[r]=o}return n}function cx(e,t){return t?Tm(e,t):e}function ra(e,t={}){var o,s,a,i,d,l,p,u,f,g,v,x,T;let n={palette:Cm,semantic:Am,components:Sm},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,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.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,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:cx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let S=Em(r);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(k=>k.message).join(", ")}`)}if(t.plugins)for(let S of t.plugins)r=S.transform(r);return r}function il(e){var x,T,S,k,M,E,L,C,R,F,j,W,O,N,Z,Ae,de,ee,xe,Te,ne,be,le,oe,re,We,Oe,K,G,ve,X,ie,Re,ge,Ge,nt,Pt,Ye,_e,J,Ve,ze,we,Se,Ze,Qe,Ee,$e,un,Dt,Yt,Nr,H,V,pe,Be,je,De,Le,it,It,ht,Rt,P,ce,Me,Et,et,Ut,bn,bt,xt,Wt,vt,mn,$t,On,En,Tn,xn,Mn,cr,wt,xr,vr,Or,dr,pt,So,wr,Eo,Hn,Xo,Xr,Fr,Yr,Zr,To,Mo,eo,yt,Fn,_n,kn,Ct,Xn,Yn,$n,to,_r,no,jn,Ht,Ln,Zn,ro,$r,oo;let t=al(e),n={};for(let[he,Bn]of Object.entries(t)){let Cr=he.replace(/\./g,"-");n[`--persona-${Cr}`]=Bn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(T=n["--persona-semantic-colors-secondary"])!=null?T:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(S=n["--persona-semantic-colors-accent"])!=null?S:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(k=n["--persona-semantic-colors-surface"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(M=n["--persona-semantic-colors-background"])!=null?M:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(E=n["--persona-semantic-colors-container"])!=null?E:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(L=n["--persona-semantic-colors-text"])!=null?L: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"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ae=n["--persona-components-approval-requested-background"])!=null?Ae:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(xe=n["--persona-components-approval-requested-shadow"])!=null?xe:"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"]=(Te=n["--persona-components-approval-approve-background"])!=null?Te:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ne=n["--persona-components-approval-deny-background"])!=null?ne:n["--persona-container"],n["--persona-attachment-image-bg"]=(be=n["--persona-components-attachment-image-background"])!=null?be: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"]=(oe=n["--persona-semantic-typography-fontFamily"])!=null?oe:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(re=n["--persona-semantic-typography-fontSize"])!=null?re:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(We=n["--persona-semantic-typography-fontWeight"])!=null?We:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Oe=n["--persona-semantic-typography-lineHeight"])!=null?Oe: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"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(G=n["--persona-palette-radius-md"])!=null?G:"0.375rem",n["--persona-radius-lg"]=(ve=n["--persona-palette-radius-lg"])!=null?ve:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(ie=n["--persona-palette-radius-full"])!=null?ie:"9999px",n["--persona-launcher-radius"]=(ge=(Re=n["--persona-components-launcher-borderRadius"])!=null?Re:n["--persona-palette-radius-full"])!=null?ge:"9999px",n["--persona-launcher-bg"]=(Ge=n["--persona-components-launcher-background"])!=null?Ge:n["--persona-primary"],n["--persona-launcher-fg"]=(nt=n["--persona-components-launcher-foreground"])!=null?nt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Pt=n["--persona-components-launcher-border"])!=null?Pt:n["--persona-border"],n["--persona-button-primary-bg"]=(Ye=n["--persona-components-button-primary-background"])!=null?Ye:n["--persona-primary"],n["--persona-button-primary-fg"]=(_e=n["--persona-components-button-primary-foreground"])!=null?_e:n["--persona-text-inverse"],n["--persona-button-radius"]=(Ve=(J=n["--persona-components-button-primary-borderRadius"])!=null?J:n["--persona-palette-radius-full"])!=null?Ve:"9999px",n["--persona-panel-radius"]=(we=(ze=n["--persona-components-panel-borderRadius"])!=null?ze:n["--persona-radius-xl"])!=null?we:"0.75rem",n["--persona-panel-border"]=(Se=n["--persona-components-panel-border"])!=null?Se:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Qe=(Ze=n["--persona-components-panel-shadow"])!=null?Ze:n["--persona-palette-shadows-xl"])!=null?Qe:"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"]=(un=($e=n["--persona-components-input-borderRadius"])!=null?$e:n["--persona-radius-lg"])!=null?un:"0.5rem",n["--persona-message-user-radius"]=(Yt=(Dt=n["--persona-components-message-user-borderRadius"])!=null?Dt:n["--persona-radius-lg"])!=null?Yt:"0.5rem",n["--persona-message-assistant-radius"]=(H=(Nr=n["--persona-components-message-assistant-borderRadius"])!=null?Nr:n["--persona-radius-lg"])!=null?H:"0.5rem",n["--persona-header-bg"]=(V=n["--persona-components-header-background"])!=null?V:n["--persona-surface"],n["--persona-header-border"]=(pe=n["--persona-components-header-border"])!=null?pe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Be=n["--persona-components-header-iconBackground"])!=null?Be:n["--persona-primary"],n["--persona-header-icon-fg"]=(je=n["--persona-components-header-iconForeground"])!=null?je:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(De=n["--persona-components-header-titleForeground"])!=null?De:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Le=n["--persona-components-header-subtitleForeground"])!=null?Le:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(it=n["--persona-components-header-actionIconForeground"])!=null?it: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=(ht=e.components)==null?void 0:ht.introCard;n["--persona-intro-card-bg"]=(Rt=n["--persona-components-introCard-background"])!=null?Rt:n["--persona-surface"],n["--persona-intro-card-radius"]=(P=n["--persona-components-introCard-borderRadius"])!=null?P:"1rem",n["--persona-intro-card-padding"]=(ce=n["--persona-components-introCard-padding"])!=null?ce:"1.5rem",n["--persona-intro-card-shadow"]=(Et=(Me=o==null?void 0:o.shadow)!=null?Me:n["--persona-components-introCard-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(et=n["--persona-components-input-background"])!=null?et:n["--persona-surface"],n["--persona-input-placeholder"]=(Ut=n["--persona-components-input-placeholder"])!=null?Ut:n["--persona-text-muted"],n["--persona-message-user-bg"]=(bn=n["--persona-components-message-user-background"])!=null?bn:n["--persona-accent"],n["--persona-message-user-text"]=(bt=n["--persona-components-message-user-text"])!=null?bt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(xt=n["--persona-components-message-user-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Wt=n["--persona-components-message-assistant-background"])!=null?Wt:n["--persona-surface"],n["--persona-message-assistant-text"]=(vt=n["--persona-components-message-assistant-text"])!=null?vt:n["--persona-text"],n["--persona-message-assistant-border"]=(mn=n["--persona-components-message-assistant-border"])!=null?mn:n["--persona-border"],n["--persona-message-assistant-shadow"]=($t=n["--persona-components-message-assistant-shadow"])!=null?$t:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(En=(On=n["--persona-components-scrollToBottom-background"])!=null?On:n["--persona-button-primary-bg"])!=null?En:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(xn=(Tn=n["--persona-components-scrollToBottom-foreground"])!=null?Tn:n["--persona-button-primary-fg"])!=null?xn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Mn=n["--persona-components-scrollToBottom-border"])!=null?Mn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(cr=n["--persona-components-scrollToBottom-size"])!=null?cr:"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"]=(dr=(Or=n["--persona-components-scrollToBottom-shadow"])!=null?Or:n["--persona-palette-shadows-sm"])!=null?dr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(pt=n["--persona-components-scrollToBottom-padding"])!=null?pt:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(So=n["--persona-components-scrollToBottom-gap"])!=null?So:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Eo=(wr=n["--persona-components-scrollToBottom-fontSize"])!=null?wr:n["--persona-palette-typography-fontSize-sm"])!=null?Eo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Hn=n["--persona-components-scrollToBottom-iconSize"])!=null?Hn:"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"]=(Xr=n["--persona-components-reasoningBubble-shadow"])!=null?Xr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"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"]=(Mo=(To=n["--persona-components-markdown-link-foreground"])!=null?To:n["--persona-accent"])!=null?Mo:"#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"]=(yt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?yt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Fn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Fn:"inherit",n["--persona-md-table-header-bg"]=(_n=n["--persona-components-markdown-table-headerBackground"])!=null?_n:n["--persona-container"],n["--persona-md-table-border-color"]=(kn=n["--persona-components-markdown-table-borderColor"])!=null?kn: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"]=(Yn=n["--persona-components-markdown-blockquote-background"])!=null?Yn:"transparent",n["--persona-md-blockquote-text-color"]=($n=n["--persona-components-markdown-blockquote-textColor"])!=null?$n:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(to=n["--persona-components-collapsibleWidget-container"])!=null?to:n["--persona-surface"],n["--cw-surface"]=(_r=n["--persona-components-collapsibleWidget-surface"])!=null?_r:n["--persona-surface"],n["--cw-border"]=(no=n["--persona-components-collapsibleWidget-border"])!=null?no:n["--persona-border"],n["--persona-message-border"]=(jn=n["--persona-components-message-border"])!=null?jn: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 f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let he=v.toolbar;he.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,n["--persona-dropdown-bg"]=(Ht=n["--persona-dropdown-bg"])!=null?Ht:he.copyMenuBackground),he.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,n["--persona-dropdown-border"]=(Ln=n["--persona-dropdown-border"])!=null?Ln:he.copyMenuBorder),he.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,n["--persona-dropdown-shadow"]=(Zn=n["--persona-dropdown-shadow"])!=null?Zn:he.copyMenuShadow),he.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ro=n["--persona-dropdown-radius"])!=null?ro:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=($r=n["--persona-dropdown-item-hover-bg"])!=null?$r:he.copyMenuItemHoverBackground),he.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(v!=null&&v.tab){let he=v.tab;he.background&&(n["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(n["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(n["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(n["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(n["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(n["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(n["--persona-artifact-tab-list-padding"]=he.listPadding)}if(v!=null&&v.pane){let he=v.pane;if(he.toolbarBackground){let Bn=(oo=ws(e,he.toolbarBackground))!=null?oo:he.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Bn}}return n}var dx={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 px={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"}}},Mm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ka=()=>{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"},ux=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ka()},km=e=>ux(e),mx=e=>ra(e),gx=e=>{var n;let t=ra(void 0,{validate:!1});return ra({...e,palette:{...t.palette,colors:{...px.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},oa=e=>{let t=km(e),n=Mm(e==null?void 0:e.theme),r=Mm(e==null?void 0:e.darkTheme);return t==="dark"?gx(na(n!=null?n:{},r!=null?r:{})):mx(n)},fx=e=>il(e),zo=(e,t)=>{let n=oa(t),r=fx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},ll=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ka())});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(Ka());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 hx}from"idiomorph";var Ga=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;hx.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 Lm=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Ja={index:-1,draft:""};function Pm(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:{...Ja}}}function Im(e,t){var n,r,o,s,a,i,d,l,p,u,f,g,v,x,T,S,k,M,E,L,C,R,F,j,W,O,N,Z,Ae,de,ee,xe,Te,ne,be,le,oe,re;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,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(T=(x=e.toolCall)==null?void 0:x.name)!=null?T:"",(M=(k=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:k.length)!=null?M:0,(R=(C=(L=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:L[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,(ee=(de=(Ae=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Ae[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?ee:0,(be=(ne=(Te=(xe=e.reasoning)==null?void 0:xe.chunks)==null?void 0:Te[e.reasoning.chunks.length-1])==null?void 0:ne.slice(-32))!=null?be:"",(oe=(le=e.contentParts)==null?void 0:le.length)!=null?oe:0,(re=e.stopReason)!=null?re:"",t].join("\0")}function Rm(){return new Map}function Wm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Hm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Bm(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 Jr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Vo(e,t){return Jr(e)-e.scrollTop<=t}function Xa(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 Ya(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 Dm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Nm(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 Om(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var An={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Sn=1e5,bo=Sn+1;var sa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},yx=["pre","code","a","script","style"],Za=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}},_m=[{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 _m)aa.set(e.name,e);var bx=e=>{aa.set(e.name,e)},xx=e=>{_m.some(t=>t.name===e)||aa.delete(e)},vx=()=>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},ei=(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},wx=(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},Cx=(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},cl=/\s/,Ax=(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},Sx=(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(cl.test(s[i])){let l=i;for(;l<s.length&&cl.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&&!cl.test(s[p]);)l.appendChild(wx(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Ex=(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(Cx(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},la=(e,t,n,r)=>{var u,f;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:yx).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Ax(d,s)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?Sx:Ex;for(let g of i)p(g,n,l);return o.innerHTML},ti=(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},Fm=new WeakMap,Tx=(e,t)=>{var s;if(!e.styles)return;let n=Fm.get(t);if(n||(n=new Set,Fm.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)},dl=new WeakMap,Mx=(e,t)=>{if(!e.onAttach)return;let n=dl.get(t);if(n||(n=new Map,dl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},$m=e=>{let t=dl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},pl=(e,t)=>{Tx(e,t),Mx(e,t)};function ul(e,t=Sn){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,xo=null;function ml(e=document){var n;if(da++,da===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;xo={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&&xo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=xo.originalOverflow,o.style.position=xo.originalPosition,o.style.top=xo.originalTop,o.style.width=xo.originalWidth,s.scrollTo(0,xo.scrollY),xo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},pn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},vo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},ir=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 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 kx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ni=(e,t={})=>{var T,S,k,M,E,L;let{showClose:n=!0,wrapperClassName:r=kx,buttonSize:o,iconSize:s="28px"}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=(S=o!=null?o:a.closeButtonSize)!=null?S:"32px",d=y("div",r),l=(k=a.closeButtonTooltipText)!=null?k:"Close chat",p=(M=a.closeButtonShowTooltip)!=null?M:!0,u=(E=a.closeButtonIconName)!=null?E:"x",f=(L=a.closeButtonIconText)!=null?L:"\xD7",g=!!(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",!g&&"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||Wn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${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=f,d.appendChild(v),p&&l){let C=null,R=()=>{if(C)return;let j=v.ownerDocument,W=j.body;if(!W)return;C=Hr(j,"div","persona-clear-chat-tooltip"),C.textContent=l;let O=Hr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(bo),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}},Lx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ri=(e,t={})=>{var C,R,F,j,W,O,N,Z,Ae,de,ee,xe,Te;let{wrapperClassName:n=Lx,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:"",f=(Z=a.borderColor)!=null?Z:"",g=(Ae=a.borderRadius)!=null?Ae:"",v=(de=a.paddingX)!=null?de:"",x=(ee=a.paddingY)!=null?ee:"",T=(xe=a.tooltipText)!=null?xe:"Clear chat",S=(Te=a.showTooltip)!=null?Te:!0,k=y("div",n),M=!!(u||f),E=St("button",{className:qs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!M&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:l||Wn.actionIconColor,backgroundColor:p||void 0,border:M?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),L=me(d,o,"currentColor",1);if(L&&(L.style.display="block",E.appendChild(L)),k.appendChild(E),S&&T){let ne=null,be=()=>{if(ne)return;let oe=E.ownerDocument,re=oe.body;if(!re)return;ne=Hr(oe,"div","persona-clear-chat-tooltip"),ne.textContent=T;let We=Hr(oe,"div");We.className="persona-clear-chat-tooltip-arrow",ne.appendChild(We);let Oe=E.getBoundingClientRect();ne.style.position="fixed",ne.style.zIndex=String(bo),ne.style.left=`${Oe.left+Oe.width/2}px`,ne.style.top=`${Oe.top-8}px`,ne.style.transform="translate(-50%, -100%)",re.appendChild(ne)},le=()=>{ne&&ne.parentNode&&(ne.parentNode.removeChild(ne),ne=null)};k.addEventListener("mouseenter",be),k.addEventListener("mouseleave",le),E.addEventListener("focus",be),E.addEventListener("blur",le),k._cleanupTooltip=()=>{le(),k.removeEventListener("mouseenter",be),k.removeEventListener("mouseleave",le),E.removeEventListener("focus",be),E.removeEventListener("blur",le)}}return{button:E,wrapper:k}};var Wn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},wo=e=>{var L,C,R,F,j,W,O,N,Z,Ae,de,ee,xe,Te,ne,be;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=(L=t==null?void 0:t.launcher)!=null?L:{},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,oe=me(d,le*.6,"currentColor",1);oe?l.replaceChildren(oe):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=(Z=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?Z:"\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=(Ae=t==null?void 0:t.launcher)==null?void 0:Ae.title)!=null?de:"Chat Assistant",style:{color:Wn.titleColor}}),f=St("span",{className:"persona-text-xs",text:(xe=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?xe:"Here to help you get answers fast",style:{color:Wn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(l,p);let g=(Te=o.clearChat)!=null?Te:{},v=(ne=g.enabled)!=null?ne:!0,x=(be=g.placement)!=null?be:"inline",T=null,S=null;if(v){let oe=ri(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=oe.button,S=oe.wrapper,x==="top-right"&&(S.style.right="48px"),x==="inline"&&r.appendChild(S)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:M,wrapper:E}=ni(t,{showClose:n,wrapperClassName:k});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:f,closeButton:M,closeButtonWrapper:E,clearChatButton:T,clearChatButtonWrapper:S}},Cs=(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 Ko(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(bo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let T=me(g.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let x=document.createElement("span");x.textContent=g.label,v.appendChild(x),v.addEventListener("click",T=>{T.stopPropagation(),p(),n(g.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:f}}function Jt(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 oi(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 f=me(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function si(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=Jt({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 gl(e){var g,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=(g=d.borderRadius)!=null?g:"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,T;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(T=d.border)!=null?T:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Ko({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let T=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",T?"false":"true"),f.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"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var jm=e=>{var r;let t=wo({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 Px(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=Ko({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 Um=e=>{var k,M,E,L,C,R,F,j,W;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(k=t==null?void 0:t.launcher)!=null?k:{},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=gl({label:(M=a.title)!=null?M:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Wn.titleColor,p=(E=l.querySelector(".persona-combo-btn-label"))!=null?E: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=Wn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",l.appendChild(p),Px(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",Z=>{Z.target.closest("button")||N()}),l.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.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,Z;l.style.backgroundColor=(N=O.background)!=null?N:"",l.style.borderColor=(Z=O.border)!=null?Z:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(j=a.closeButtonSize)!=null?j:"32px",f=y("div",""),g=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");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Wn.actionIconColor;let v=(W=a.closeButtonIconName)!=null?W:"x",x=me(v,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let T=y("div");T.style.display="none";let S=y("span");return S.style.display="none",{header:i,iconHolder:T,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},fl={default:jm,minimal:Um},qm=e=>{var t;return(t=fl[e])!=null?t:fl.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"),f=y("span"),g=y("button");g.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=qm(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 ai=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}},ii=e=>{var L,C,R,F,j,W,O,N,Z,Ae,de,ee;let t=(L=e==null?void 0:e.sendButton)!=null?L:{},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=(Ae=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Ae:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(ee=t.size)!=null?ee:"40px",f=t.backgroundColor,g=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&&!f&&"persona-bg-persona-primary",!n&&!g&&"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?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,S=null;if(n){let xe=parseFloat(u)||24,Te=(g==null?void 0:g.trim())||"currentColor";o?(T=me(o,xe,Te,2),T?x.appendChild(T):x.textContent=r):x.textContent=r,S=me(s,xe,Te,2)}else x.textContent=d;let k=null;p&&a&&(k=y("div","persona-send-button-tooltip"),k.textContent=a,v.appendChild(k)),x.setAttribute("aria-label",a),v.appendChild(x);let M="send";return{button:x,wrapper:v,setMode:xe=>{if(xe===M)return;M=xe;let Te=xe==="stop"?i:a;if(x.setAttribute("aria-label",Te),k&&(k.textContent=Te),n){if(T&&S){let ne=xe==="stop"?S:T;x.replaceChildren(ne)}}else x.textContent=xe==="stop"?l:d}}},li=e=>{var k,M,E,L,C,R,F,j,W,O,N,Z;let t=(k=e==null?void 0:e.voiceRecognition)!=null?k:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((M=t.provider)==null?void 0:M.type)==="runtype";if(!(r||o))return null;let a=(L=(E=e==null?void 0:e.sendButton)==null?void 0:E.size)!=null?L:"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,f=y("div","persona-send-button-wrapper"),g=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?g.appendChild(x):g.textContent="\u{1F3A4}",f.appendChild(g);let T=(N=t.tooltipText)!=null?N:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&T){let Ae=y("div","persona-send-button-tooltip");Ae.textContent=T,f.appendChild(Ae)}return{button:g,wrapper:f}},ci=e=>{var v,x,T,S,k,M,E,L;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(T=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?T:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((S=t.allowedTypes)!=null?S:Gr).join(","),o.multiple=((k=t.maxFiles)!=null?k:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(M=t.buttonIconName)!=null?M:"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":(E=t.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});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 f=(L=t.buttonTooltipText)!=null?L:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,l.appendChild(g),{button:p,wrapper:l,input:o,previewsContainer:r}},di=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},pi=()=>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,T,S,k,M;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=pi(),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}=ai(t);a();let i=ii(t),d=li(t),l=ci(t),p=di(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":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(l==null?void 0:l.button)&&E.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:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var zm=()=>{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}},Vm=e=>{var v,x,T,S,k,M;let{config:t}=e,n=St("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=pi();r.style.display="none";let o=di(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ai(t);s.style.maxHeight="100px",a();let i=ii(t),d=li(t),l=ci(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 f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(l==null?void 0:l.button)&&E.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,f),l&&n.append(l.previewsContainer),n.append(p,r,o);let g=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:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(S=l==null?void 0:l.wrapper)!=null?S:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(M=l==null?void 0:l.previewsContainer)!=null?M:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Km=e=>{var p,u,f,g,v,x,T,S,k,M,E,L,C,R,F,j,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=pn(e);if(vo(e)){let O=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},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((T=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?T:Sn);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",N.appendChild(Z);let Ae=y("div","persona-widget-pill-root");return Ae.setAttribute("data-persona-composer-bar",""),Ae.dataset.state="collapsed",Ae.dataset.expandedSize=(S=O.expandedSize)!=null?S:"anchored",Ae.style.zIndex=String((M=(k=e==null?void 0:e.launcher)==null?void 0:k.zIndex)!=null?M:Sn),{wrapper:N,panel:Z,pillRoot:Ae}}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"),Z=(L=(E=e==null?void 0:e.launcher)==null?void 0:E.width)!=null?L:"100%";return O.style.width=Z,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:Sn);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:ar;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Ix=(e,t)=>{var E,L,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}=ni(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=(L=(E=e==null?void 0:e.launcher)==null?void 0:E.clearChat)==null?void 0:L.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=ri(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=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."}),f=St("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),g=y("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(g.style.maxWidth=v,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((N=e==null?void 0:e.copy)==null?void 0:N.showWelcomeCard)!==!1||(f.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(f,g);let T=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"}}),S=Vm({config:e}),{root:k,textNode:M}=zm();return n.append(d,o,l,T),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:g,composerOverlay:T,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.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:S.footer,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:k,peekTextNode:M}},Gm=(e,t=!0)=>{var T,S,k,M,E,L,C,R,F;if(vo(e))return Ix(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=(T=e==null?void 0:e.layout)==null?void 0:T.header,o=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,s=r?ua(e,r,{showClose:t}):wo({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:(M=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?M:"Hello \u{1F44B}"}),d=St("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(E=e==null?void 0:e.copy)==null?void 0:E.welcomeSubtitle)!=null?L:"Ask anything about your account or products."}),l=St("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:pn(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 g=ma({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;o?Cs(n,s,e):(s.header.style.display="none",Cs(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||(g.footer.style.display="none"),n.append(g.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var hl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
18
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>
19
21
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
20
22
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -22,14 +24,14 @@ _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]
22
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
23
25
  </span>
24
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>
25
- `,n.addEventListener("click",t);let r=o=>{var N,M,P,S,W,B,D,k,j,z,te,Pe,je;let a=(N=o.launcher)!=null?N:{},i=dn(o),d=n.querySelector("[data-role='launcher-title']");if(d){let Se=(M=a.title)!=null?M:"Chat Assistant";d.textContent=Se,d.setAttribute("title",Se)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let Se=(P=a.subtitle)!=null?P:"Here to help you get answers fast";c.textContent=Se,c.setAttribute("title",Se)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let Se=(S=a.agentIconSize)!=null?S:"40px";if(m.style.height=Se,m.style.width=Se,m.innerHTML="",a.agentIconName){let ke=parseFloat(Se)||24,Fe=xe(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);Fe?(m.appendChild(Fe),m.style.display=""):(m.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",m.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let Se=(D=a.agentIconSize)!=null?D:"40px";f.style.height=Se,f.style.width=Se,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let Se=(k=a.callToActionIconSize)!=null?k:"32px";g.style.height=Se,g.style.width=Se,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Fe=parseFloat(Se)||24,he=Math.max(Fe-ke,8),Be=xe(a.callToActionIconName,he,"currentColor",2);Be?g.appendChild(Be):g.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else g.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}let x=a.position&&hr[a.position]?hr[a.position]:hr["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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:`${v} ${x}`,i||(n.style.zIndex=String((te=a.zIndex)!=null?te:wn));let C="1px solid var(--persona-border, #e5e7eb)",I="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=(Pe=a.border)!=null?Pe:C,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,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=(je=a.collapsedMaxWidth)!=null?je:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var jm=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:s}=_m(e),o=$m(e,t),a={wrapper:n,panel:r,pillRoot:s},i={container:o.container,body:o.body,messagesWrapper:o.messagesWrapper,composerOverlay:o.composerOverlay,introTitle:o.introTitle,introSubtitle:o.introSubtitle},d={element:o.header,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper},c={footer:o.footer,form:o.composerForm,textarea:o.textarea,sendButton:o.sendButton,sendButtonWrapper:o.sendButtonWrapper,micButton:o.micButton,micButtonWrapper:o.micButtonWrapper,statusText:o.statusText,suggestions:o.suggestions,attachmentButton:o.attachmentButton,attachmentButtonWrapper:o.attachmentButtonWrapper,attachmentInput:o.attachmentInput,attachmentPreviewsContainer:o.attachmentPreviewsContainer,actionsRow:o.actionsRow,leftActions:o.leftActions,rightActions:o.rightActions,setSendButtonMode:o.setSendButtonMode,peekBanner:o.peekBanner,peekTextNode:o.peekTextNode};return{shell:a,panelElements:o,transcript:i,header:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},fl=({config:e,plugins:t,onToggle:n})=>{let r=t.find(o=>o.renderLauncher);if(r!=null&&r.renderLauncher){let o=r.renderLauncher({config:e,defaultRenderer:()=>gl(e,n).element,onToggle:n});if(o)return{instance:null,element:o}}let s=gl(e,n);return{instance:s,element:s.element}};var hx=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}},yx=(e,t)=>{if(!e)return null;let n=hx(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},bx=(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},xx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},hl=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(":"))},yl=320,qm=320,vx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),wx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Cx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Sx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Ax=(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 s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var m;let c=y("img");c.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${yl}px`,c.style.maxHeight=`${qm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),xx(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Tx=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(!hl(r.audio))return;let s=y("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${yl}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ex=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(!hl(r.video))return;let s=y("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${yl}px`,s.style.maxHeight=`${qm}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Mx=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(!hl(r.data))return;let s=y("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},bs=()=>{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 s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},zm=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:bs};if(t){let s=t(r);if(s!==null)return s}return bs()},kx=(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 s=y("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=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},Um=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?r.textContent=t.format(s):r.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Lx=(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},Vm=(e,t,n)=>{var x,v,E,C,I,N,M;let r=(x=t.showCopy)!=null?x:!0,s=(v=t.showUpvote)!=null?v:!0,o=(E=t.showDownvote)!=null?E:!0,a=(C=t.showReadAloud)!=null?C:!1;if(!r&&!s&&!o&&!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=(I=t.visibility)!=null?I:"hover",d=(N=t.align)!=null?N:"right",c=(M=t.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(P,S,W)=>{let B=qt({icon:P,label:S,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",W),B};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),s&&f.appendChild(g("thumbs-up","Upvote","upvote")),o&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},ca=(e,t,n,r,s,o)=>{var ae,Q,ne,le,re,G,ee,qe,J,ie,Re,ve,Xe,Ke,Ne,ce,et;let a=n!=null?n:{},i=(ae=a.layout)!=null?ae:"bubble",d=a.avatar,c=a.timestamp,p=(Q=d==null?void 0:d.show)!=null?Q:!1,m=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(le=d==null?void 0:d.position)!=null?le:"left",g=(re=c==null?void 0:c.position)!=null?re:"below",x=Lx(e.role,i),v=y("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=vx(e),C=(ee=(G=e.content)==null?void 0:G.trim())!=null?ee:"",N=E.length>0&&C===Na,M=Qa((J=(qe=o==null?void 0:o.widgetConfig)==null?void 0:qe.features)==null?void 0:J.streamAnimation),P=(ve=(Re=(ie=o==null?void 0:o.widgetConfig)==null?void 0:ie.features)==null?void 0:Re.streamAnimation)==null?void 0:ve.plugins,S=e.role==="assistant"&&M.type!=="none"?na(M.type,P):null,W=e.role==="assistant"&&((Xe=S==null?void 0:S.isAnimating)==null?void 0:Xe.call(S,e))===!0,B=e.role==="assistant"&&S!==null&&(!!e.streaming||W);B&&(S!=null&&S.bubbleClass)&&v.classList.add(S.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),B&&S&&(S.containerClass&&D.classList.add(S.containerClass),D.style.setProperty("--persona-stream-step",`${M.speed}ms`),D.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let k=B?Xa((Ke=e.content)!=null?Ke:"",M.buffer,S,e,!!e.streaming):(Ne=e.content)!=null?Ne:"",j=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),z=j;B&&(S==null?void 0:S.wrap)==="char"?z=ra(j,"char",e.id,{skipTags:S.skipTags}):B&&(S==null?void 0:S.wrap)==="word"&&(z=ra(j,"word",e.id,{skipTags:S.skipTags}));let te=null;if(N?(te=document.createElement("div"),te.innerHTML=z,te.style.display="none",D.appendChild(te)):D.innerHTML=z,B&&(S!=null&&S.useCaret)&&!N&&C){let X=Ya(),de=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=de[de.length-1];if(we!=null&&we.parentNode)we.parentNode.insertBefore(X,we.nextSibling);else{let ze=D.lastElementChild;ze?ze.appendChild(X):D.appendChild(X)}}if(m&&g==="inline"&&e.createdAt){let X=Um(e,c,"span");X.classList.add("persona-timestamp-inline");let de=D.lastElementChild;de?de.appendChild(X):D.appendChild(X)}if(E.length>0){let X=Ax(E,!N&&!!C,()=>{N&&te&&(te.style.display="")});X?v.appendChild(X):N&&te&&(te.style.display="")}let Pe=wx(e);if(Pe.length>0){let X=Tx(Pe);X&&v.appendChild(X)}let je=Cx(e);if(je.length>0){let X=Ex(je);X&&v.appendChild(X)}let Se=Sx(e);if(Se.length>0){let X=Mx(Se);X&&v.appendChild(X)}if(v.appendChild(D),m&&g==="below"&&e.createdAt){let X=Um(e,c);X.classList.add("persona-mt-1"),v.appendChild(X)}let ke=e.role==="assistant"?yx(e.stopReason,(et=(ce=o==null?void 0:o.widgetConfig)==null?void 0:ce.copy)==null?void 0:et.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(k&&k.trim()),de=M.placeholder==="skeleton",we=de&&M.buffer==="line"&&X;if(X)we&&v.appendChild(oa());else if(de)v.appendChild(oa());else{let ze=zm("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);ze&&v.appendChild(ze)}}if(ke&&e.stopReason&&!e.streaming&&(C||(D.style.display="none"),v.appendChild(bx(e.stopReason,ke))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=Vm(e,r,s);v.appendChild(X)}if(!p||e.role==="system")return v;let he=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Be=kx(d,e.role);return f==="right"||f==="left"&&e.role==="user"?he.append(v,Be):he.append(Be,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),he},Px=(e,t,n,r,s,o)=>{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,s,o)};var xs=new Set,Ix=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Rx=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Km=(e,t)=>{let n=xs.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=xe(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},bl=(e,t)=>{var je,Se,ke,Fe,he,Be,ae,Q,ne,le,re;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 s=(Se=(je=t==null?void 0:t.features)==null?void 0:je.reasoningDisplay)!=null?Se:{},o=s.expandable!==!1,a=o&&xs.has(e.id),i=n.status!=="complete",d=Rx(e,(ke=s.previewMaxLines)!=null?ke:3),c=y("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Fe=t==null?void 0:t.reasoning)!=null?Fe:{},x=String((he=n.startedAt)!=null?he:Date.now()),v=()=>{let G=y("span","");return G.setAttribute("data-tool-elapsed",x),G.textContent=Ha(n),G},E=(Be=g.renderCollapsedSummary)==null?void 0:Be.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ha(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(m.textContent=E,p.appendChild(m)):E instanceof HTMLElement?p.appendChild(E):(m.textContent=f,p.appendChild(m));let C=y("span","persona-text-xs persona-text-persona-primary");C.textContent=Ju(n),p.appendChild(C);let I=(ae=s.loadingAnimation)!=null?ae:"none",N=g.activeTextTemplate,M=g.completeTextTemplate,P=i?N:M,S=E instanceof HTMLElement,W=(G,ee,qe)=>{let J=qe;for(let ie of ee){let Re=y("span","persona-tool-char");Re.style.setProperty("--char-index",String(J)),Re.textContent=ie===" "?"\xA0":ie,G.appendChild(Re),J++}return J},B=(G,ee)=>{m.textContent="";let qe=Ba(G,""),J=0;for(let ie of qe){let Re=ie.styles.length>0?(()=>{let ve=y("span",ie.styles.map(Xe=>`persona-tool-text-${Xe}`).join(" "));return m.appendChild(ve),ve})():m;if(ie.isDuration&&i)Re.appendChild(v());else{let ve=ie.isDuration?Ha(n):ie.text;ee?J=W(Re,ve,J):Re.appendChild(document.createTextNode(ve))}}};if(!S&&P)if(C.style.display="none",m.style.display="",i&&I!=="none"){let G=(Q=g.loadingAnimationDuration)!=null?Q:2e3;m.setAttribute("data-preserve-animation","true"),I==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`),B(P,!1)):(m.classList.add(`persona-tool-loading-${I}`),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),B(P,!0))}else B(P,!1);else if(!S&&i&&I!=="none"){m.style.display="";let G=(ne=g.loadingAnimationDuration)!=null?ne:2e3;if(m.setAttribute("data-preserve-animation","true"),I==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{m.classList.add(`persona-tool-loading-${I}`),m.style.setProperty("--persona-tool-anim-duration",`${G}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let ee=m.textContent||f;m.textContent="",W(m,ee,0)}n.status==="complete"&&(m.style.display="none")}else S||(n.status==="complete"?m.style.display="none":m.style.display="");let D=null;if(o){D=y("div","persona-flex persona-items-center");let ee=xe(a?"chevron-up":"chevron-down",16,"currentColor",2);ee?D.appendChild(ee):D.textContent=a?"Hide":"Show";let qe=y("div","persona-flex persona-items-center persona-ml-auto");qe.append(D),c.append(p,qe)}else c.append(p);let k=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let G=(re=(le=t==null?void 0:t.reasoning)==null?void 0:le.renderCollapsedPreview)==null?void 0:re.call(le,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Ix(k,G)||(k.textContent=d),k.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(c,k),r;let j=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let z=n.chunks.join(""),te=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return te.textContent=z||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(te),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let ee=xe(a?"chevron-up":"chevron-down",16,"currentColor",2);ee?D.appendChild(ee):D.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,j),r};var vs=new Set,Wx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Hx=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
27
- `);let s=ds(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
28
- `):""},xl=(e,t)=>{var n,r,s;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=(s=t.codeBlockTextColor)!=null?s:"var(--persona-text, #171717)"},Bx=(e,t)=>{var p,m,f,g,x;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,s=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",o=Hx(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Qu(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((x=n.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&d.activeTextTemplate?c=Vi(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Vi(n,d.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Gm=(e,t,n)=>{var p;let r=vs.has(e),s=(p=n==null?void 0:n.toolCall)!=null?p:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let m=s.toggleTextColor||s.headerTextColor||"var(--persona-primary, #171717)",f=xe(r?"chevron-up":"chevron-down",16,m,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},vl=(e,t)=>{var z,te,Pe,je,Se,ke,Fe,he,Be;let n=e.toolCall,r=(z=t==null?void 0:t.toolCall)!=null?z:{},s=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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.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 s;let o=(Pe=(te=t==null?void 0:t.features)==null?void 0:te.toolCallDisplay)!=null?Pe:{},a=o.expandable!==!1,i=a&&vs.has(e.id),{summary:d,previewText:c,isActive:p}=Bx(e,t),m=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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let x=String((je=n.startedAt)!=null?je:Date.now()),v=()=>{let ae=y("span","");return ae.setAttribute("data-tool-elapsed",x),ae.textContent=qs(n),ae},E=(ke=r.renderCollapsedSummary)==null?void 0:ke.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(Se=o.collapsedMode)!=null?Se:"tool-call",isActive:p,config:t!=null?t:{},elapsed:qs(n),createElapsedElement:v});typeof E=="string"&&E.trim()?(g.textContent=E,f.appendChild(g)):E instanceof HTMLElement?f.appendChild(E):(g.textContent=d,f.appendChild(g));let C=(Fe=o.loadingAnimation)!=null?Fe:"none",I=r.activeTextTemplate,N=r.completeTextTemplate,M=p?I:N,P=E instanceof HTMLElement,S=(ae,Q,ne)=>{let le=ne;for(let re of Q){let G=y("span","persona-tool-char");G.style.setProperty("--char-index",String(le)),G.textContent=re===" "?"\xA0":re,ae.appendChild(G),le++}return le},W=(ae,Q)=>{var G;g.textContent="";let ne=((G=n.name)==null?void 0:G.trim())||"tool",le=Ba(ae,ne),re=0;for(let ee of le){let qe=ee.styles.length>0?(()=>{let J=y("span",ee.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return g.appendChild(J),J})():g;if(ee.isDuration&&p)qe.appendChild(v());else{let J=ee.isDuration?qs(n):ee.text;Q?re=S(qe,J,re):qe.appendChild(document.createTextNode(J))}}};if(!P)if(p&&C!=="none"){let ae=(he=r.loadingAnimationDuration)!=null?he:2e3;if(g.setAttribute("data-preserve-animation","true"),C==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),M&&W(M,!1);else if(g.classList.add(`persona-tool-loading-${C}`),g.style.setProperty("--persona-tool-anim-duration",`${ae}ms`),C==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)W(M,!0);else{let Q=g.textContent||d;g.textContent="",S(g,Q,0)}}else M&&W(M,!1);let B=null;if(a){B=y("div","persona-flex persona-items-center");let ae=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",Q=xe(i?"chevron-up":"chevron-down",16,ae,2);Q?B.appendChild(Q):B.textContent=i?"Hide":"Show";let ne=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ne.append(B),m.append(f,ne)}else m.append(f);let D=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let ae=(Be=r.renderCollapsedPreview)==null?void 0:Be.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Wx(D,ae)||(D.textContent=c),D.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(m,D),s;let k=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",r.contentBackgroundColor&&(k.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(k.style.color=r.contentTextColor),r.contentPaddingX&&(k.style.paddingLeft=r.contentPaddingX,k.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(k.style.paddingTop=r.contentPaddingY,k.style.paddingBottom=r.contentPaddingY),n.name){let ae=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ae.style.color=r.contentTextColor:r.headerTextColor&&(ae.style.color=r.headerTextColor),ae.textContent=n.name,k.appendChild(ae)}if(n.args!==void 0){let ae=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",xl(ne,r),ne.textContent=ds(n.args),ae.append(Q,ne),k.appendChild(ae)}if(n.chunks&&n.chunks.length){let ae=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",xl(ne,r),ne.textContent=n.chunks.join(""),ae.append(Q,ne),k.appendChild(ae)}if(n.status==="complete"&&n.result!==void 0){let ae=y("div","persona-space-y-1"),Q=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",xl(ne,r),ne.textContent=ds(n.result),ae.append(Q,ne),k.appendChild(ae)}if(n.status==="complete"&&typeof n.duration=="number"){let ae=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ae.style.color=r.contentTextColor),ae.textContent=`Duration: ${n.duration}ms`,k.appendChild(ae)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),B){B.innerHTML="";let ae=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",Q=xe(i?"chevron-up":"chevron-down",16,ae,2);Q?B.appendChild(Q):B.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),s.append(m,D,k),s};var ci=new Map,Dx=e=>{let n=(e.startsWith(lo)?e.slice(lo.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)},Jm=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Qm=(e,t)=>{var r,s,o;let n=(s=(r=Jm(t))==null?void 0:r.detailsDisplay)!=null?s:"collapsed";return(o=ci.get(e))!=null?o:n==="expanded"},Xm=(e,t,n)=>{var a,i;let r=Jm(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.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 o=e.querySelector("[data-approval-details-chevron]");if(o){o.innerHTML="";let d=xe(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&o.appendChild(d)}},Ym=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let o=Qm(e,n);Xm(r,o,n),s.style.display=o?"":"none"};var di=(e,t)=>{var W,B,D,k,j,z,te,Pe,je,Se,ke,Fe,he,Be,ae;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(B=r==null?void 0:r.borderColor)!=null?B:"var(--persona-approval-border, #fef08a)",o.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 o;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(D=r==null?void 0:r.titleColor)!=null?D:"currentColor",p=xe(d,20,c,2);p&&i.appendChild(p);let m=y("div","persona-flex-1 persona-min-w-0"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",f.appendChild(g),!s){let Q=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",n.status),n.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):n.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):n.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),f.appendChild(Q)}m.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(lo)?Di(n.toolName):void 0,E=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),C=!n.toolName,I=E||(C?n.description:`The assistant wants to use \u201C${v!=null?v:Dx(n.toolName)}\u201D.`),N=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(N.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(N.style.color=r.descriptionColor),N.textContent=I,m.appendChild(N),n.reason){let Q=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let ne=y("span","persona-font-medium");ne.textContent=`${(z=r==null?void 0:r.reasonLabel)!=null?z:"Agent's stated reason:"} `,Q.appendChild(ne),Q.appendChild(document.createTextNode(n.reason)),m.appendChild(Q)}let M=(te=r==null?void 0:r.detailsDisplay)!=null?te:"collapsed",P=!!n.description&&!C,S=P||!!n.parameters;if(M!=="hidden"&&S){let Q=Qm(e.id,t),ne=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");ne.type="button",ne.setAttribute("data-expand-header","true"),ne.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ne.style.color=r.descriptionColor);let le=y("span");le.setAttribute("data-approval-details-label","true");let re=y("span","persona-inline-flex persona-items-center");re.setAttribute("data-approval-details-chevron","true"),ne.append(le,re),Xm(ne,Q,t),m.appendChild(ne);let G=y("div");if(G.setAttribute("data-approval-details","true"),G.style.display=Q?"":"none",P){let ee=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,G.appendChild(ee)}if(n.parameters){let ee=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&&(ee.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.style.fontSize="0.75rem",ee.style.lineHeight="1rem",ee.textContent=ds(n.parameters),G.appendChild(ee)}m.appendChild(G)}if(s){let Q=y("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let ne=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");ne.type="button",ne.style.backgroundColor=(Pe=r==null?void 0:r.approveButtonColor)!=null?Pe:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(je=r==null?void 0:r.approveButtonTextColor)!=null?je:"#ffffff",ne.setAttribute("data-approval-action","approve");let le=xe("shield-check",14,(Se=r==null?void 0:r.approveButtonTextColor)!=null?Se:"#ffffff",2);le&&(le.style.marginRight="4px",ne.appendChild(le));let re=document.createTextNode((ke=r==null?void 0:r.approveLabel)!=null?ke:"Approve");ne.appendChild(re);let G=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");G.type="button",G.style.backgroundColor=(Fe=r==null?void 0:r.denyButtonColor)!=null?Fe:"transparent",G.style.color=(he=r==null?void 0:r.denyButtonTextColor)!=null?he:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let ee=xe("shield-x",14,(Be=r==null?void 0:r.denyButtonTextColor)!=null?Be:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",G.appendChild(ee));let qe=document.createTextNode((ae=r==null?void 0:r.denyLabel)!=null?ae:"Deny");G.appendChild(qe),Q.append(ne,G),m.appendChild(Q)}return a.append(i,m),o.appendChild(a),o};var Zm=e=>{let t=[],n=null;return{buttons:t,render:(s,o,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!s||!s.length||!p&&(i!=null?i:o?o.getMessages():[]).some(E=>E.role==="user"))return;let m=document.createDocumentFragment(),f=o?o.isStreaming():!1,g=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(s.forEach(x=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=x,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!o||o.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),o.sendMessage(x))}),m.appendChild(v),t.push(v)}),e.appendChild(m),p){let x=JSON.stringify(s);x!==n&&(n=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var da=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 pa=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 s=r.result;s.objectStoreNames.contains(this.storeName)||s.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 s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.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 s of t)r.put(s)}catch{}}};var Nx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ox=new Set(["step_start","execution_start"]),Fx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),_x=new Set(["step_complete","agent_turn_complete"]),$x=new Set(["flow_complete","agent_complete"]),eg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),ng=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,zo=(e,t)=>{let n=e[t];return ng(n)?n:void 0};function wl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function pi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function jx(e,t){return typeof t.type=="string"?t.type:e}function Ux(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 qx(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 tg(e){var r,s,o,a,i;let t=zo(e,"result"),n=[zo(e,"tokens"),zo(e,"totalTokens"),t?zo(t,"tokens"):void 0,zo(e,"usage"),t?zo(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(s=(r=Jn(d.output))!=null?r:Jn(d.outputTokens))!=null?s:Jn(d.completionTokens);if(c!==void 0)return c}return(i=(o=Jn(e.outputTokens))!=null?o:Jn(e.completionTokens))!=null?i:t?(a=Jn(t.outputTokens))!=null?a:Jn(t.completionTokens):void 0}function zx(e){var n,r,s,o,a;let t=zo(e,"result");return(a=(s=(r=(n=Jn(e.executionTime))!=null?n:Jn(e.executionTimeMs))!=null?r:Jn(e.execution_time))!=null?s:Jn(e.duration))!=null?a:t?(o=Jn(t.executionTime))!=null?o:Jn(t.executionTimeMs):void 0}function Vx(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ua=class{constructor(t=Vx){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:pi(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 o;if(!ng(n)){eg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=jx(t,n),s=this.now();if(Nx.has(r)){this.startRun(s);return}if(Ox.has(r)){this.run||this.startRun(s);return}if(Fx.has(r)){if(!qx(r,n))return;let a=Ux(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+wl(i.visibleCharCount),c=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:pi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(_x.has(r)){if(!this.run)return;let a=this.run,i=tg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+wl(a.visibleCharCount),p=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:pi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if($x.has(r)){if(!this.run)return;let a=this.run,i=tg(n),d=i!=null?i:a.exactOutputTokens+wl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:pi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(eg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=zx(n);return o!=null?o:r-t.startedAt}};function ws(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Kx={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Gx={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Jx=["flowName","stepName","reasoningText","text","name","tool","toolName"],Qx=100;function Xx(e,t){let n={...Kx,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Gx}function Yx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Zx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function ev(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function tv(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 nv(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 rv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function ov(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 sv(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});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 Cl(e,t,n,r,s,o,a,i){var f;let d=s.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");ws(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(m()),c;function m(){var z,te;let g=y("div",""),x=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=xe(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let C=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(z=r.timestampFormat)!=null?z:"relative";C.textContent=I==="relative"?Yx(e.timestamp,n):Zx(e.timestamp);let N=null;r.showSequenceNumbers!==!1&&(N=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),N.textContent=String(t+1));let M=Xx(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 S=(te=r.descriptionFields)!=null?te:Jx,W=ev(e.payload,S),B=null;W&&(B=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),B.textContent=W);let D=y("div","persona-flex-1 persona-min-w-0"),k=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"),j=xe("clipboard","12px","currentColor",1.5);return j&&k.appendChild(j),k.addEventListener("click",async Pe=>{Pe.stopPropagation(),await tv(nv(e)),k.innerHTML="";let je=xe("check","12px","currentColor",1.5);je&&k.appendChild(je),setTimeout(()=>{k.innerHTML="";let Se=xe("clipboard","12px","currentColor",1.5);Se&&k.appendChild(Se)},1500)}),x.appendChild(v),x.appendChild(C),N&&x.appendChild(N),x.appendChild(P),B&&x.appendChild(B),x.appendChild(D),x.appendChild(k),g.appendChild(x),d&&g.appendChild(sv(e,a,i)),g}}function rg(e){var x,v,E,C,I;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(x=s==null?void 0:s.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",m=(I=(C=s==null?void 0:s.features)==null?void 0:C.eventStream)!=null?I:{},f=o.find(N=>N.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let N=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(N)return{element:N,update:()=>{},destroy:()=>{}}}return g();function g(){let N=m.classNames,M=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ws(M,N==null?void 0:N.panel);let P=[],S="",W="",B=null,D=[],k={},j=0,z=Ka(),te=0,Pe=0,je=!1,Se=null,ke=!1,Fe=0,he=new Set,Be=new Map,ae="",Q="",ne=null,le,re,G,ee,qe,J=null,ie=null,Re=null;function ve(){let V=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),pe=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");ws(pe,N==null?void 0:N.headerBar);let Ee=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ee.textContent="Events",le=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"),le.textContent="0",a){ie=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ie.style.cursor="help";let Qn=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Qn.textContent="Throughput",J=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"),J.textContent="-- tok/s",Re=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"),Re.style.display="none",Re.style.pointerEvents="none";let Cn=ie,en=Re,Pn=()=>{if(!en.textContent)return;let xt=Cn.getBoundingClientRect(),Dn=V.getBoundingClientRect();en.style.left=`${xt.left-Dn.left}px`,en.style.top=`${xt.bottom-Dn.top+4}px`,en.style.display="block"},br=()=>{en.style.display="none"};ie.addEventListener("mouseenter",Pn),ie.addEventListener("mouseleave",br),ie.appendChild(Qn),ie.appendChild(J)}let bt=y("div","persona-flex-1");re=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 Yt=y("option","");Yt.value="",Yt.textContent="All events",re.appendChild(Yt),G=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"),G.type="button",G.title="Copy All";let un=xe("clipboard-copy","12px","currentColor",1.5);un&&G.appendChild(un);let Wt=y("span","persona-text-xs");Wt.textContent="Copy All",G.appendChild(Wt),pe.appendChild(Ee),pe.appendChild(le),ie&&pe.appendChild(ie),pe.appendChild(bt),pe.appendChild(re),pe.appendChild(G);let nt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ws(nt,N==null?void 0:N.searchBar);let Rt=xe("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");Rt&&lt.appendChild(Rt),ee=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"),ws(ee,N==null?void 0:N.searchInput),ee.type="text",ee.placeholder="Search event payloads...",qe=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"),qe.type="button",qe.style.display="none";let Kt=xe("x","12px","currentColor",2);return Kt&&qe.appendChild(Kt),nt.appendChild(lt),nt.appendChild(ee),nt.appendChild(qe),V.appendChild(pe),V.appendChild(nt),Re&&V.appendChild(Re),V}let Xe,Ke=o.find(V=>V.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&s){let V=Ke.renderEventStreamToolbar({config:s,defaultRenderer:()=>ve(),eventCount:t.getSize(),filteredCount:0,onFilterChange:pe=>{S=pe,Pt(),hn()},onSearchChange:pe=>{W=pe,Pt(),hn()}});Xe=V!=null?V:ve()}else Xe=ve();let Ne=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");Ne.style.display="none";function ce(){if(!a||!J||!ie)return;let V=a();J.textContent=rv(V);let pe=ov(V);Re&&(Re.textContent=pe,pe||(Re.style.display="none")),pe?ie.setAttribute("aria-label",pe):ie.removeAttribute("aria-label")}let et=y("div","persona-flex-1 persona-min-h-0 persona-relative"),X=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let de=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");ws(de,N==null?void 0:N.scrollIndicator),de.style.display="none",de.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let we=xe(c,"14px","currentColor",2);we&&de.appendChild(we);let ze=y("span","");ze.textContent=p,de.appendChild(ze);let Lt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Lt.style.display="none",et.appendChild(X),et.appendChild(Lt),et.appendChild(de),M.setAttribute("tabindex","0"),M.appendChild(Xe),M.appendChild(Ne),M.appendChild(et);function Ae(){let V=t.getAll(),pe={};for(let Wt of V)pe[Wt.type]=(pe[Wt.type]||0)+1;let Ee=Object.keys(pe).sort(),bt=Ee.length!==D.length||!Ee.every((Wt,nt)=>Wt===D[nt]),Yt=!bt&&Ee.some(Wt=>pe[Wt]!==k[Wt]),Zt=V.length!==Object.values(k).reduce((Wt,nt)=>Wt+nt,0);if(!bt&&!Yt&&!Zt||(D=Ee,k=pe,!re))return;let un=re.value;if(re.options[0].textContent="All events",bt){for(;re.options.length>1;)re.remove(1);for(let Wt of Ee){let nt=y("option","");nt.value=Wt,nt.textContent=`${Wt} (${pe[Wt]||0})`,re.appendChild(nt)}un&&Ee.includes(un)?re.value=un:un&&(re.value="",S="")}else for(let Wt=1;Wt<re.options.length;Wt++){let nt=re.options[Wt];nt.textContent=`${nt.value} (${pe[nt.value]||0})`}}function me(){let V=t.getAll();if(S&&(V=V.filter(pe=>pe.type===S)),W){let pe=W.toLowerCase();V=V.filter(Ee=>Ee.type.toLowerCase().includes(pe)||Ee.payload.toLowerCase().includes(pe))}return V}function fn(){return S!==""||W!==""}function Pt(){j=0,te=0,z.resume(),de.style.display="none"}function rn(V){he.has(V)?he.delete(V):he.add(V),ne=V;let pe=X.scrollTop,Ee=z.isFollowing();ke=!0,z.pause(),hn(),X.scrollTop=pe,Ee&&z.resume(),ke=!1}function yr(){return Uo(X,50)}function hn(){Pe=Date.now(),je=!1,ce(),Ae();let V=t.getEvictedCount();V>0?(Ne.textContent=`${V.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",P=me();let pe=P.length,Ee=t.getSize()>0;le&&(le.textContent=String(t.getSize())),pe===0&&Ee&&fn()?(Lt.textContent=W?`No events matching '${W}'`:"No events matching filter",Lt.style.display="",X.style.display="none"):(Lt.style.display="none",X.style.display=""),G&&(G.title=fn()?`Copy Filtered (${pe})`:"Copy All"),d&&!z.isFollowing()&&pe>j&&(te+=pe-j,ze.textContent=p?`${p}${te>0?` (${te})`:""}`:"",de.style.display=""),j=pe;let bt=t.getAll(),Yt=bt.length>0?bt[0].timestamp:0,Zt=new Set(P.map(nt=>nt.id));for(let nt of he)Zt.has(nt)||he.delete(nt);let un=S!==ae||W!==Q,Wt=Be.size===0&&P.length>0;if(un||Wt||P.length===0){X.innerHTML="",Be.clear();let nt=document.createDocumentFragment();for(let Rt=0;Rt<P.length;Rt++){let lt=Cl(P[Rt],Rt,Yt,m,he,rn,o,s);Be.set(P[Rt].id,lt),nt.appendChild(lt)}X.appendChild(nt),ae=S,Q=W,ne=null}else{if(ne!==null){let Rt=Be.get(ne);if(Rt&&Rt.parentNode===X){let lt=P.findIndex(Kt=>Kt.id===ne);if(lt>=0){let Kt=Cl(P[lt],lt,Yt,m,he,rn,o,s);X.insertBefore(Kt,Rt),Rt.remove(),Be.set(ne,Kt)}}ne=null}let nt=new Set(P.map(Rt=>Rt.id));for(let[Rt,lt]of Be)nt.has(Rt)||(lt.remove(),Be.delete(Rt));for(let Rt=0;Rt<P.length;Rt++){let lt=P[Rt];if(!Be.has(lt.id)){let Kt=Cl(lt,Rt,Yt,m,he,rn,o,s);Be.set(lt.id,Kt),X.appendChild(Kt)}}}z.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Ve(){if(Date.now()-Pe>=Qx){Se!==null&&(cancelAnimationFrame(Se),Se=null),hn();return}je||(je=!0,Se=requestAnimationFrame(()=>{Se=null,hn()}))}let T=(V,pe)=>{if(!G)return;G.innerHTML="";let Ee=xe(V,"12px","currentColor",1.5);Ee&&G.appendChild(Ee);let bt=y("span","persona-text-xs");bt.textContent="Copy All",G.appendChild(bt),setTimeout(()=>{G.innerHTML="";let Yt=xe("clipboard-copy","12px","currentColor",1.5);Yt&&G.appendChild(Yt);let Zt=y("span","persona-text-xs");Zt.textContent="Copy All",G.appendChild(Zt),G.disabled=!1},pe)},ue=async()=>{if(G){G.disabled=!0;try{let V;fn()?V=P:n?(V=await n(),V.length===0&&(V=t.getAll())):V=t.getAll();let pe=V.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(pe,null,2)),T("check",1500)}catch{T("x",1500)}}},Me=()=>{re&&(S=re.value,Pt(),hn())},Te=()=>{!ee||!qe||(qe.style.display=ee.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{W=ee.value,Pt(),hn()},150))},Ie=()=>{!ee||!qe||(ee.value="",W="",qe.style.display="none",B&&clearTimeout(B),Pt(),hn())},tt=()=>{if(ke)return;let V=X.scrollTop,{action:pe,nextLastScrollTop:Ee}=Ga({following:z.isFollowing(),currentScrollTop:V,lastScrollTop:Fe,nearBottom:yr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Fe=Ee,pe==="resume"?(z.resume(),te=0,de.style.display="none"):pe==="pause"&&(z.pause(),d&&(ze.textContent=p,de.style.display=""))},Je=V=>{let pe=Ja({following:z.isFollowing(),deltaY:V.deltaY,nearBottom:yr(),resumeWhenNearBottom:!0});pe==="pause"?(z.pause(),d&&(ze.textContent=p,de.style.display="")):pe==="resume"&&(z.resume(),te=0,de.style.display="none")},pt=()=>{d&&(X.scrollTop=X.scrollHeight,z.resume(),te=0,de.style.display="none")},It=V=>{let pe=V.target;if(!pe||pe.closest("button"))return;let Ee=pe.closest("[data-event-id]");if(!Ee)return;let bt=Ee.getAttribute("data-event-id");bt&&rn(bt)},U=V=>{if((V.metaKey||V.ctrlKey)&&V.key==="f"){V.preventDefault(),ee==null||ee.focus(),ee==null||ee.select();return}V.key==="Escape"&&(ee&&document.activeElement===ee?(Ie(),ee.blur(),M.focus()):r&&r())};G&&G.addEventListener("click",ue),re&&re.addEventListener("change",Me),ee&&ee.addEventListener("input",Te),qe&&qe.addEventListener("click",Ie),X.addEventListener("scroll",tt),X.addEventListener("wheel",Je,{passive:!0}),X.addEventListener("click",It),de.addEventListener("click",pt),M.addEventListener("keydown",U);function st(){B&&clearTimeout(B),Se!==null&&(cancelAnimationFrame(Se),Se=null),je=!1,Be.clear(),G&&G.removeEventListener("click",ue),re&&re.removeEventListener("change",Me),ee&&ee.removeEventListener("input",Te),qe&&qe.removeEventListener("click",Ie),X.removeEventListener("scroll",tt),X.removeEventListener("wheel",Je),X.removeEventListener("click",It),de.removeEventListener("click",pt),M.removeEventListener("keydown",U)}return{element:M,update:Ve,destroy:st}}}function og(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=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 c=document.createElement("div");c.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 m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(g)}else m.textContent=a;if(c.append(p,m),i.append(d,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var sg=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.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",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>og(e,t)});if(p)return p}return og(e,t)};var Sl=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)})}},bo=new Sl;bo.register("PersonaArtifactCard",sg);function av(e){var s;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((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function ag(e,t){var re,G,ee,qe;let n=(G=(re=e.features)==null?void 0:re.artifacts)==null?void 0:G.layout,s=((ee=n==null?void 0:n.toolbarPreset)!=null?ee:"default")==="document",o=(qe=n==null?void 0:n.panePadding)==null?void 0:qe.trim(),a=e.markdown?is(e.markdown):null,i=Ns(e.sanitize),d=J=>{let ie=a?a(J):qr(J);return i?i(ie):ie},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),s&&m.classList.add("persona-artifact-pane-document");let f=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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let v="rendered",E=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?qt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):qt({icon:"eye",label:"Rendered view"}),I=s?qt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):qt({icon:"code-2",label:"Source"}),N=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,S=n==null?void 0:n.documentToolbarCopyMenuItems,W=!!(P&&S&&S.length>0),B=null,D,k=null,j=null;if(s&&(M||P)&&!W){if(D=M?ti({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let J=xe("chevron-down",14,"currentColor",2);J&&D.appendChild(J)}}else s&&W?(B=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=M?ti({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=qt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),B.append(D,k)):s?D=qt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=qt({icon:"copy",label:"Copy"});let z=s?qt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):qt({icon:"refresh-cw",label:"Refresh"}),te=s?qt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):qt({icon:"x",label:"Close"}),Pe=()=>{var Xe,Ke,Ne;let J=(Xe=Be.find(ce=>ce.id===ae))!=null?Xe:Be[Be.length-1],ie=(Ke=J==null?void 0:J.id)!=null?Ke:null,Re=(J==null?void 0:J.artifactType)==="markdown"&&(Ne=J.markdown)!=null?Ne:"",ve=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Re,jsonPayload:ve,id:ie}},je=async()=>{var Xe;let{markdown:J,jsonPayload:ie}=Pe(),Re=(Xe=Be.find(Ke=>Ke.id===ae))!=null?Xe:Be[Be.length-1],ve=(Re==null?void 0:Re.artifactType)==="markdown"?J:Re?ie:"";try{await navigator.clipboard.writeText(ve)}catch{}};if(D.addEventListener("click",async()=>{let J=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(J&&W){let{markdown:ie,jsonPayload:Re,id:ve}=Pe();try{await J({actionId:"primary",artifactId:ve,markdown:ie,jsonPayload:Re})}catch{}return}await je()}),k&&(S!=null&&S.length)){let J=()=>{var Re;return(Re=m.closest("[data-persona-root]"))!=null?Re:document.body},ie=()=>{j=qo({items:S.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:ve,jsonPayload:Xe,id:Ke}=Pe(),Ne=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ne?await Ne({actionId:Re,artifactId:Ke,markdown:ve,jsonPayload:Xe}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(ve):Re==="json"||Re==="source"?await navigator.clipboard.writeText(Xe):await navigator.clipboard.writeText(ve||Xe)}catch{}},anchor:B!=null?B:k,position:"bottom-right",portal:J()})};m.isConnected?ie():requestAnimationFrame(ie),k.addEventListener("click",Re=>{Re.stopPropagation(),j==null||j.toggle()})}z.addEventListener("click",async()=>{var J;try{await((J=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:J.call(n))}catch{}ne()}),te.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let Se=()=>{s&&(C.setAttribute("aria-pressed",v==="rendered"?"true":"false"),I.setAttribute("aria-pressed",v==="source"?"true":"false"))};C.addEventListener("click",()=>{v="rendered",Se(),ne()}),I.addEventListener("click",()=>{v="source",Se(),ne()});let ke=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");s?(f.replaceChildren(),E.append(C,I),B?N.append(B,z,te):N.append(D,z,te),f.append(E,ke,N),Se()):(f.appendChild(g),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Fe=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"),he=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Fe.style.paddingLeft=o,Fe.style.paddingRight=o,he.style.padding=o),m.appendChild(f),m.appendChild(Fe),m.appendChild(he);let Be=[],ae=null,Q=!1,ne=()=>{var ve,Xe,Ke,Ne;let J=s&&Be.length<=1;Fe.classList.toggle("persona-hidden",J),Fe.replaceChildren();for(let ce of Be){let et=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");et.type="button",et.textContent=ce.title||ce.id.slice(0,8),ce.id===ae&&et.classList.add("persona-bg-persona-container","persona-border-persona-border"),et.addEventListener("click",()=>t.onSelect(ce.id)),Fe.appendChild(et)}he.replaceChildren();let ie=ae&&Be.find(ce=>ce.id===ae)||Be[Be.length-1];if(!ie)return;if(s){let ce=ie.artifactType==="markdown"?"MD":(ve=ie.component)!=null?ve:"Component",X=(ie.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ke.textContent=`${X} \xB7 ${ce}`}else g.textContent="Artifacts";if(ie.artifactType==="markdown"){if(s&&v==="source"){let et=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");et.textContent=(Xe=ie.markdown)!=null?Xe:"",he.appendChild(et);return}let ce=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ce.innerHTML=d((Ke=ie.markdown)!=null?Ke:""),he.appendChild(ce);return}let Re=ie.component?bo.get(ie.component):void 0;if(Re){let et={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=Re((Ne=ie.props)!=null?Ne:{},et);if(X){he.appendChild(X);return}}catch{}}he.appendChild(av(ie))},le=()=>{var ie;let J=Be.length>0;if(m.classList.toggle("persona-hidden",!J),c){let Re=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Xe=((ie=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ie:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&Xe&&Q?(c.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:c,update(J){var ie,Re,ve;Be=J.artifacts,ae=(ve=(Re=J.selectedId)!=null?Re:(ie=J.artifacts[J.artifacts.length-1])==null?void 0:ie.id)!=null?ve:null,Be.length>0&&(Q=!0),ne(),le()},setMobileOpen(J){Q=J,!J&&c?(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):le()}}}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 ig(e,t){var o,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=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(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)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function iv(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 ui(e,t){var d,c,p,m,f,g,x,v,E,C;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"),iv(e),ig(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.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",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"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=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):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=(C=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:C.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ig(e,t)}var lg=["panel","seamless"];function mi(e,t){var i,d,c,p,m,f;for(let g of lg)e.classList.remove(`persona-artifact-appearance-${g}`);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=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",s=lg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.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 g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function cg(e,t){var n,r,s;return!t||!ir(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function lv(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 cv(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 pv(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function dg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function pg(e,t,n,r,s,o){let a=lv(s,200),i=pv(t,n,r,200);i=Math.max(a,i);let d=cv(o);return d!==null&&(i=Math.min(i,d)),dv(e,a,i)}var ug={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"}},Al=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,v,E;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(v=ug[a])!=null?v:ug.init;o.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let C=y("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,d.appendChild(C)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var S,W;let I=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${C.name}`;let N=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");N.textContent=C.label,I.appendChild(N);let M=(S=C.type)!=null?S:"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}-${C.name}`,P.name=C.name,P.placeholder=(W=C.placeholder)!=null?W:"",C.required&&(P.required=!0),I.appendChild(P),p.appendChild(I)});let m=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=(E=i.submitLabel)!=null?E:"Submit",m.appendChild(f),m.appendChild(g),p.appendChild(m),o.replaceChildren(d,p),p.addEventListener("submit",async C=>{var P,S;C.preventDefault();let I=(P=n.formEndpoint)!=null?P:"/form",N=new FormData(p),M={};N.forEach((W,B)=>{M[B]=W}),M.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let W=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let B=await W.json();f.textContent=(S=B.message)!=null?S:"Thanks! We'll be in touch soon.",B.success&&B.nextPrompt&&await r.sendMessage(String(B.nextPrompt))}catch(W){f.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Tl=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,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},gi=new Tl;var mg=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var uv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},mv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},fi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=uv(e),n=mv(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},El=e=>typeof e=="string"?e:e==null?"":String(e),Cs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:El(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=El(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:El(n.text)}}},gg=e=>Array.isArray(e)?e.map(t=>String(t)):[],hi=e=>{let t=new Set(gg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(gg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.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((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},m=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let f=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:f,resubmit:m.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var gv=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}},fv=e=>e.map(t=>({...t,streaming:!1})),hv=e=>e.map(t=>({...t,status:"complete"})),Ml=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?gv(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?fv(n.messages):void 0,artifacts:n.artifacts?hv(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},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 yv,STR as bv,OBJ as xv}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 wv(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 kl(){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 s=yv(n,bv|xv),o=wv(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Cv(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ll(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=bo.get(e.component);if(!o)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=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Sv(){let e=kl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function fg(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 Pl(e){let t=fg(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 Il(e){let t=fg(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 Av=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Av}=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 m=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,g.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,g.appendChild(v),f.appendChild(g);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 C=[];for(let S=1;S<=5;S++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),W.title=c[S-1],W.dataset.rating=String(S),W.innerHTML=`
27
+ `,n.addEventListener("click",t);let r=s=>{var M,E,L,C,R,F,j,W,O,N,Z,Ae,de;let a=(M=s.launcher)!=null?M:{},i=pn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(E=a.title)!=null?E:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ee=(L=a.subtitle)!=null?L:"Here to help you get answers fast";l.textContent=ee,l.setAttribute("title",ee)}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 ee=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=ee,u.style.width=ee,u.innerHTML="",a.agentIconName){let xe=parseFloat(ee)||24,Te=me(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Te?(u.appendChild(Te),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 f=n.querySelector("[data-role='launcher-image']");if(f){let ee=(j=a.agentIconSize)!=null?j:"40px";f.style.height=ee,f.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ee=(W=a.callToActionIconSize)!=null?W:"32px";g.style.height=ee,g.style.width=ee,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Te=parseFloat(ee)||24,ne=Math.max(Te-xe,8),be=me(a.callToActionIconName,ne,"currentColor",2);be?g.appendChild(be):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.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",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?T:`${x} ${v}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:Sn));let S="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Ae=a.border)!=null?Ae:S,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:k,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 Jm=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Km(e),s=Gm(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:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{l.footer.replaceWith(f),l.footer=f}}},yl=({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:()=>hl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=hl(e,n);return{instance:o,element:o.element}};var Rx=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}},Wx=(e,t)=>{if(!e)return null;let n=Rx(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Hx=(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},Bx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bl=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(":"))},xl=320,Xm=320,Dx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Nx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ox=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Fx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),_x=(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=`${xl}px`,l.style.maxHeight=`${Xm}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}),Bx(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}},$x=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(!bl(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=`${xl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jx=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(!bl(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=`${xl}px`,o.style.maxHeight=`${Xm}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}},Ux=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(!bl(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}},As=()=>{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},Ym=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:As};if(t){let o=t(r);if(o!==null)return o}return As()},qx=(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},Qm=(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},zx=(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},Zm=(e,t,n)=>{var v,x,T,S,k,M,E;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(T=t.showDownvote)!=null?T:!0,a=(S=t.showReadAloud)!=null?S:!1;if(!r&&!o&&!s&&!a){let L=y("div");return L.style.display="none",L.id=`actions-${e.id}`,L.setAttribute("data-actions-for",e.id),L}let i=(k=t.visibility)!=null?k:"hover",d=(M=t.align)!=null?M:"right",l=(E=t.layout)!=null?E:"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],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(L,C,R)=>{let F=Jt({icon:L,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",R),F};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),o&&f.appendChild(g("thumbs-up","Upvote","upvote")),s&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},ga=(e,t,n,r,o,s)=>{var le,oe,re,We,Oe,K,G,ve,X,ie,Re,ge,Ge,nt,Pt,Ye,_e;let a=n!=null?n:{},i=(le=a.layout)!=null?le:"bubble",d=a.avatar,l=a.timestamp,p=(oe=d==null?void 0:d.show)!=null?oe:!1,u=(re=l==null?void 0:l.show)!=null?re:!1,f=(We=d==null?void 0:d.position)!=null?We:"left",g=(Oe=l==null?void 0:l.position)!=null?Oe:"below",v=zx(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 T=Dx(e),S=(G=(K=e.content)==null?void 0:K.trim())!=null?G:"",M=T.length>0&&S===_a,E=Za((X=(ve=s==null?void 0:s.widgetConfig)==null?void 0:ve.features)==null?void 0:X.streamAnimation),L=(ge=(Re=(ie=s==null?void 0:s.widgetConfig)==null?void 0:ie.features)==null?void 0:Re.streamAnimation)==null?void 0:ge.plugins,C=e.role==="assistant"&&E.type!=="none"?ia(E.type,L):null,R=e.role==="assistant"&&((Ge=C==null?void 0:C.isAnimating)==null?void 0:Ge.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",`${E.speed}ms`),j.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let W=F?ei((nt=e.content)!=null?nt:"",E.buffer,C,e,!!e.streaming):(Pt=e.content)!=null?Pt:"",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 Z=null;if(M?(Z=document.createElement("div"),Z.innerHTML=N,Z.style.display="none",j.appendChild(Z)):j.innerHTML=N,F&&(C!=null&&C.useCaret)&&!M&&S){let J=ti(),Ve=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=Ve[Ve.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(J,ze.nextSibling);else{let we=j.lastElementChild;we?we.appendChild(J):j.appendChild(J)}}if(u&&g==="inline"&&e.createdAt){let J=Qm(e,l,"span");J.classList.add("persona-timestamp-inline");let Ve=j.lastElementChild;Ve?Ve.appendChild(J):j.appendChild(J)}if(T.length>0){let J=_x(T,!M&&!!S,()=>{M&&Z&&(Z.style.display="")});J?x.appendChild(J):M&&Z&&(Z.style.display="")}let Ae=Nx(e);if(Ae.length>0){let J=$x(Ae);J&&x.appendChild(J)}let de=Ox(e);if(de.length>0){let J=jx(de);J&&x.appendChild(J)}let ee=Fx(e);if(ee.length>0){let J=Ux(ee);J&&x.appendChild(J)}if(x.appendChild(j),u&&g==="below"&&e.createdAt){let J=Qm(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let xe=e.role==="assistant"?Wx(e.stopReason,(_e=(Ye=s==null?void 0:s.widgetConfig)==null?void 0:Ye.copy)==null?void 0:_e.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(W&&W.trim()),Ve=E.placeholder==="skeleton",ze=Ve&&E.buffer==="line"&&J;if(J)ze&&x.appendChild(ca());else if(Ve)x.appendChild(ca());else{let we=Ym("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);we&&x.appendChild(we)}}if(xe&&e.stopReason&&!e.streaming&&(S||(j.style.display="none"),x.appendChild(Hx(e.stopReason,xe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Zm(e,r,o);x.appendChild(J)}if(!p||e.role==="system")return x;let ne=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),be=qx(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ne.append(x,be):ne.append(be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ne},Vx=(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 Ss=new Set,Kx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Gx=(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
+ `):""},eg=(e,t)=>{let n=Ss.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")},vl=(e,t)=>{var de,ee,xe,Te,ne,be,le,oe,re,We,Oe;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=(ee=(de=t==null?void 0:t.features)==null?void 0:de.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&Ss.has(e.id),i=n.status!=="complete",d=Gx(e,(xe=o.previewMaxLines)!=null?xe: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"),f="Thinking...",g=(Te=t==null?void 0:t.reasoning)!=null?Te:{},v=String((ne=n.startedAt)!=null?ne:Date.now()),x=()=>{let K=y("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Na(n),K},T=(be=g.renderCollapsedSummary)==null?void 0:be.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Na(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(u.textContent=T,p.appendChild(u)):T instanceof HTMLElement?p.appendChild(T):(u.textContent=f,p.appendChild(u));let S=y("span","persona-text-xs persona-text-persona-primary");S.textContent=nm(n),p.appendChild(S);let k=(le=o.loadingAnimation)!=null?le:"none",M=g.activeTextTemplate,E=g.completeTextTemplate,L=i?M:E,C=T instanceof HTMLElement,R=(K,G,ve)=>{let X=ve;for(let ie of G){let Re=y("span","persona-tool-char");Re.style.setProperty("--char-index",String(X)),Re.textContent=ie===" "?"\xA0":ie,K.appendChild(Re),X++}return X},F=(K,G)=>{u.textContent="";let ve=Oa(K,""),X=0;for(let ie of ve){let Re=ie.styles.length>0?(()=>{let ge=y("span",ie.styles.map(Ge=>`persona-tool-text-${Ge}`).join(" "));return u.appendChild(ge),ge})():u;if(ie.isDuration&&i)Re.appendChild(x());else{let ge=ie.isDuration?Na(n):ie.text;G?X=R(Re,ge,X):Re.appendChild(document.createTextNode(ge))}}};if(!C&&L)if(S.style.display="none",u.style.display="",i&&k!=="none"){let K=(oe=g.loadingAnimationDuration)!=null?oe:2e3;u.setAttribute("data-preserve-animation","true"),k==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),F(L,!1)):(u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),F(L,!0))}else F(L,!1);else if(!C&&i&&k!=="none"){u.style.display="";let K=(re=g.loadingAnimationDuration)!=null?re:2e3;if(u.setAttribute("data-preserve-animation","true"),k==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${K}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let G=u.textContent||f;u.textContent="",R(u,G,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 G=me(a?"chevron-up":"chevron-down",16,"currentColor",2);G?j.appendChild(G):j.textContent=a?"Hide":"Show";let ve=y("div","persona-flex persona-items-center persona-ml-auto");ve.append(j),l.append(p,ve)}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 K=(Oe=(We=t==null?void 0:t.reasoning)==null?void 0:We.renderCollapsedPreview)==null?void 0:Oe.call(We,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Kx(W,K)||(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(""),Z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Z),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let G=me(a?"chevron-up":"chevron-down",16,"currentColor",2);G?j.appendChild(G):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 Es=new Set,Jx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Qx=(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=yo(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
+ `):""},wl=(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)"},Xx=(e,t)=>{var p,u,f,g,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=Qx(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?rm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},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=Gi(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Gi(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},tg=(e,t,n)=>{var p;let r=Es.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)",f=me(r?"chevron-up":"chevron-down",16,u,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Cl=(e,t)=>{var N,Z,Ae,de,ee,xe,Te,ne,be;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=(Ae=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?Ae:{},a=s.expandable!==!1,i=a&&Es.has(e.id),{summary:d,previewText:l,isActive:p}=Xx(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 f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.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},T=(xe=r.renderCollapsedSummary)==null?void 0:xe.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Js(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(g.textContent=T,f.appendChild(g)):T instanceof HTMLElement?f.appendChild(T):(g.textContent=d,f.appendChild(g));let S=(Te=s.loadingAnimation)!=null?Te:"none",k=r.activeTextTemplate,M=r.completeTextTemplate,E=p?k:M,L=T instanceof HTMLElement,C=(le,oe,re)=>{let We=re;for(let Oe of oe){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(We)),K.textContent=Oe===" "?"\xA0":Oe,le.appendChild(K),We++}return We},R=(le,oe)=>{var K;g.textContent="";let re=((K=n.name)==null?void 0:K.trim())||"tool",We=Oa(le,re),Oe=0;for(let G of We){let ve=G.styles.length>0?(()=>{let X=y("span",G.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return g.appendChild(X),X})():g;if(G.isDuration&&p)ve.appendChild(x());else{let X=G.isDuration?Js(n):G.text;oe?Oe=C(ve,X,Oe):ve.appendChild(document.createTextNode(X))}}};if(!L)if(p&&S!=="none"){let le=(ne=r.loadingAnimationDuration)!=null?ne:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${le}ms`),E&&R(E,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${le}ms`),S==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),E)R(E,!0);else{let oe=g.textContent||d;g.textContent="",C(g,oe,0)}}else E&&R(E,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let le=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",oe=me(i?"chevron-up":"chevron-down",16,le,2);oe?F.appendChild(oe):F.textContent=i?"Hide":"Show";let re=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");re.append(F),u.append(f,re)}else u.append(f);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=(be=r.renderCollapsedPreview)==null?void 0:be.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Jx(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"),oe=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Arguments";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",wl(re,r),re.textContent=yo(n.args),le.append(oe,re),W.appendChild(le)}if(n.chunks&&n.chunks.length){let le=y("div","persona-space-y-1"),oe=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Activity";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",wl(re,r),re.textContent=n.chunks.join(""),le.append(oe,re),W.appendChild(le)}if(n.status==="complete"&&n.result!==void 0){let le=y("div","persona-space-y-1"),oe=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Result";let re=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");re.style.fontSize="0.75rem",re.style.lineHeight="1rem",wl(re,r),re.textContent=yo(n.result),le.append(oe,re),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)",oe=me(i?"chevron-up":"chevron-down",16,le,2);oe?F.appendChild(oe):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 Go=new Map,ui=e=>{let n=(e.startsWith(Wr)?e.slice(Wr.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)},ng=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,rg=(e,t)=>{var r,o,s;let n=(o=(r=ng(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Go.get(e))!=null?s:n==="expanded"},og=(e,t,n)=>{var a,i;let r=ng(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)}},sg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=rg(e,n);og(r,s,n),o.style.display=s?"":"none"};var mi=(e,t)=>{var R,F,j,W,O,N,Z,Ae,de,ee,xe,Te,ne,be,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"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(W=r==null?void 0:r.title)!=null?W:"Approval Required",f.appendChild(g),!o){let oe=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");oe.setAttribute("data-approval-status",n.status),n.status==="approved"?(oe.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",oe.style.color="var(--persona-palette-colors-success-700, #15803d)",oe.textContent="Approved"):n.status==="denied"?(oe.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",oe.style.color="var(--persona-palette-colors-error-700, #b91c1c)",oe.textContent="Denied"):n.status==="timeout"&&(oe.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",oe.style.color="var(--persona-palette-colors-warning-700, #b45309)",oe.textContent="Timeout"),f.appendChild(oe)}u.appendChild(f);let x=n.toolType==="webmcp"||n.toolName.startsWith(Wr)?Us(n.toolName):void 0,T=(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}:{}}),S=!n.toolName,k=T||(S?n.description:`The assistant wants to use \u201C${x!=null?x:ui(n.toolName)}\u201D.`),M=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(M.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(M.style.color=r.descriptionColor),M.textContent=k,u.appendChild(M),n.reason){let oe=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");oe.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?oe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(oe.style.color=r.descriptionColor);let re=y("span","persona-font-medium");re.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,oe.appendChild(re),oe.appendChild(document.createTextNode(n.reason)),u.appendChild(oe)}let E=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",L=!!n.description&&!S,C=L||!!n.parameters;if(E!=="hidden"&&C){let oe=rg(e.id,t),re=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");re.type="button",re.setAttribute("data-expand-header","true"),re.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let We=y("span");We.setAttribute("data-approval-details-label","true");let Oe=y("span","persona-inline-flex persona-items-center");Oe.setAttribute("data-approval-details-chevron","true"),re.append(We,Oe),og(re,oe,t),u.appendChild(re);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=oe?"":"none",L){let G=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(G.style.color=r.descriptionColor),G.textContent=n.description,K.appendChild(G)}if(n.parameters){let G=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(G.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(G.style.color=r.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=yo(n.parameters),K.appendChild(G)}u.appendChild(K)}if(o){let oe=y("div","persona-flex persona-gap-2 persona-mt-2");oe.setAttribute("data-approval-buttons","true");let re=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");re.type="button",re.style.backgroundColor=(Ae=r==null?void 0:r.approveButtonColor)!=null?Ae:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",re.setAttribute("data-approval-action","approve");let We=me("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);We&&(We.style.marginRight="4px",re.appendChild(We));let Oe=document.createTextNode((xe=r==null?void 0:r.approveLabel)!=null?xe:"Approve");re.appendChild(Oe);let K=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");K.type="button",K.style.backgroundColor=(Te=r==null?void 0:r.denyButtonColor)!=null?Te:"transparent",K.style.color=(ne=r==null?void 0:r.denyButtonTextColor)!=null?ne:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let G=me("shield-x",14,(be=r==null?void 0:r.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",K.appendChild(G));let ve=document.createTextNode((le=r==null?void 0:r.denyLabel)!=null?le:"Deny");K.appendChild(ve),oe.append(re,K),u.appendChild(oe)}return a.append(i,u),s.appendChild(a),s};function Yx(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 ag(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:Yx(t),p=!1,u=null,f=()=>{if(!p)return;let T=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${T.width}px`);let S=r==="top-start"||r==="top-end"?T.top-o-n.getBoundingClientRect().height:T.bottom+o,k=r==="bottom-end"||r==="top-end"?T.right-n.getBoundingClientRect().width:T.left;n.style.top=`${S}px`,n.style.left=`${k}px`},g=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},v=()=>{var L,C,R;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),l.appendChild(n),f();let T=(C=((L=t.ownerDocument)!=null?L:document).defaultView)!=null?C:window,S=(R=t.ownerDocument)!=null?R:document,k=()=>{if(!t.isConnected){g(),d==null||d("anchor-removed");return}f()},M=F=>{let j=typeof F.composedPath=="function"?F.composedPath():[];j.includes(n)||j.includes(t)||(g(),d==null||d("outside"))},E=T.setTimeout(()=>{S.addEventListener("pointerdown",M,!0)},0);T.addEventListener("scroll",k,!0),T.addEventListener("resize",k),u=()=>{T.clearTimeout(E),S.removeEventListener("pointerdown",M,!0),T.removeEventListener("scroll",k,!0),T.removeEventListener("resize",k)},i==null||i()};return{get isOpen(){return p},open:v,close:g,toggle:()=>p?g():v(),reposition:f,destroy:g}}function ig(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Zx=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),lg=(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))},Jo=(e,t)=>{lg(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)},ev=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,tv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=Go.get(e))!=null?o:n==="expanded"},Al=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},nv=(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(Wr)?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:ui(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},rv=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?ui(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},ov=(e,t,n,r,o,s,a)=>{var F,j,W,O,N,Z,Ae;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,f=u&&tv(t.id,r),g=(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",f?"true":"false"),x.setAttribute("aria-label",f?v:g)):x.setAttribute("data-static","true");let T=y("span","persona-approval-logo"),S=me("shield-check",16,"currentColor",2);S&&T.appendChild(S),x.appendChild(T);let k=nv(n,r);if(u){let de=y("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let ee=me("chevron-down",14,"currentColor",2);ee&&de.appendChild(ee),k.append(" "),k.appendChild(de)}x.appendChild(k),i.appendChild(x);let M=y("div","persona-approval-body");if(u){let de=y("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!f,l){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,de.appendChild(ee)}if(p){let ee=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=yo(n.parameters),de.appendChild(ee)}M.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 ee=y("span","persona-approval-reason-label");ee.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,de.append(ee,document.createTextNode(n.reason)),M.appendChild(de)}let E=y("div","persona-approval-actions"),L=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"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Al("\u23CE"));let xe=y("button","persona-approval-caret");xe.type="button",xe.setAttribute("data-action","toggle-menu"),xe.setAttribute("aria-label","More options"),C(xe);let Te=me("chevron-down",15,"currentColor",2);Te&&xe.appendChild(Te),de.append(ee,xe),E.append(de,R),R.append(Al("Esc"));let ne=y("div","persona-approval-menu"),be=y("button","persona-approval-menu-item");be.type="button",be.append("Allow once",Al("\u2318\u23CE")),ne.appendChild(be),L=ag({anchor:de,content:ne,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,L),be.addEventListener("click",()=>{Jo(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((Ae=r==null?void 0:r.approveLabel)!=null?Ae:"Allow"),E.append(de,R)}return M.appendChild(E),i.appendChild(M),i.addEventListener("click",de=>{let ee=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!ee)return;let xe=ee.getAttribute("data-action");if(xe==="toggle-params"){let Te=i.querySelector('[data-role="params"]');if(Te){let ne=Te.hidden;Te.hidden=!ne,x.setAttribute("aria-expanded",ne?"true":"false"),x.setAttribute("aria-label",ne?v:g),Go.set(t.id,ne)}return}if(xe==="toggle-menu"){L==null||L.toggle();return}if(xe==="always"){Jo(e,t.id),o({remember:!0});return}if(xe==="allow"){Jo(e,t.id),o();return}if(xe==="deny"){Jo(e,t.id),s();return}}),i},cg=()=>{let e=Zx();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=ev(a);if(i.status!=="pending"){if(Jo(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return rv(i)}lg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=ov(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=f=>{ig(f)||r.id===e.latestPendingApprovalId&&(f.key!=="Escape"&&f.key!=="Enter"||(f.preventDefault(),f.stopImmediatePropagation(),Jo(e,r.id),f.key==="Escape"?s():f.metaKey||f.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()])Jo(e,r);e.latestPendingApprovalId=null}}};var dg=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(T=>T.role==="user"))return;let u=document.createDocumentFragment(),f=s?s.isStreaming():!1,g=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=f,d!=null&&d.fontFamily&&(x.style.fontFamily=g(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 sv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),av=new Set(["step_start","execution_start"]),iv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),lv=new Set(["step_complete","agent_turn_complete"]),cv=new Set(["flow_complete","agent_complete"]),pg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),mg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Qo=(e,t)=>{let n=e[t];return mg(n)?n:void 0};function Sl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function gi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function dv(e,t){return typeof t.type=="string"?t.type:e}function pv(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 uv(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 ug(e){var r,o,s,a,i;let t=Qo(e,"result"),n=[Qo(e,"tokens"),Qo(e,"totalTokens"),t?Qo(t,"tokens"):void 0,Qo(e,"usage"),t?Qo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?o:Qn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Qn(e.outputTokens))!=null?s:Qn(e.completionTokens))!=null?i:t?(a=Qn(t.outputTokens))!=null?a:Qn(t.completionTokens):void 0}function mv(e){var n,r,o,s,a;let t=Qo(e,"result");return(a=(o=(r=(n=Qn(e.executionTime))!=null?n:Qn(e.executionTimeMs))!=null?r:Qn(e.execution_time))!=null?o:Qn(e.duration))!=null?a:t?(s=Qn(t.executionTime))!=null?s:Qn(t.executionTimeMs):void 0}function gv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ya=class{constructor(t=gv){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:gi(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(!mg(n)){pg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=dv(t,n),o=this.now();if(sv.has(r)){this.startRun(o);return}if(av.has(r)){this.run||this.startRun(o);return}if(iv.has(r)){if(!uv(r,n))return;let a=pv(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+Sl(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:gi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(lv.has(r)){if(!this.run)return;let a=this.run,i=ug(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Sl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:gi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(cv.has(r)){if(!this.run)return;let a=this.run,i=ug(n),d=i!=null?i:a.exactOutputTokens+Sl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:gi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(pg.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=mv(n);return s!=null?s:r-t.startedAt}};function Ts(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var fv={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)"}},hv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},yv=["flowName","stepName","reasoningText","text","name","tool","toolName"],bv=100;function xv(e,t){let n={...fv,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return hv}function vv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function wv(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 Cv(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 Av(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 Sv(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 Ev(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Tv(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 Mv(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 f;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ts(l,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(u()),l;function u(){var N,Z;let g=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"),T=me(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&x.appendChild(T);let S=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(N=r.timestampFormat)!=null?N:"relative";S.textContent=k==="relative"?vv(e.timestamp,n):wv(e.timestamp);let M=null;r.showSequenceNumbers!==!1&&(M=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let E=xv(e.type,r.badgeColors),L=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");L.style.backgroundColor=E.bg,L.style.color=E.text,L.style.borderColor=E.text+"50",L.textContent=e.type;let C=(Z=r.descriptionFields)!=null?Z:yv,R=Cv(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 Ae=>{Ae.stopPropagation(),await Av(Sv(e)),W.innerHTML="";let de=me("check","12px","currentColor",1.5);de&&W.appendChild(de),setTimeout(()=>{W.innerHTML="";let ee=me("clipboard","12px","currentColor",1.5);ee&&W.appendChild(ee)},1500)}),v.appendChild(x),v.appendChild(S),M&&v.appendChild(M),v.appendChild(L),F&&v.appendChild(F),v.appendChild(j),v.appendChild(W),g.appendChild(v),d&&g.appendChild(Mv(e,a,i)),g}}function gg(e){var v,x,T,S,k;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=(T=i==null?void 0:i.label)!=null?T:"",u=(k=(S=o==null?void 0:o.features)==null?void 0:S.eventStream)!=null?k:{},f=s.find(M=>M.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let M=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return g();function g(){let M=u.classNames,E=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ts(E,M==null?void 0:M.panel);let L=[],C="",R="",F=null,j=[],W={},O=0,N=Qa(),Z=0,Ae=0,de=!1,ee=null,xe=!1,Te=0,ne=new Set,be=new Map,le="",oe="",re=null,We,Oe,K,G,ve,X=null,ie=null,Re=null;function ge(){let P=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ce=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");Ts(ce,M==null?void 0:M.headerBar);let Me=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Me.textContent="Events",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"),We.textContent="0",a){ie=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ie.style.cursor="help";let $t=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");$t.textContent="Throughput",X=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),X.textContent="-- tok/s",Re=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"),Re.style.display="none",Re.style.pointerEvents="none";let On=ie,En=Re,Tn=()=>{if(!En.textContent)return;let Mn=On.getBoundingClientRect(),cr=P.getBoundingClientRect();En.style.left=`${Mn.left-cr.left}px`,En.style.top=`${Mn.bottom-cr.top+4}px`,En.style.display="block"},xn=()=>{En.style.display="none"};ie.addEventListener("mouseenter",Tn),ie.addEventListener("mouseleave",xn),ie.appendChild($t),ie.appendChild(X)}let Et=y("div","persona-flex-1");Oe=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 et=y("option","");et.value="",et.textContent="All events",Oe.appendChild(et),K=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"),K.type="button",K.title="Copy All";let bn=me("clipboard-copy","12px","currentColor",1.5);bn&&K.appendChild(bn);let bt=y("span","persona-text-xs");bt.textContent="Copy All",K.appendChild(bt),ce.appendChild(Me),ce.appendChild(We),ie&&ce.appendChild(ie),ce.appendChild(Et),ce.appendChild(Oe),ce.appendChild(K);let xt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ts(xt,M==null?void 0:M.searchBar);let Wt=me("search","14px","var(--persona-muted, #9ca3af)",1.5),vt=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");Wt&&vt.appendChild(Wt),G=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ts(G,M==null?void 0:M.searchInput),G.type="text",G.placeholder="Search event payloads...",ve=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"),ve.type="button",ve.style.display="none";let mn=me("x","12px","currentColor",2);return mn&&ve.appendChild(mn),xt.appendChild(vt),xt.appendChild(G),xt.appendChild(ve),P.appendChild(ce),P.appendChild(xt),Re&&P.appendChild(Re),P}let Ge,nt=s.find(P=>P.renderEventStreamToolbar);if(nt!=null&&nt.renderEventStreamToolbar&&o){let P=nt.renderEventStreamToolbar({config:o,defaultRenderer:()=>ge(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ce=>{C=ce,$e(),Yt()},onSearchChange:ce=>{R=ce,$e(),Yt()}});Ge=P!=null?P:ge()}else Ge=ge();let Pt=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");Pt.style.display="none";function Ye(){if(!a||!X||!ie)return;let P=a();X.textContent=Ev(P);let ce=Tv(P);Re&&(Re.textContent=ce,ce||(Re.style.display="none")),ce?ie.setAttribute("aria-label",ce):ie.removeAttribute("aria-label")}let _e=y("div","persona-flex-1 persona-min-h-0 persona-relative"),J=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let Ve=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(Ve,M==null?void 0:M.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let ze=me(l,"14px","currentColor",2);ze&&Ve.appendChild(ze);let we=y("span","");we.textContent=p,Ve.appendChild(we);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",_e.appendChild(J),_e.appendChild(Se),_e.appendChild(Ve),E.setAttribute("tabindex","0"),E.appendChild(Ge),E.appendChild(Pt),E.appendChild(_e);function Ze(){let P=t.getAll(),ce={};for(let bt of P)ce[bt.type]=(ce[bt.type]||0)+1;let Me=Object.keys(ce).sort(),Et=Me.length!==j.length||!Me.every((bt,xt)=>bt===j[xt]),et=!Et&&Me.some(bt=>ce[bt]!==W[bt]),Ut=P.length!==Object.values(W).reduce((bt,xt)=>bt+xt,0);if(!Et&&!et&&!Ut||(j=Me,W=ce,!Oe))return;let bn=Oe.value;if(Oe.options[0].textContent="All events",Et){for(;Oe.options.length>1;)Oe.remove(1);for(let bt of Me){let xt=y("option","");xt.value=bt,xt.textContent=`${bt} (${ce[bt]||0})`,Oe.appendChild(xt)}bn&&Me.includes(bn)?Oe.value=bn:bn&&(Oe.value="",C="")}else for(let bt=1;bt<Oe.options.length;bt++){let xt=Oe.options[bt];xt.textContent=`${xt.value} (${ce[xt.value]||0})`}}function Qe(){let P=t.getAll();if(C&&(P=P.filter(ce=>ce.type===C)),R){let ce=R.toLowerCase();P=P.filter(Me=>Me.type.toLowerCase().includes(ce)||Me.payload.toLowerCase().includes(ce))}return P}function Ee(){return C!==""||R!==""}function $e(){O=0,Z=0,N.resume(),Ve.style.display="none"}function un(P){ne.has(P)?ne.delete(P):ne.add(P),re=P;let ce=J.scrollTop,Me=N.isFollowing();xe=!0,N.pause(),Yt(),J.scrollTop=ce,Me&&N.resume(),xe=!1}function Dt(){return Vo(J,50)}function Yt(){Ae=Date.now(),de=!1,Ye(),Ze();let P=t.getEvictedCount();P>0?(Pt.textContent=`${P.toLocaleString()} older events truncated`,Pt.style.display=""):Pt.style.display="none",L=Qe();let ce=L.length,Me=t.getSize()>0;We&&(We.textContent=String(t.getSize())),ce===0&&Me&&Ee()?(Se.textContent=R?`No events matching '${R}'`:"No events matching filter",Se.style.display="",J.style.display="none"):(Se.style.display="none",J.style.display=""),K&&(K.title=Ee()?`Copy Filtered (${ce})`:"Copy All"),d&&!N.isFollowing()&&ce>O&&(Z+=ce-O,we.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",Ve.style.display=""),O=ce;let Et=t.getAll(),et=Et.length>0?Et[0].timestamp:0,Ut=new Set(L.map(xt=>xt.id));for(let xt of ne)Ut.has(xt)||ne.delete(xt);let bn=C!==le||R!==oe,bt=be.size===0&&L.length>0;if(bn||bt||L.length===0){J.innerHTML="",be.clear();let xt=document.createDocumentFragment();for(let Wt=0;Wt<L.length;Wt++){let vt=El(L[Wt],Wt,et,u,ne,un,s,o);be.set(L[Wt].id,vt),xt.appendChild(vt)}J.appendChild(xt),le=C,oe=R,re=null}else{if(re!==null){let Wt=be.get(re);if(Wt&&Wt.parentNode===J){let vt=L.findIndex(mn=>mn.id===re);if(vt>=0){let mn=El(L[vt],vt,et,u,ne,un,s,o);J.insertBefore(mn,Wt),Wt.remove(),be.set(re,mn)}}re=null}let xt=new Set(L.map(Wt=>Wt.id));for(let[Wt,vt]of be)xt.has(Wt)||(vt.remove(),be.delete(Wt));for(let Wt=0;Wt<L.length;Wt++){let vt=L[Wt];if(!be.has(vt.id)){let mn=El(vt,Wt,et,u,ne,un,s,o);be.set(vt.id,mn),J.appendChild(mn)}}}N.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Nr(){if(Date.now()-Ae>=bv){ee!==null&&(cancelAnimationFrame(ee),ee=null),Yt();return}de||(de=!0,ee=requestAnimationFrame(()=>{ee=null,Yt()}))}let H=(P,ce)=>{if(!K)return;K.innerHTML="";let Me=me(P,"12px","currentColor",1.5);Me&&K.appendChild(Me);let Et=y("span","persona-text-xs");Et.textContent="Copy All",K.appendChild(Et),setTimeout(()=>{K.innerHTML="";let et=me("clipboard-copy","12px","currentColor",1.5);et&&K.appendChild(et);let Ut=y("span","persona-text-xs");Ut.textContent="Copy All",K.appendChild(Ut),K.disabled=!1},ce)},V=async()=>{if(K){K.disabled=!0;try{let P;Ee()?P=L:n?(P=await n(),P.length===0&&(P=t.getAll())):P=t.getAll();let ce=P.map(Me=>{try{return JSON.parse(Me.payload)}catch{return Me.payload}});await navigator.clipboard.writeText(JSON.stringify(ce,null,2)),H("check",1500)}catch{H("x",1500)}}},pe=()=>{Oe&&(C=Oe.value,$e(),Yt())},Be=()=>{!G||!ve||(ve.style.display=G.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{R=G.value,$e(),Yt()},150))},je=()=>{!G||!ve||(G.value="",R="",ve.style.display="none",F&&clearTimeout(F),$e(),Yt())},De=()=>{if(xe)return;let P=J.scrollTop,{action:ce,nextLastScrollTop:Me}=Xa({following:N.isFollowing(),currentScrollTop:P,lastScrollTop:Te,nearBottom:Dt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Te=Me,ce==="resume"?(N.resume(),Z=0,Ve.style.display="none"):ce==="pause"&&(N.pause(),d&&(we.textContent=p,Ve.style.display=""))},Le=P=>{let ce=Ya({following:N.isFollowing(),deltaY:P.deltaY,nearBottom:Dt(),resumeWhenNearBottom:!0});ce==="pause"?(N.pause(),d&&(we.textContent=p,Ve.style.display="")):ce==="resume"&&(N.resume(),Z=0,Ve.style.display="none")},it=()=>{d&&(J.scrollTop=J.scrollHeight,N.resume(),Z=0,Ve.style.display="none")},It=P=>{let ce=P.target;if(!ce||ce.closest("button"))return;let Me=ce.closest("[data-event-id]");if(!Me)return;let Et=Me.getAttribute("data-event-id");Et&&un(Et)},ht=P=>{if((P.metaKey||P.ctrlKey)&&P.key==="f"){P.preventDefault(),G==null||G.focus(),G==null||G.select();return}P.key==="Escape"&&(G&&document.activeElement===G?(je(),G.blur(),E.focus()):r&&r())};K&&K.addEventListener("click",V),Oe&&Oe.addEventListener("change",pe),G&&G.addEventListener("input",Be),ve&&ve.addEventListener("click",je),J.addEventListener("scroll",De),J.addEventListener("wheel",Le,{passive:!0}),J.addEventListener("click",It),Ve.addEventListener("click",it),E.addEventListener("keydown",ht);function Rt(){F&&clearTimeout(F),ee!==null&&(cancelAnimationFrame(ee),ee=null),de=!1,be.clear(),K&&K.removeEventListener("click",V),Oe&&Oe.removeEventListener("change",pe),G&&G.removeEventListener("input",Be),ve&&ve.removeEventListener("click",je),J.removeEventListener("scroll",De),J.removeEventListener("wheel",Le),J.removeEventListener("click",It),Ve.removeEventListener("click",it),E.removeEventListener("keydown",ht)}return{element:E,update:Nr,destroy:Rt}}}function fg(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 f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}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:()=>fg(e,t)});if(p)return p}return fg(e,t)};var Tl=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)})}},Co=new Tl;Co.register("PersonaArtifactCard",hg);function kv(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 yg(e,t){var Oe,K,G,ve;let n=(K=(Oe=e.features)==null?void 0:Oe.artifacts)==null?void 0:K.layout,o=((G=n==null?void 0:n.toolbarPreset)!=null?G:"default")==="document",s=(ve=n==null?void 0:n.panePadding)==null?void 0:ve.trim(),a=e.markdown?ms(e.markdown):null,i=$s(e.sanitize),d=X=>{let ie=a?a(X):Kr(X);return i?i(ie):ie},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 X;p(),(X=t.onDismiss)==null||X.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 f=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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.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 X;p(),(X=t.onDismiss)==null||X.call(t)});let x="rendered",T=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=o?Jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Jt({icon:"eye",label:"Rendered view"}),k=o?Jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Jt({icon:"code-2",label:"Source"}),M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,L=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,R=!!(L&&C&&C.length>0),F=null,j,W=null,O=null;if(o&&(E||L)&&!R){if(j=E?oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let X=me("chevron-down",14,"currentColor",2);X&&j.appendChild(X)}}else o&&R?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=E?oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=Jt({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=Jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Jt({icon:"copy",label:"Copy"});let N=o?Jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Jt({icon:"refresh-cw",label:"Refresh"}),Z=o?Jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Jt({icon:"x",label:"Close"}),Ae=()=>{var Ge,nt,Pt;let X=(Ge=be.find(Ye=>Ye.id===le))!=null?Ge:be[be.length-1],ie=(nt=X==null?void 0:X.id)!=null?nt:null,Re=(X==null?void 0:X.artifactType)==="markdown"&&(Pt=X.markdown)!=null?Pt:"",ge=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:Re,jsonPayload:ge,id:ie}},de=async()=>{var Ge;let{markdown:X,jsonPayload:ie}=Ae(),Re=(Ge=be.find(nt=>nt.id===le))!=null?Ge:be[be.length-1],ge=(Re==null?void 0:Re.artifactType)==="markdown"?X:Re?ie:"";try{await navigator.clipboard.writeText(ge)}catch{}};if(j.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&R){let{markdown:ie,jsonPayload:Re,id:ge}=Ae();try{await X({actionId:"primary",artifactId:ge,markdown:ie,jsonPayload:Re})}catch{}return}await de()}),W&&(C!=null&&C.length)){let X=()=>{var Re;return(Re=u.closest("[data-persona-root]"))!=null?Re:document.body},ie=()=>{O=Ko({items:C.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:ge,jsonPayload:Ge,id:nt}=Ae(),Pt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Pt?await Pt({actionId:Re,artifactId:nt,markdown:ge,jsonPayload:Ge}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(ge):Re==="json"||Re==="source"?await navigator.clipboard.writeText(Ge):await navigator.clipboard.writeText(ge||Ge)}catch{}},anchor:F!=null?F:W,position:"bottom-right",portal:X()})};u.isConnected?ie():requestAnimationFrame(ie),W.addEventListener("click",Re=>{Re.stopPropagation(),O==null||O.toggle()})}N.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}re()}),Z.addEventListener("click",()=>{var X;p(),(X=t.onDismiss)==null||X.call(t)});let ee=()=>{o&&(S.setAttribute("aria-pressed",x==="rendered"?"true":"false"),k.setAttribute("aria-pressed",x==="source"?"true":"false"))};S.addEventListener("click",()=>{x="rendered",ee(),re()}),k.addEventListener("click",()=>{x="source",ee(),re()});let xe=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?(f.replaceChildren(),T.append(S,k),F?M.append(F,N,Z):M.append(j,N,Z),f.append(T,xe,M),ee()):(f.appendChild(g),f.appendChild(v)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Te=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"),ne=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Te.style.paddingLeft=s,Te.style.paddingRight=s,ne.style.padding=s),u.appendChild(f),u.appendChild(Te),u.appendChild(ne);let be=[],le=null,oe=!1,re=()=>{var ge,Ge,nt,Pt;let X=o&&be.length<=1;Te.classList.toggle("persona-hidden",X),Te.replaceChildren();for(let Ye of be){let _e=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");_e.type="button",_e.textContent=Ye.title||Ye.id.slice(0,8),Ye.id===le&&_e.classList.add("persona-bg-persona-container","persona-border-persona-border"),_e.addEventListener("click",()=>t.onSelect(Ye.id)),Te.appendChild(_e)}ne.replaceChildren();let ie=le&&be.find(Ye=>Ye.id===le)||be[be.length-1];if(!ie)return;if(o){let Ye=ie.artifactType==="markdown"?"MD":(ge=ie.component)!=null?ge:"Component",J=(ie.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${J} \xB7 ${Ye}`}else g.textContent="Artifacts";if(ie.artifactType==="markdown"){if(o&&x==="source"){let _e=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");_e.textContent=(Ge=ie.markdown)!=null?Ge:"",ne.appendChild(_e);return}let Ye=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ye.innerHTML=d((nt=ie.markdown)!=null?nt:""),ne.appendChild(Ye);return}let Re=ie.component?Co.get(ie.component):void 0;if(Re){let _e={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=Re((Pt=ie.props)!=null?Pt:{},_e);if(J){ne.appendChild(J);return}}catch{}}ne.appendChild(kv(ie))},We=()=>{var ie;let X=be.length>0;if(u.classList.toggle("persona-hidden",!X),l){let Re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ge=((ie=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ie:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;X&&Ge&&oe?(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(X){var ie,Re,ge;be=X.artifacts,le=(ge=(Re=X.selectedId)!=null?Re:(ie=X.artifacts[X.artifacts.length-1])==null?void 0:ie.id)!=null?ge:null,be.length>0&&(oe=!0),re(),We()},setMobileOpen(X){oe=X,!X&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):We()}}}function lr(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 bg(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"),!lr(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 Lv(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 fi(e,t){var d,l,p,u,f,g,v,x,T,S;if(!lr(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"),Lv(e),bg(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",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"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=(g=n==null?void 0:n.paneBackground)==null?void 0:g.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=(T=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),bg(e,t)}var xg=["panel","seamless"];function hi(e,t){var i,d,l,p,u,f;for(let g of xg)e.classList.remove(`persona-artifact-appearance-${g}`);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"),!lr(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=xg.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 g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function vg(e,t){var n,r,o;return!t||!lr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Pv(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 Iv(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 Rv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Wv(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function wg(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 Cg(e,t,n,r,o,s){let a=Pv(o,200),i=Wv(t,n,r,200);i=Math.max(a,i);let d=Iv(s);return d!==null&&(i=Math.min(i,d)),Rv(e,a,i)}var Ag={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Ml=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,T;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Ag[a])!=null?x:Ag.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 S=y("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,d.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var C,R;let k=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${t.id}-${a}-${S.name}`;let M=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=S.label,k.appendChild(M);let E=(C=S.type)!=null?C:"text",L;E==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=E),L.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",L.id=`${t.id}-${a}-${S.name}`,L.name=S.name,L.placeholder=(R=S.placeholder)!=null?R:"",S.required&&(L.required=!0),k.appendChild(L),p.appendChild(k)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=(T=i.submitLabel)!=null?T:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async S=>{var L,C;S.preventDefault();let k=(L=n.formEndpoint)!=null?L:"/form",M=new FormData(p),E={};M.forEach((R,F)=>{E[F]=R}),E.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let F=await R.json();f.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){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var kl=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()}},yi=new kl;var Sg=()=>{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 Hv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Bv=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},bi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Hv(e),n=Bv(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}},Ll=e=>typeof e=="string"?e:e==null?"":String(e),Ms={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ll(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Ll(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:Ll(n.text)}}},Eg=e=>Array.isArray(e)?e.map(t=>String(t)):[],xi=e=>{let t=new Set(Eg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Eg(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 f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Dv=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}},Nv=e=>e.map(t=>({...t,streaming:!1})),Ov=e=>e.map(t=>({...t,status:"complete"})),Pl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Dv(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?Nv(n.messages):void 0,artifacts:n.artifacts?Ov(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 Fv,STR as _v,OBJ as $v}from"partial-json";function jv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Uv(e,t){if(!jv(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 Il(){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=Fv(n,_v|$v),s=Uv(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function qv(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Rl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Co.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 zv(){let e=Il();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Tg(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 Wl(e){let t=Tg(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 Hl(e){let t=Tg(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 Vv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Bl(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=Vv}=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,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,g.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,g.appendChild(x),f.appendChild(g);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];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=`
29
31
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
30
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>
31
33
  </svg>
32
- `,W.addEventListener("click",()=>{m=S,C.forEach((B,D)=>{let k=D<S;B.classList.toggle("selected",k),B.setAttribute("aria-checked",D===S-1?"true":"false")})}),C.push(W),E.appendChild(W)}f.appendChild(E);let I=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),S.appendChild(I),f.appendChild(S)}let N=document.createElement("div");N.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(m===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let S=(I==null?void 0:I.value.trim())||void 0;await t(m,S),p.remove()}catch(S){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),N.appendChild(M),N.appendChild(P),f.appendChild(N),p.appendChild(f),p}function Wl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,x.appendChild(E),g.appendChild(x);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-nps",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let N=document.createElement("span");N.className="persona-feedback-label-low",N.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=p,I.appendChild(N),I.appendChild(M);let P=document.createElement("div");P.className="persona-feedback-numbers";let S=[];for(let j=0;j<=10;j++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-number-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`Rating ${j} out of 10`),z.textContent=String(j),z.dataset.rating=String(j),j<=6?z.classList.add("persona-feedback-detractor"):j<=8?z.classList.add("persona-feedback-passive"):z.classList.add("persona-feedback-promoter"),z.addEventListener("click",()=>{f=j,S.forEach((te,Pe)=>{te.classList.toggle("selected",Pe===j),te.setAttribute("aria-checked",Pe===j?"true":"false")})}),S.push(z),P.appendChild(z)}C.appendChild(I),C.appendChild(P),g.appendChild(C);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=o,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),g.appendChild(j)}let B=document.createElement("div");B.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{n==null||n(),m.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await t(f,j),m.remove()}catch(j){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),B.appendChild(D),B.appendChild(k),g.appendChild(B),m.appendChild(g),m}var Ss="persona-chat-history",Tv=30*1e3,Ev={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Mv(e){var r,s,o;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=(s=Ev[i.type])!=null?s:"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((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function yi(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 kv(e){var t,n,r,s,o,a,i,d,c;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:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Lv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Hl=e=>!e||typeof e!="object"?{}:{...e},hg=e=>e.map(t=>({...t,streaming:!1})),yg=(e,t,n)=>{let r=e!=null&&e.markdown?is(e.markdown):null,s=Ns(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(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."),o=>{var p,m,f;let a=(p=o.text)!=null?p:"",i=(m=o.message.rawContent)!=null?m:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});g!==null&&(a=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}let d=Bo()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...o,text:a,raw:(f=i!=null?i:o.text)!=null?f:""});c=s?s(g):g}else if(r){let g=r(a);c=s&&d?s(g):g}else c=qr(a);return c}};function bg(e){var i,d,c,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",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=xe(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let m=y("span","persona-drop-overlay-label");m.textContent=e.label,t.appendChild(m)}return t}var Bl=(e,t,n)=>{var xc,vc,wc,Cc,Sc,Ac,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,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd;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=rl(t),s=gi.getForInstance(r.plugins);r.components&&bo.registerAll(r.components);let o=mg(),i=r.persistState===!1?null:(xc=r.storageAdapter)!=null?xc:Ml(),d={},c=null,p=!1,m=l=>{if(r.onStateLoaded)try{let u=r.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:b}=u;return b&&(p=!0),h}return u}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return m(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=m(u);h.metadata&&(d=Hl(h.metadata)),(vc=h.messages)!=null&&vc.length&&(r={...r,initialMessages:h.messages}),(wc=h.artifacts)!=null&&wc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Cc=h.selectedArtifactId)!=null?Cc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(Sc=l.messages)!=null&&Sc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let f=()=>d,g=l=>{var h;d=(h=l({...d}))!=null?h:{},no()},x=r.actionParsers&&r.actionParsers.length?r.actionParsers:[fi],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Cs.message,Cs.messageAndClick],E=hi({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let C=(Tc=(Ac=r.launcher)==null?void 0:Ac.enabled)!=null?Tc:!0,I=(Mc=(Ec=r.launcher)==null?void 0:Ec.autoExpand)!=null?Mc:!1,N=(kc=r.autoFocusInput)!=null?kc:!1,M=I,P=C,S=(Pc=(Lc=r.layout)==null?void 0:Lc.header)==null?void 0:Pc.layout,W=!1,B=()=>ho(r),D=()=>C||B(),k=B()?!1:C?I:!0,j=!1,z=null,te=()=>{j=!0,z&&clearTimeout(z),z=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},Pe=yg(r,E,te),je=(Rc=(Ic=r.features)==null?void 0:Ic.showReasoning)!=null?Rc:!0,Se=(Hc=(Wc=r.features)==null?void 0:Wc.showToolCalls)!=null?Hc:!0,ke=(Dc=(Bc=r.features)==null?void 0:Bc.showEventStreamToggle)!=null?Dc:!1,Fe=(Oc=(Nc=r.features)==null?void 0:Nc.scrollToBottom)!=null?Oc:{},he=(_c=(Fc=r.features)==null?void 0:Fc.scrollBehavior)!=null?_c:{},ae=`${(jc=typeof r.persistState=="object"?($c=r.persistState)==null?void 0:$c.keyPrefix:void 0)!=null?jc:"persona-"}event-stream`,Q=ke?new pa(ae):null,ne=(zc=(qc=(Uc=r.features)==null?void 0:Uc.eventStream)==null?void 0:qc.maxEvents)!=null?zc:2e3,le=ke?new da(ne,Q):null,re=ke?new ua:null,G=null,ee=!1,qe=null,J=0;Q==null||Q.open().then(()=>le==null?void 0:le.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ie={onCopy:l=>{var u,h;o.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;o.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},Re=(Vc=r.statusIndicator)!=null?Vc:{},ve=l=>{var u,h,b,A;return l==="idle"?(u=Re.idleText)!=null?u:vn.idle:l==="connecting"?(h=Re.connectingText)!=null?h:vn.connecting:l==="connected"?(b=Re.connectedText)!=null?b:vn.connected:l==="error"?(A=Re.errorText)!=null?A:vn.error:vn[l]};function Xe(l,u,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=u,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=u}let Ke=jm({config:r,showClose:D()}),{wrapper:Ne,panel:ce,pillRoot:et}=Ke.shell,X=Ke.panelElements,{container:de,body:we,messagesWrapper:ze,suggestions:Lt,textarea:Ae,sendButton:me,sendButtonWrapper:fn,composerForm:Pt,statusText:rn,introTitle:yr,introSubtitle:hn,closeButton:Ve,iconHolder:T,headerTitle:ue,headerSubtitle:Me,header:Te,footer:Ie,actionsRow:tt,leftActions:Je,rightActions:pt}=X,It=X.setSendButtonMode,U=X.micButton,st=X.micButtonWrapper,V=X.attachmentButton,pe=X.attachmentButtonWrapper,Ee=X.attachmentInput,bt=X.attachmentPreviewsContainer;de.classList.add("persona-relative"),we.classList.add("persona-relative");let Yt=12,Zt=()=>{var l;return(l=Fe.label)!=null?l:""},un=()=>{var l;return(l=Fe.iconName)!=null?l:"arrow-down"},Wt=()=>Fe.enabled!==!1,nt=()=>{var l;return(l=he.mode)!=null?l:"follow"},Rt=()=>{var l;return(l=he.anchorTopOffset)!=null?l:16},lt=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");lt.type="button",lt.style.display="none",lt.setAttribute("data-persona-scroll-to-bottom","true");let Kt=y("span","persona-flex persona-items-center"),Qn=y("span",""),Cn=y("span","");Cn.setAttribute("data-persona-scroll-to-bottom-count",""),Cn.style.display="none",lt.append(Kt,Qn,Cn),de.appendChild(lt);let en=y("div","persona-stream-anchor-spacer");en.setAttribute("aria-hidden","true"),en.setAttribute("data-persona-anchor-spacer",""),en.style.flexShrink="0",en.style.pointerEvents="none",en.style.height="0px",we.appendChild(en);let Pn=()=>{let u=Ie.style.display==="none"?0:Ie.offsetHeight;lt.style.bottom=`${u+Yt}px`};Pn();let br=()=>{let l=!!Zt();lt.setAttribute("aria-label",Zt()||"Jump to latest"),lt.title=Zt(),lt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Kt.innerHTML="";let u=xe(un(),"14px","currentColor",2);u?(Kt.appendChild(u),Kt.style.display=""):Kt.style.display="none",Qn.textContent=Zt(),Qn.style.display=l?"":"none"};br();let xt=null,Dn=null,xr=s.find(l=>l.renderHeader);if(xr!=null&&xr.renderHeader){let l=xr.renderHeader({config:r,defaultRenderer:()=>{let u=yo({config:r,showClose:D()});return ys(de,u,r),u.header},onClose:()=>_t(!1,"user")});if(l){let u=de.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Te=l,Ke.header.element=l)}}let Wr=()=>{var u,h,b,A;if(!le)return;if(ee=!0,!G&&le&&(G=rg({buffer:le,getFullHistory:()=>le.getAllFromStore(),onClose:()=>lr(),config:r,plugins:s,getThroughput:()=>{var R;return(R=re==null?void 0:re.getMetric())!=null?R:{status:"idle"}}})),G&&(we.style.display="none",(u=Ie.parentNode)==null||u.insertBefore(G.element,Ie),G.update()),ht){ht.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let R=(A=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:A.toggleButtonActive;R&&R.split(/\s+/).forEach(q=>q&&ht.classList.add(q))}let l=()=>{if(!ee)return;let R=Date.now();R-J>=200&&(G==null||G.update(),J=R),qe=requestAnimationFrame(l)};J=0,qe=requestAnimationFrame(l),Ye(),o.emit("eventStream:opened",{timestamp:Date.now()})},lr=()=>{var l,u,h;if(ee){if(ee=!1,G&&G.element.remove(),we.style.display="",ht){ht.style.boxShadow="";let b=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(A=>A&&ht.classList.remove(A))}qe!==null&&(cancelAnimationFrame(qe),qe=null),Ye(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ht=null;if(ke){let l=(Gc=(Kc=r.features)==null?void 0:Kc.eventStream)==null?void 0:Gc.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ht=y("button",u),ht.style.width="28px",ht.style.height="28px",ht.style.color=Ln.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let h=xe("activity","18px","currentColor",1.5);h&&ht.appendChild(h);let b=X.clearChatButtonWrapper,A=X.closeButtonWrapper,R=b||A;R&&R.parentNode===Te?Te.insertBefore(ht,R):Te.appendChild(ht),ht.addEventListener("click",()=>{ee?lr():Wr()})}let vo=l=>{var A,R,q,O,H;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=(A=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?A:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let oe=l.querySelector("[data-persona-composer-form]");oe!=null&&oe.parentNode?oe.parentNode.insertBefore(h,oe):l.insertBefore(h,l.firstChild)}if(!((R=l.querySelector("[data-persona-composer-attachment-input]"))!=null?R:l.querySelector('input[type="file"]'))){let oe=y("input");oe.type="file",oe.setAttribute("data-persona-composer-attachment-input",""),oe.accept=((q=u.allowedTypes)!=null?q:zr).join(","),oe.multiple=((O=u.maxFiles)!=null?O:4)>1,oe.style.display="none",oe.setAttribute("aria-label",(H=u.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(oe)}},vr=s.find(l=>l.renderComposer);if(vr!=null&&vr.renderComposer){let l=r.composer,u=vr.renderComposer({config:r,defaultRenderer:()=>la({config:r}).footer,onSubmit:h=>{var q;if(!F||F.isStreaming())return;let b=h.trim(),A=(q=xt==null?void 0:xt.hasAttachments())!=null?q:!1;if(!b&&!A)return;Ql();let R;A&&(R=[],R.push(...xt.getContentParts()),b&&R.push(Oa(b))),F.sendMessage(b,{contentParts:R}),A&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ee==null||Ee.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Jc=r.voiceRecognition)==null?void 0:Jc.enabled)===!0?()=>{Dn==null||Dn()}:void 0});u&&(Ke.replaceComposer(u),Ie=Ke.composer.footer)}let wo=l=>{let u=(...se)=>{for(let Y of se){let be=l.querySelector(Y);if(be)return be}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),q=l.querySelector("[data-persona-composer-status]");h&&(Pt=h),b&&(Ae=b),A&&(me=A),R&&(U=R,st=R.parentElement),q&&(rn=q);let O=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Lt=O);let H=u("[data-persona-composer-attachment-button]",".persona-attachment-button");H&&(V=H,pe=H.parentElement),Ee=u("[data-persona-composer-attachment-input]",'input[type="file"]'),bt=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let oe=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");oe&&(tt=oe)};vo(Ie),wo(Ie);let In=(ed=(Qc=r.layout)==null?void 0:Qc.contentMaxWidth)!=null?ed:B()?(Zc=(Yc=(Xc=r.launcher)==null?void 0:Xc.composerBar)==null?void 0:Yc.contentMaxWidth)!=null?Zc:"720px":void 0;if(In&&(ze.style.maxWidth=In,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%"),In&&Pt&&!B()&&(Pt.style.maxWidth=In,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),In&&Lt&&!B()&&(Lt.style.maxWidth=In,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),In&&bt&&!B()&&(bt.style.maxWidth=In,bt.style.marginLeft="auto",bt.style.marginRight="auto"),(td=r.attachments)!=null&&td.enabled&&Ee&&bt){xt=fs.fromConfig(r.attachments),xt.setPreviewsContainer(bt),Ee.addEventListener("change",h=>{let b=h.target;xt==null||xt.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,u=bg(l);de.appendChild(u)}(()=>{var b,A;let l=(A=(b=r.layout)==null?void 0:b.slots)!=null?A:{},u=R=>{switch(R){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ze;case"footer-top":return Lt;case"composer":return Pt;case"footer-bottom":return rn;default:return null}},h=(R,q)=>{var O;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")Te.insertBefore(q,Te.firstChild);else if(R==="header-right")Te.appendChild(q);else{let H=Te.querySelector(".persona-flex-col");H?(O=H.parentNode)==null||O.insertBefore(q,H.nextSibling):Te.appendChild(q)}break;case"body-top":{let H=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(q):we.insertBefore(q,we.firstChild);break}case"body-bottom":we.appendChild(q);break;case"footer-top":Lt.replaceWith(q);break;case"footer-bottom":rn.replaceWith(q);break;default:break}};for(let[R,q]of Object.entries(l))if(q)try{let O=q({config:r,defaultContent:()=>u(R)});O&&h(R,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,O)}})();let Gr=l=>{var q,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-bubble-type");if(R==="reasoning")xs.has(A)?xs.delete(A):xs.add(A),Km(A,b);else if(R==="tool")vs.has(A)?vs.delete(A):vs.add(A),Gm(A,b,r);else if(R==="approval"){let H=r.approval!==!1?r.approval:void 0,oe=((q=H==null?void 0:H.detailsDisplay)!=null?q:"collapsed")==="expanded",se=(O=ci.get(A))!=null?O:oe;ci.set(A,!se),Ym(A,b,r)}Tr.delete(A)};ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Gr(l))}),ze.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Gr(l))}),ze.addEventListener("copy",l=>{let{clipboardData:u}=l;if(!u)return;let h=ze.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let A=b.toString(),R=Cm(A);!R||R===A||(u.setData("text/plain",R),l.preventDefault())});let Hr=new Map,Jr=null,Qr="idle",Co={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},So=(l,u)=>{let{icon:h,label:b}=Co[u];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let A=xe(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},Xr=()=>{ze.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{var R;let h=u.closest("[data-actions-for]"),b=(R=h==null?void 0:h.getAttribute("data-actions-for"))!=null?R:null;So(u,b&&b===Jr?Qr:"idle")})};ze.addEventListener("click",l=>{var q;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let A=b.getAttribute("data-actions-for");if(!A)return;let R=h.getAttribute("data-action");if(R==="copy"){let H=F.getMessages().find(oe=>oe.id===A);if(H&&ie.onCopy){let oe=H.content||"";navigator.clipboard.writeText(oe).then(()=>{h.classList.add("persona-message-action-success");let se=xe("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=xe("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),ie.onCopy(H)}}else if(R==="read-aloud")F.toggleReadAloud(A);else if(R==="upvote"||R==="downvote"){let H=((q=Hr.get(A))!=null?q:null)===R,oe=R==="upvote"?"thumbs-up":"thumbs-down";if(H){Hr.delete(A),h.classList.remove("persona-message-action-active");let se=xe(oe,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=R==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${se}"]`);if(Y){Y.classList.remove("persona-message-action-active");let $e=xe(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Y.innerHTML="",Y.appendChild($e))}Hr.set(A,R),h.classList.add("persona-message-action-active");let be=xe(oe,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=F.getMessages().find(ot=>ot.id===A);Ce&&ie.onFeedback&&ie.onFeedback({type:R,messageId:Ce.id,message:Ce})}}}),ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let R=h.getAttribute("data-approval-action");if(!R)return;let q=R==="approve"?"approved":"denied",H=F.getMessages().find(se=>se.id===A);if(!(H!=null&&H.approval))return;let oe=b.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?F.resolveWebMcpApproval(A,q):F.resolveApproval(H.approval,q)});let wt=null,Nn=null,On={artifacts:[],selectedId:null},Sn=!1,St={current:null};ze.addEventListener("click",l=>{var Y,be,Oe,Ce,ot;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Oe=(be=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Oe.call(be,{type:"download",artifactId:b}))===!0)return;let R=F.getArtifactById(b),q=R==null?void 0:R.markdown,O=(R==null?void 0:R.title)||"artifact";if(!q){let $e=h.closest("[data-open-artifact]"),mt=$e==null?void 0:$e.closest("[data-message-id]"),at=mt==null?void 0:mt.getAttribute("data-message-id");if(at){let Le=F.getMessages().find(Ue=>Ue.id===at);if(Le!=null&&Le.rawContent)try{let Ue=JSON.parse(Le.rawContent);q=(Ce=Ue==null?void 0:Ue.props)==null?void 0:Ce.markdown,O=((ot=Ue==null?void 0:Ue.props)==null?void 0:ot.title)||O}catch{}}}if(!q)return;let H=new Blob([q],{type:"text/markdown"}),oe=URL.createObjectURL(H),se=document.createElement("a");se.href=oe,se.download=`${O}.md`,se.click(),URL.revokeObjectURL(oe)}),ze.addEventListener("click",l=>{var R,q,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((O=(q=(R=r.features)==null?void 0:R.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:O.call(q,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Sn=!1,F.selectArtifact(b),$n())}),ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let Xn=X.composerOverlay,Yn=(l,u,h)=>{var O,H,oe,se;let b=u.trim();if(!b||!St.current)return;let A=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",R=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:b,answers:h.structured,values:(H=h.values)!=null?H:h.source==="multi"?b.split(", "):[b],isFreeText:R,source:h.source},bubbles:!0,composed:!0})),Oo(Xn,A);let q=St.current.getMessages().find(Y=>{var be;return((be=Y.toolCall)==null?void 0:be.id)===A});(oe=q==null?void 0:q.agentMetadata)!=null&&oe.awaitingLocalTool?St.current.resolveAskUserQuestion(q,(se=h.structured)!=null?se:b):St.current.sendMessage(b)},Fn=l=>{var A;let u=St.current;if(!u)return;let h=(A=l.getAttribute("data-tool-call-id"))!=null?A:"",b=u.getMessages().find(R=>{var q;return((q=R.toolCall)==null?void 0:q.id)===h});b&&u.persistAskUserQuestionProgress(b,{answers:ka(l,b),currentIndex:or(l)})},Yr=l=>Object.entries(l).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Br=l=>{var A,R,q;if(((R=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:R.groupedAutoAdvance)===!1)return;let u=or(l),h=cs(l);if(u>=h-1)return;let b=(q=St.current)==null?void 0:q.getMessages().find(O=>{var H;return((H=O.toolCall)==null?void 0:H.id)===l.getAttribute("data-tool-call-id")});b&&(La(l,b,r,u+1),Fn(l))};Xn.addEventListener("click",l=>{var R,q,O,H,oe,se,Y,be,Oe,Ce,ot,$e,mt,at;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let We=(R=b.getAttribute("data-tool-call-id"))!=null?R:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Oo(Xn,We);let Le=(q=St.current)==null?void 0:q.getMessages().find(Ue=>{var Ge;return((Ge=Ue.toolCall)==null?void 0:Ge.id)===We});(O=Le==null?void 0:Le.agentMetadata)!=null&&O.awaitingLocalTool&&((H=St.current)==null||H.markAskUserQuestionResolved(Le),(oe=St.current)==null||oe.resolveAskUserQuestion(Le,"(dismissed)"));return}if(A==="pick"){let We=h.getAttribute("data-option-label");if(!We)return;let Le=b.getAttribute("data-multi-select")==="true",Ue=uo(b);if(Ue&&Le){let Ge=No(b)[or(b)],yt=new Set(Array.isArray(Ge)?Ge:[]);yt.has(We)?yt.delete(We):yt.add(We),mo(b,Array.from(yt)),Fn(b);return}if(Ue){mo(b,We),Fn(b),Br(b);return}if(Le){let Ge=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ge?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ge);let yt=b.querySelector('[data-ask-user-action="submit-multi"]');yt&&(yt.disabled=ji(b).length===0);return}Yn(b,We,{source:"pick",values:[We]});return}if(A==="submit-multi"){let We=ji(b);if(We.length===0)return;Yn(b,We.join(", "),{source:"multi",values:We});return}if(A==="open-free-text"){let We=b.querySelector('[data-ask-free-text-row="true"]');if(We){We.classList.remove("persona-hidden");let Le=We.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(A==="focus-free-text"){let We=b.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus();return}if(A==="submit-free-text"){let We=b.querySelector('[data-ask-free-text-input="true"]'),Le=(se=We==null?void 0:We.value)!=null?se:"";if(!Le.trim())return;if(uo(b)){mo(b,Le.trim()),Fn(b),Br(b);return}Yn(b,Le,{source:"free-text"});return}if(A==="next"||A==="back"){if(!St.current)return;let We=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",Le=St.current.getMessages().find(De=>{var He;return((He=De.toolCall)==null?void 0:He.id)===We});if(!Le)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),Ge=(Oe=(be=Ue==null?void 0:Ue.value)==null?void 0:be.trim())!=null?Oe:"";if(Ge){let De=No(b)[or(b)];(typeof De!="string"||De!==Ge)&&mo(b,Ge)}let yt=A==="next"?1:-1,L=or(b)+yt;La(b,Le,r,L),Fn(b);return}if(A==="submit-all"){if(!St.current)return;let We=(Ce=b.getAttribute("data-tool-call-id"))!=null?Ce:"",Le=St.current.getMessages().find(De=>{var He;return((He=De.toolCall)==null?void 0:He.id)===We});if(!Le)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),Ge=($e=(ot=Ue==null?void 0:Ue.value)==null?void 0:ot.trim())!=null?$e:"";Ge&&mo(b,Ge);let yt=ka(b,Le);St.current.persistAskUserQuestionProgress(Le,{answers:yt,currentIndex:or(b)});let L=Yr(yt);Yn(b,L||"(submitted)",{source:"submit-all",structured:yt});return}if(A==="skip"){if(!St.current)return;let We=(mt=b.getAttribute("data-tool-call-id"))!=null?mt:"",Le=St.current.getMessages().find(He=>{var ge;return((ge=He.toolCall)==null?void 0:ge.id)===We});if(!Le)return;let Ue=uo(b),Ge=or(b),yt=cs(b),L=Ge>=yt-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:We},bubbles:!0,composed:!0})),Oo(Xn,We),(at=Le.agentMetadata)!=null&&at.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Le),St.current.resolveAskUserQuestion(Le,"(dismissed)"));return}mo(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),L){let He=ka(b,Le),ge=Yr(He);Yn(b,ge||"(skipped)",{source:"submit-all",structured:He});return}La(b,Le,r,Ge+1),Fn(b);return}}),Xn.addEventListener("keydown",l=>{var R;if(l.key!=="Enter")return;let h=l.target;if(!((R=h.matches)!=null&&R.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let A=h.value;if(A.trim()){if(uo(b)){mo(b,A.trim()),Fn(b),Br(b);return}Yn(b,A,{source:"free-text"})}});let Zr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if((u==null?void 0:u.tagName)==="INPUT"||(u==null?void 0:u.tagName)==="TEXTAREA"||u!=null&&u.isContentEditable)return;let h=Xn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),R=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];R&&(l.preventDefault(),R.click())};document.addEventListener("keydown",Zr);let _n=null,Ht=null,An=null,Zn=null,eo=()=>{};function Dr(){Zn==null||Zn(),Zn=null}let to=()=>{var q;if(!_n||!Ht)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((q=e.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ht.style.removeProperty("position"),Ht.style.removeProperty("left"),Ht.style.removeProperty("top"),Ht.style.removeProperty("bottom"),Ht.style.removeProperty("width"),Ht.style.removeProperty("z-index");return}let b=_n.firstElementChild;if(!b||b===Ht)return;let A=10;Ht.style.position="absolute",Ht.style.top="0",Ht.style.bottom="0",Ht.style.width=`${A}px`,Ht.style.zIndex="5";let R=b.offsetWidth-A/2;Ht.style.left=`${Math.max(0,R)}px`},wr=()=>{},$n=()=>{var h,b,A,R,q;if(!wt||!ir(r))return;ui(e,r),mi(e,r),wr();let l=(R=(A=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:A.narrowHostMaxWidth)!=null?R:520,u=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),wt.update(On),Sn?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(q=wt.backdrop)==null||q.classList.add("persona-hidden")):On.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),eo()};if(ir(r)){ce.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(de),wt=ag(r,{onSelect:h=>{var b;return(b=St.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Sn=!0,$n()}}),wt.element.classList.add("persona-hidden"),_n=u,u.appendChild(l),u.appendChild(wt.element),wt.backdrop&&ce.appendChild(wt.backdrop),ce.appendChild(u),eo=()=>{var b,A,R,q;if(!_n||!wt)return;if(!(((R=(A=(b=r.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:R.resizable)===!0)){An==null||An(),An=null,Dr(),Ht&&(Ht.remove(),Ht=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!Ht){let O=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let H=e.ownerDocument,oe=(q=H.defaultView)!=null?q:window,se=Y=>{var mt,at;if(!wt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;Y.preventDefault(),Dr();let be=Y.clientX,Oe=wt.element.getBoundingClientRect().width,Ce=(at=(mt=r.features)==null?void 0:mt.artifacts)==null?void 0:at.layout,ot=We=>{let Le=_n.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Ge=Ue?0:dg(_n,oe),yt=Ue?0:O.getBoundingClientRect().width||6,L=Oe-(We.clientX-be),De=pg(L,Le,Ge,yt,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);wt.element.style.width=`${De}px`,wt.element.style.maxWidth="none",to()},$e=()=>{H.removeEventListener("pointermove",ot),H.removeEventListener("pointerup",$e),H.removeEventListener("pointercancel",$e),Zn=null;try{O.releasePointerCapture(Y.pointerId)}catch{}};Zn=$e,H.addEventListener("pointermove",ot),H.addEventListener("pointerup",$e),H.addEventListener("pointercancel",$e);try{O.setPointerCapture(Y.pointerId)}catch{}};O.addEventListener("pointerdown",se),Ht=O,_n.insertBefore(O,wt.element),An=()=>{O.removeEventListener("pointerdown",se)}}if(Ht){let O=On.artifacts.length>0&&!Sn;Ht.classList.toggle("persona-hidden",!O),to()}},wr=()=>{var oe,se,Y,be,Oe,Ce,ot,$e,mt,at,We,Le,Ue,Ge;if(!C||!wt||((se=(oe=r.launcher)==null?void 0:oe.sidebarMode)!=null?se:!1)||dn(r)&&ar(r).reveal==="emerge")return;let b=(Y=e.ownerDocument.defaultView)!=null?Y:window,A=(Oe=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Oe:!0,R=(ot=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?ot:640;if(A&&b.innerWidth<=R||!cg(r,C))return;let q=(at=(mt=($e=r.launcher)==null?void 0:$e.width)!=null?mt:r.launcherWidth)!=null?at:sr,O=(Ge=(Ue=(Le=(We=r.features)==null?void 0:We.artifacts)==null?void 0:Le.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Sn?(ce.style.width=O,ce.style.maxWidth=O):(ce.style.width=q,ce.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{$n()}),Nn.observe(ce))}else ce.appendChild(de),B()&&et&&(X.peekBanner&&et.appendChild(X.peekBanner),et.appendChild(Ie));e.appendChild(Ne),et&&e.appendChild(et);let ye=()=>{var De,He,ge,Dt,Bt,Ut,vt,$t,Vn,Xt,Qe,Mt,nn,rr,Kn,ko,Lo,rs,os,zt,Po,ao,io,Ur,Io,ur,Ze,an;if(B()){ce.style.width="100%",ce.style.maxWidth="100%";let Ft=(He=(De=r.launcher)==null?void 0:De.composerBar)!=null?He:{},Nt=Ne.dataset.state==="expanded",gt=(ge=Ft.expandedSize)!=null?ge:"anchored";if(!(Nt&&gt!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let Ct=(Bt=(Dt=r.theme)==null?void 0:Dt.components)==null?void 0:Bt.panel,bn=Zs(r),Tn=(Mn,Ro)=>{var Ws;return Mn==null||Mn===""?Ro:(Ws=hs(bn,Mn))!=null?Ws:Mn},Lr="1px solid var(--persona-border)",pn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",En="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=Tn(Ct==null?void 0:Ct.border,Lr),de.style.borderRadius=Tn(Ct==null?void 0:Ct.borderRadius,En),de.style.boxShadow=Tn(Ct==null?void 0:Ct.shadow,pn),de.style.overflow="hidden";return}let l=dn(r),u=(vt=(Ut=r.launcher)==null?void 0:Ut.sidebarMode)!=null?vt:!1,h=l||u||((Vn=($t=r.launcher)==null?void 0:$t.fullHeight)!=null?Vn:!1),b=((Xt=r.launcher)==null?void 0:Xt.enabled)===!1,A=(Mt=(Qe=r.theme)==null?void 0:Qe.components)==null?void 0:Mt.panel,R=Zs(r),q=(Ft,Nt)=>{var gt;return Ft==null||Ft===""?Nt:(gt=hs(R,Ft))!=null?gt:Ft},O=(nn=e.ownerDocument.defaultView)!=null?nn:window,H=(Kn=(rr=r.launcher)==null?void 0:rr.mobileFullscreen)!=null?Kn:!0,oe=(Lo=(ko=r.launcher)==null?void 0:ko.mobileBreakpoint)!=null?Lo:640,se=O.innerWidth<=oe,Y=H&&se&&C,be=(os=(rs=r.launcher)==null?void 0:rs.position)!=null?os:"bottom-left",Oe=be==="bottom-left"||be==="top-left",Ce=(Po=(zt=r.launcher)==null?void 0:zt.zIndex)!=null?Po:wn,ot=u||Y?"none":"1px solid var(--persona-border)",$e=Y?"none":u?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))";l&&!Y&&($e="none",ot="none");let mt=u||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=q(A==null?void 0:A.border,ot),We=q(A==null?void 0:A.shadow,$e),Le=q(A==null?void 0:A.borderRadius,mt),Ue=we.scrollTop;e.style.cssText="",Ne.style.cssText="",ce.style.cssText="",de.style.cssText="",we.style.cssText="",Ie.style.cssText="";let Ge=()=>{var Nt;if(Ue<=0)return;((Nt=we.ownerDocument.defaultView)!=null?Nt:window).requestAnimationFrame(()=>{if(we.scrollTop===Ue)return;let gt=we.scrollHeight-we.clientHeight;gt<=0||(we.scrollTop=Math.min(Ue,gt))})};if(Y){Ne.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"),Ne.style.cssText=`
34
+ `,R.addEventListener("click",()=>{u=C,S.forEach((F,j)=>{let W=j<C;F.classList.toggle("selected",W),F.setAttribute("aria-checked",j===C-1?"true":"false")})}),S.push(R),T.appendChild(R)}f.appendChild(T);let k=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),C.appendChild(k),f.appendChild(C)}let M=document.createElement("div");M.className="persona-feedback-actions";let E=document.createElement("button");E.type="button",E.className="persona-feedback-btn persona-feedback-btn-skip",E.textContent=i,E.addEventListener("click",()=>{n==null||n(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(u===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let C=(k==null?void 0:k.value.trim())||void 0;await t(u,C),p.remove()}catch(C){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),M.appendChild(E),M.appendChild(L),f.appendChild(M),p.appendChild(f),p}function Dl(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 f=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=o,v.appendChild(T),g.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let M=document.createElement("span");M.className="persona-feedback-label-low",M.textContent=l;let E=document.createElement("span");E.className="persona-feedback-label-high",E.textContent=p,k.appendChild(M),k.appendChild(E);let L=document.createElement("div");L.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",()=>{f=O,C.forEach((Z,Ae)=>{Z.classList.toggle("selected",Ae===O),Z.setAttribute("aria-checked",Ae===O?"true":"false")})}),C.push(N),L.appendChild(N)}S.appendChild(k),S.appendChild(L),g.appendChild(S);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),g.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(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.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(f,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),g.appendChild(F),u.appendChild(g),u}var ks="persona-chat-history",Kv=30*1e3,Gv={"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 Jv(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=Gv[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 vi(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 Qv(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 Xv(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nl=e=>!e||typeof e!="object"?{}:{...e},Mg=e=>e.map(t=>({...t,streaming:!1})),kg=(e,t,n)=>{let r=e!=null&&e.markdown?ms(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,f;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d=Oo()!==null,l;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""});l=o?o(g):g}else if(r){let g=s.streaming?Iu(a):a,v=r(g);l=o&&d?o(v):v}else l=Kr(a);return l}};function Lg(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 Ol=(e,t,n)=>{var Cc,Ac,Sc,Ec,Tc,Mc,kc,Lc,Pc,Ic,Rc,Wc,Hc,Bc,Dc,Nc,Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Gc,Jc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd;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=sl(t),o=yi.getForInstance(r.plugins),{plugin:s,teardown:a}=cg();r.components&&Co.registerAll(r.components);let i=Sg(),l=r.persistState===!1?null:(Cc=r.storageAdapter)!=null?Cc:Pl(),p={},u=null,f=!1,g=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&&(f=!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 g(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=Nl(h.metadata)),(Ac=h.messages)!=null&&Ac.length&&(r={...r,initialMessages:h.messages}),(Sc=h.artifacts)!=null&&Sc.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=g({messages:[],metadata:{}});(Tc=c.messages)!=null&&Tc.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:{},w()},T=r.actionParsers&&r.actionParsers.length?r.actionParsers:[bi],S=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ms.message,Ms.messageAndClick],k=xi({parsers:T,handlers:S,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null});k.syncFromMetadata();let M=(kc=(Mc=r.launcher)==null?void 0:Mc.enabled)!=null?kc:!0,E=(Pc=(Lc=r.launcher)==null?void 0:Lc.autoExpand)!=null?Pc:!1,L=(Ic=r.autoFocusInput)!=null?Ic:!1,C=E,R=M,F=(Wc=(Rc=r.layout)==null?void 0:Rc.header)==null?void 0:Wc.layout,j=!1,W=()=>vo(r),O=()=>M||W(),N=W()?!1:M?E:!0,Z=!1,Ae=null,de=()=>{Z=!0,Ae&&clearTimeout(Ae),Ae=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=kg(r,k,de),xe=(Bc=(Hc=r.features)==null?void 0:Hc.showReasoning)!=null?Bc:!0,Te=(Nc=(Dc=r.features)==null?void 0:Dc.showToolCalls)!=null?Nc:!0,ne=(Fc=(Oc=r.features)==null?void 0:Oc.showEventStreamToggle)!=null?Fc:!1,be=($c=(_c=r.features)==null?void 0:_c.scrollToBottom)!=null?$c:{},le=(Uc=(jc=r.features)==null?void 0:jc.scrollBehavior)!=null?Uc:{},re=`${(zc=typeof r.persistState=="object"?(qc=r.persistState)==null?void 0:qc.keyPrefix:void 0)!=null?zc:"persona-"}event-stream`,We=ne?new ha(re):null,Oe=(Gc=(Kc=(Vc=r.features)==null?void 0:Vc.eventStream)==null?void 0:Kc.maxEvents)!=null?Gc:2e3,K=ne?new fa(Oe,We):null,G=ne?new ya:null,ve=null,X=!1,ie=null,Re=0;We==null||We.open().then(()=>K==null?void 0:K.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)}},Ge=(Jc=r.statusIndicator)!=null?Jc:{},nt=c=>{var m,h,b,A;return c==="idle"?(m=Ge.idleText)!=null?m:An.idle:c==="connecting"?(h=Ge.connectingText)!=null?h:An.connecting:c==="connected"?(b=Ge.connectedText)!=null?b:An.connected:c==="error"?(A=Ge.errorText)!=null?A:An.error:An[c]};function Pt(c,m,h,b){if(b==="idle"&&h.idleLink){c.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=m,A.style.color="inherit",A.style.textDecoration="none",c.appendChild(A)}else c.textContent=m}let Ye=Jm({config:r,showClose:O()}),{wrapper:_e,panel:J,pillRoot:Ve}=Ye.shell,ze=Ye.panelElements,{container:we,body:Se,messagesWrapper:Ze,suggestions:Qe,textarea:Ee,sendButton:$e,sendButtonWrapper:un,composerForm:Dt,statusText:Yt,introTitle:Nr,introSubtitle:H,closeButton:V,iconHolder:pe,headerTitle:Be,headerSubtitle:je,header:De,footer:Le,actionsRow:it,leftActions:It,rightActions:ht}=ze,Rt=ze.setSendButtonMode,P=ze.micButton,ce=ze.micButtonWrapper,Me=ze.attachmentButton,Et=ze.attachmentButtonWrapper,et=ze.attachmentInput,Ut=ze.attachmentPreviewsContainer;we.classList.add("persona-relative"),Se.classList.add("persona-relative");let bn=12,bt=()=>{var c;return(c=be.label)!=null?c:""},xt=()=>{var c;return(c=be.iconName)!=null?c:"arrow-down"},Wt=()=>be.enabled!==!1,vt=()=>{var c;return(c=le.mode)!=null?c:"follow"},mn=()=>{var c;return(c=le.anchorTopOffset)!=null?c:16},$t=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");$t.type="button",$t.style.display="none",$t.setAttribute("data-persona-scroll-to-bottom","true");let On=y("span","persona-flex persona-items-center"),En=y("span",""),Tn=y("span","");Tn.setAttribute("data-persona-scroll-to-bottom-count",""),Tn.style.display="none",$t.append(On,En,Tn),we.appendChild($t);let xn=y("div","persona-stream-anchor-spacer");xn.setAttribute("aria-hidden","true"),xn.setAttribute("data-persona-anchor-spacer",""),xn.style.flexShrink="0",xn.style.pointerEvents="none",xn.style.height="0px",Se.appendChild(xn);let Mn=()=>{let m=Le.style.display==="none"?0:Le.offsetHeight;$t.style.bottom=`${m+bn}px`};Mn();let cr=()=>{let c=!!bt();$t.setAttribute("aria-label",bt()||"Jump to latest"),$t.title=bt(),$t.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),On.innerHTML="";let m=me(xt(),"14px","currentColor",2);m?(On.appendChild(m),On.style.display=""):On.style.display="none",En.textContent=bt(),En.style.display=c?"":"none"};cr();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=wo({config:r,showClose:O()});return Cs(we,m,r),m.header},onClose:()=>qt(!1,"user")});if(c){let m=we.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),De=c,Ye.header.element=c)}}let Or=()=>{var m,h,b,A;if(!K)return;if(X=!0,!ve&&K&&(ve=gg({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>dr(),config:r,plugins:o,getThroughput:()=>{var B;return(B=G==null?void 0:G.getMetric())!=null?B:{status:"idle"}}})),ve&&(Se.style.display="none",(m=Le.parentNode)==null||m.insertBefore(ve.element,Le),ve.update()),pt){pt.style.boxShadow=`inset 0 0 0 1.5px ${Wn.actionIconColor}`;let B=(A=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:A.toggleButtonActive;B&&B.split(/\s+/).forEach(z=>z&&pt.classList.add(z))}let c=()=>{if(!X)return;let B=Date.now();B-Re>=200&&(ve==null||ve.update(),Re=B),ie=requestAnimationFrame(c)};Re=0,ie=requestAnimationFrame(c),zn(),i.emit("eventStream:opened",{timestamp:Date.now()})},dr=()=>{var c,m,h;if(X){if(X=!1,ve&&ve.element.remove(),Se.style.display="",pt){pt.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(A=>A&&pt.classList.remove(A))}ie!==null&&(cancelAnimationFrame(ie),ie=null),zn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},pt=null;if(ne){let c=(Xc=(Qc=r.features)==null?void 0:Qc.eventStream)==null?void 0:Xc.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:"");pt=y("button",m),pt.style.width="28px",pt.style.height="28px",pt.style.color=Wn.actionIconColor,pt.type="button",pt.setAttribute("aria-label","Event Stream"),pt.title="Event Stream";let h=me("activity","18px","currentColor",1.5);h&&pt.appendChild(h);let b=ze.clearChatButtonWrapper,A=ze.closeButtonWrapper,B=b||A;B&&B.parentNode===De?De.insertBefore(pt,B):De.appendChild(pt),pt.addEventListener("click",()=>{X?dr():Or()})}let So=c=>{var A,B,z,_,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(A=c.querySelector("[data-persona-composer-attachment-previews]"))!=null?A: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 se=c.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(h,se):c.insertBefore(h,c.firstChild)}if(!((B=c.querySelector("[data-persona-composer-attachment-input]"))!=null?B:c.querySelector('input[type="file"]'))){let se=y("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((z=m.allowedTypes)!=null?z:Gr).join(","),se.multiple=((_=m.maxFiles)!=null?_:4)>1,se.style.display="none",se.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(se)}},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 z;if(!$||$.isStreaming())return;let b=h.trim(),A=(z=wt==null?void 0:wt.hasAttachments())!=null?z:!1;if(!b&&!A)return;Zl();let B;A&&(B=[],B.push(...wt.getContentParts()),b&&B.push($a(b))),$.sendMessage(b,{contentParts:B}),A&&wt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{et==null||et.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:((Yc=r.voiceRecognition)==null?void 0:Yc.enabled)===!0?()=>{xr==null||xr()}:void 0});m&&(Ye.replaceComposer(m),Le=Ye.composer.footer)}let Eo=c=>{let m=(...ae)=>{for(let Y of ae){let ye=c.querySelector(Y);if(ye)return ye}return null},h=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),A=c.querySelector("[data-persona-composer-submit]"),B=c.querySelector("[data-persona-composer-mic]"),z=c.querySelector("[data-persona-composer-status]");h&&(Dt=h),b&&(Ee=b),A&&($e=A),B&&(P=B,ce=B.parentElement),z&&(Yt=z);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Qe=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(Me=D,Et=D.parentElement),et=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ut=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(it=se)};So(Le),Eo(Le);let Hn=(rd=(Zc=r.layout)==null?void 0:Zc.contentMaxWidth)!=null?rd:W()?(nd=(td=(ed=r.launcher)==null?void 0:ed.composerBar)==null?void 0:td.contentMaxWidth)!=null?nd:"720px":void 0;if(Hn&&(Ze.style.maxWidth=Hn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),Hn&&Dt&&!W()&&(Dt.style.maxWidth=Hn,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Hn&&Qe&&!W()&&(Qe.style.maxWidth=Hn,Qe.style.marginLeft="auto",Qe.style.marginRight="auto"),Hn&&Ut&&!W()&&(Ut.style.maxWidth=Hn,Ut.style.marginLeft="auto",Ut.style.marginRight="auto"),(od=r.attachments)!=null&&od.enabled&&et&&Ut){wt=vs.fromConfig(r.attachments),wt.setPreviewsContainer(Ut),et.addEventListener("change",h=>{let b=h.target;wt==null||wt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=Lg(c);we.appendChild(m)}(()=>{var b,A;let c=(A=(b=r.layout)==null?void 0:b.slots)!=null?A:{},m=B=>{switch(B){case"body-top":return we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return Qe;case"composer":return Dt;case"footer-bottom":return Yt;default:return null}},h=(B,z)=>{var _;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")De.insertBefore(z,De.firstChild);else if(B==="header-right")De.appendChild(z);else{let D=De.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(z,D.nextSibling):De.appendChild(z)}break;case"body-top":{let D=Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(z):Se.insertBefore(z,Se.firstChild);break}case"body-bottom":Se.appendChild(z);break;case"footer-top":Qe.replaceWith(z);break;case"footer-bottom":Yt.replaceWith(z);break;default:break}};for(let[B,z]of Object.entries(c))if(z)try{let _=z({config:r,defaultContent:()=>m(B)});_&&h(B,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,_)}})();let Xr=c=>{var z,_;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 A=b.getAttribute("data-message-id");if(!A)return;let B=h.getAttribute("data-bubble-type");if(B==="reasoning")Ss.has(A)?Ss.delete(A):Ss.add(A),eg(A,b);else if(B==="tool")Es.has(A)?Es.delete(A):Es.add(A),tg(A,b,r);else if(B==="approval"){let D=r.approval!==!1?r.approval:void 0,se=((z=D==null?void 0:D.detailsDisplay)!=null?z:"collapsed")==="expanded",ae=(_=Go.get(A))!=null?_:se;Go.set(A,!ae),sg(A,b,r)}Tr.delete(A)};Ze.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Xr(c))}),Ze.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Xr(c))}),Ze.addEventListener("copy",c=>{let{clipboardData:m}=c;if(!m)return;let h=Ze.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let A=b.toString(),B=Lm(A);!B||B===A||(m.setData("text/plain",B),c.preventDefault())});let Fr=new Map,Yr=null,Zr="idle",To={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Mo=(c,m)=>{let{icon:h,label:b}=To[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 A=me(h,14,"currentColor",2);A&&(c.innerHTML="",c.appendChild(A))},eo=()=>{Ze.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;Mo(m,b&&b===Yr?Zr:"idle")})};Ze.addEventListener("click",c=>{var z;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 A=b.getAttribute("data-actions-for");if(!A)return;let B=h.getAttribute("data-action");if(B==="copy"){let D=$.getMessages().find(se=>se.id===A);if(D&&ge.onCopy){let se=D.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let ae=me("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=me("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),ge.onCopy(D)}}else if(B==="read-aloud")$.toggleReadAloud(A);else if(B==="upvote"||B==="downvote"){let D=((z=Fr.get(A))!=null?z:null)===B,se=B==="upvote"?"thumbs-up":"thumbs-down";if(D){Fr.delete(A),h.classList.remove("persona-message-action-active");let ae=me(se,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=B==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${ae}"]`);if(Y){Y.classList.remove("persona-message-action-active");let Ue=me(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(Y.innerHTML="",Y.appendChild(Ue))}Fr.set(A,B),h.classList.add("persona-message-action-active");let ye=me(se,14,"currentColor",2);ye&&(ye.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ye)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=$.getMessages().find(tt=>tt.id===A);Ce&&ge.onFeedback&&ge.onFeedback({type:B,messageId:Ce.id,message:Ce})}}}),Ze.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 A=b.getAttribute("data-message-id");if(!A)return;let B=h.getAttribute("data-approval-action");if(!B)return;let z=B==="approve"?"approved":"denied",D=$.getMessages().find(ae=>ae.id===A);if(!(D!=null&&D.approval))return;let se=b.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?$.resolveWebMcpApproval(A,z):$.resolveApproval(D.approval,z)});let yt=null,Fn=null,_n={artifacts:[],selectedId:null},kn=!1,Ct={current:null};Ze.addEventListener("click",c=>{var Y,ye,Ne,Ce,tt;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Ne=(ye=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:Ne.call(ye,{type:"download",artifactId:b}))===!0)return;let B=$.getArtifactById(b),z=B==null?void 0:B.markdown,_=(B==null?void 0:B.title)||"artifact";if(!z){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 ke=$.getMessages().find(qe=>qe.id===rt);if(ke!=null&&ke.rawContent)try{let qe=JSON.parse(ke.rawContent);z=(Ce=qe==null?void 0:qe.props)==null?void 0:Ce.markdown,_=((tt=qe==null?void 0:qe.props)==null?void 0:tt.title)||_}catch{}}}if(!z)return;let D=new Blob([z],{type:"text/markdown"}),se=URL.createObjectURL(D),ae=document.createElement("a");ae.href=se,ae.download=`${_}.md`,ae.click(),URL.revokeObjectURL(se)}),Ze.addEventListener("click",c=>{var B,z,_;let h=c.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(z=(B=r.features)==null?void 0:B.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:_.call(z,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),kn=!1,$.selectArtifact(b),Bn())}),Ze.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=ze.composerOverlay,Yn=(c,m,h)=>{var _,D,se,ae;let b=m.trim();if(!b||!Ct.current)return;let A=(_=c.getAttribute("data-tool-call-id"))!=null?_:"",B=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,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,A);let z=Ct.current.getMessages().find(Y=>{var ye;return((ye=Y.toolCall)==null?void 0:ye.id)===A});(se=z==null?void 0:z.agentMetadata)!=null&&se.awaitingLocalTool?Ct.current.resolveAskUserQuestion(z,(ae=h.structured)!=null?ae:b):Ct.current.sendMessage(b)},$n=c=>{var A;let m=Ct.current;if(!m)return;let h=(A=c.getAttribute("data-tool-call-id"))!=null?A:"",b=m.getMessages().find(B=>{var z;return((z=B.toolCall)==null?void 0:z.id)===h});b&&m.persistAskUserQuestionProgress(b,{answers:Ia(c,b),currentIndex:sr(c)})},to=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),_r=c=>{var A,B,z;if(((B=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let m=sr(c),h=fs(c);if(m>=h-1)return;let b=(z=Ct.current)==null?void 0:z.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});b&&(Ra(c,b,r,m+1),$n(c))};Xn.addEventListener("click",c=>{var B,z,_,D,se,ae,Y,ye,Ne,Ce,tt,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 A=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),A==="dismiss"){let Pe=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),$o(Xn,Pe);let ke=(z=Ct.current)==null?void 0:z.getMessages().find(qe=>{var Ke;return((Ke=qe.toolCall)==null?void 0:Ke.id)===Pe});(_=ke==null?void 0:ke.agentMetadata)!=null&&_.awaitingLocalTool&&((D=Ct.current)==null||D.markAskUserQuestionResolved(ke),(se=Ct.current)==null||se.resolveAskUserQuestion(ke,"(dismissed)"));return}if(A==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let ke=b.getAttribute("data-multi-select")==="true",qe=fo(b);if(qe&&ke){let Ke=_o(b)[sr(b)],gt=new Set(Array.isArray(Ke)?Ke:[]);gt.has(Pe)?gt.delete(Pe):gt.add(Pe),ho(b,Array.from(gt)),$n(b);return}if(qe){ho(b,Pe),$n(b),_r(b);return}if(ke){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=qi(b).length===0);return}Yn(b,Pe,{source:"pick",values:[Pe]});return}if(A==="submit-multi"){let Pe=qi(b);if(Pe.length===0)return;Yn(b,Pe.join(", "),{source:"multi",values:Pe});return}if(A==="open-free-text"){let Pe=b.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let ke=Pe.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(A==="focus-free-text"){let Pe=b.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(A==="submit-free-text"){let Pe=b.querySelector('[data-ask-free-text-input="true"]'),ke=(ae=Pe==null?void 0:Pe.value)!=null?ae:"";if(!ke.trim())return;if(fo(b)){ho(b,ke.trim()),$n(b),_r(b);return}Yn(b,ke,{source:"free-text"});return}if(A==="next"||A==="back"){if(!Ct.current)return;let Pe=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",ke=Ct.current.getMessages().find(He=>{var Ie;return((Ie=He.toolCall)==null?void 0:Ie.id)===Pe});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ne=(ye=qe==null?void 0:qe.value)==null?void 0:ye.trim())!=null?Ne:"";if(Ke){let He=_o(b)[sr(b)];(typeof He!="string"||He!==Ke)&&ho(b,Ke)}let gt=A==="next"?1:-1,I=sr(b)+gt;Ra(b,ke,r,I),$n(b);return}if(A==="submit-all"){if(!Ct.current)return;let Pe=(Ce=b.getAttribute("data-tool-call-id"))!=null?Ce:"",ke=Ct.current.getMessages().find(He=>{var Ie;return((Ie=He.toolCall)==null?void 0:Ie.id)===Pe});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ue=(tt=qe==null?void 0:qe.value)==null?void 0:tt.trim())!=null?Ue:"";Ke&&ho(b,Ke);let gt=Ia(b,ke);Ct.current.persistAskUserQuestionProgress(ke,{answers:gt,currentIndex:sr(b)});let I=to(gt);Yn(b,I||"(submitted)",{source:"submit-all",structured:gt});return}if(A==="skip"){if(!Ct.current)return;let Pe=(ct=b.getAttribute("data-tool-call-id"))!=null?ct:"",ke=Ct.current.getMessages().find(Ie=>{var ue;return((ue=Ie.toolCall)==null?void 0:ue.id)===Pe});if(!ke)return;let qe=fo(b),Ke=sr(b),gt=fs(b),I=Ke>=gt-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),$o(Xn,Pe),(rt=ke.agentMetadata)!=null&&rt.awaitingLocalTool&&(Ct.current.markAskUserQuestionResolved(ke),Ct.current.resolveAskUserQuestion(ke,"(dismissed)"));return}ho(b,"");let He=b.querySelector('[data-ask-free-text-input="true"]');if(He&&(He.value=""),I){let Ie=Ia(b,ke),ue=to(Ie);Yn(b,ue||"(skipped)",{source:"submit-all",structured:Ie});return}Ra(b,ke,r,Ke+1),$n(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 A=h.value;if(A.trim()){if(fo(b)){ho(b,A.trim()),$n(b),_r(b);return}Yn(b,A,{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 jn=null,Ht=null,Ln=null,Zn=null,ro=()=>{};function $r(){Zn==null||Zn(),Zn=null}let oo=()=>{var z;if(!jn||!Ht)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((z=e.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){Ht.style.removeProperty("position"),Ht.style.removeProperty("left"),Ht.style.removeProperty("top"),Ht.style.removeProperty("bottom"),Ht.style.removeProperty("width"),Ht.style.removeProperty("z-index");return}let b=jn.firstElementChild;if(!b||b===Ht)return;let A=10;Ht.style.position="absolute",Ht.style.top="0",Ht.style.bottom="0",Ht.style.width=`${A}px`,Ht.style.zIndex="5";let B=b.offsetWidth-A/2;Ht.style.left=`${Math.max(0,B)}px`},he=()=>{},Bn=()=>{var h,b,A,B,z;if(!yt||!lr(r))return;fi(e,r),hi(e,r),he();let c=(B=(A=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:A.narrowHostMaxWidth)!=null?B:520,m=J.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),yt.update(_n),kn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(z=yt.backdrop)==null||z.classList.add("persona-hidden")):_n.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),ro()};if(lr(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(we),yt=yg(r,{onSelect:h=>{var b;return(b=Ct.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{kn=!0,Bn()}}),yt.element.classList.add("persona-hidden"),jn=m,m.appendChild(c),m.appendChild(yt.element),yt.backdrop&&J.appendChild(yt.backdrop),J.appendChild(m),ro=()=>{var b,A,B,z;if(!jn||!yt)return;if(!(((B=(A=(b=r.features)==null?void 0:b.artifacts)==null?void 0:A.layout)==null?void 0:B.resizable)===!0)){Ln==null||Ln(),Ln=null,$r(),Ht&&(Ht.remove(),Ht=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Ht){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,se=(z=D.defaultView)!=null?z:window,ae=Y=>{var ct,rt;if(!yt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Y.preventDefault(),$r();let ye=Y.clientX,Ne=yt.element.getBoundingClientRect().width,Ce=(rt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:rt.layout,tt=Pe=>{let ke=jn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),Ke=qe?0:wg(jn,se),gt=qe?0:_.getBoundingClientRect().width||6,I=Ne-(Pe.clientX-ye),He=Cg(I,ke,Ke,gt,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);yt.element.style.width=`${He}px`,yt.element.style.maxWidth="none",oo()},Ue=()=>{D.removeEventListener("pointermove",tt),D.removeEventListener("pointerup",Ue),D.removeEventListener("pointercancel",Ue),Zn=null;try{_.releasePointerCapture(Y.pointerId)}catch{}};Zn=Ue,D.addEventListener("pointermove",tt),D.addEventListener("pointerup",Ue),D.addEventListener("pointercancel",Ue);try{_.setPointerCapture(Y.pointerId)}catch{}};_.addEventListener("pointerdown",ae),Ht=_,jn.insertBefore(_,yt.element),Ln=()=>{_.removeEventListener("pointerdown",ae)}}if(Ht){let _=_n.artifacts.length>0&&!kn;Ht.classList.toggle("persona-hidden",!_),oo()}},he=()=>{var se,ae,Y,ye,Ne,Ce,tt,Ue,ct,rt,Pe,ke,qe,Ke;if(!M||!yt||((ae=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?ae:!1)||pn(r)&&ir(r).reveal==="emerge")return;let b=(Y=e.ownerDocument.defaultView)!=null?Y:window,A=(Ne=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Ne:!0,B=(tt=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?tt:640;if(A&&b.innerWidth<=B||!vg(r,M))return;let z=(rt=(ct=(Ue=r.launcher)==null?void 0:Ue.width)!=null?ct:r.launcherWidth)!=null?rt:ar,_=(Ke=(qe=(ke=(Pe=r.features)==null?void 0:Pe.artifacts)==null?void 0:ke.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!kn?(J.style.width=_,J.style.maxWidth=_):(J.style.width=z,J.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Bn()}),Fn.observe(J))}else J.appendChild(we),W()&&Ve&&(ze.peekBanner&&Ve.appendChild(ze.peekBanner),Ve.appendChild(Le));e.appendChild(_e),Ve&&e.appendChild(Ve);let Cr=()=>{var He,Ie,ue,Nt,Bt,Gt,ft,zt,Vn,nn,Je,Tt,on,rr,Kn,Ro,Wo,cs,ds,Qt,Ho,co,po,Vr,Bo,gr,Ir,Xe;if(W()){J.style.width="100%",J.style.maxWidth="100%";let Ot=(Ie=(He=r.launcher)==null?void 0:He.composerBar)!=null?Ie:{},Kt=_e.dataset.state==="expanded",Ft=(ue=Ot.expandedSize)!=null?ue:"anchored";if(!(Kt&&Ft!=="fullscreen")){we.style.background="",we.style.border="",we.style.borderRadius="",we.style.overflow="",we.style.boxShadow="";return}let Mt=(Bt=(Nt=r.theme)==null?void 0:Nt.components)==null?void 0:Bt.panel,jt=oa(r),fn=(yn,or)=>{var uo;return yn==null||yn===""?or:(uo=ws(jt,yn))!=null?uo:yn},Gn="1px solid var(--persona-border)",Rr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",hn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";we.style.background="var(--persona-surface, #ffffff)",we.style.border=fn(Mt==null?void 0:Mt.border,Gn),we.style.borderRadius=fn(Mt==null?void 0:Mt.borderRadius,hn),we.style.boxShadow=fn(Mt==null?void 0:Mt.shadow,Rr),we.style.overflow="hidden";return}let c=pn(r),m=(ft=(Gt=r.launcher)==null?void 0:Gt.sidebarMode)!=null?ft:!1,h=c||m||((Vn=(zt=r.launcher)==null?void 0:zt.fullHeight)!=null?Vn:!1),b=((nn=r.launcher)==null?void 0:nn.enabled)===!1,A=(Tt=(Je=r.theme)==null?void 0:Je.components)==null?void 0:Tt.panel,B=oa(r),z=(Ot,Kt)=>{var Ft;return Ot==null||Ot===""?Kt:(Ft=ws(B,Ot))!=null?Ft:Ot},_=(on=e.ownerDocument.defaultView)!=null?on:window,D=(Kn=(rr=r.launcher)==null?void 0:rr.mobileFullscreen)!=null?Kn:!0,se=(Wo=(Ro=r.launcher)==null?void 0:Ro.mobileBreakpoint)!=null?Wo:640,ae=_.innerWidth<=se,Y=D&&ae&&M,ye=(ds=(cs=r.launcher)==null?void 0:cs.position)!=null?ds:"bottom-left",Ne=ye==="bottom-left"||ye==="top-left",Ce=(Ho=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?Ho:Sn,tt=m||Y?"none":"1px solid var(--persona-border)",Ue=Y?"none":m?Ne?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!Y&&(Ue="none",tt="none");let ct=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=z(A==null?void 0:A.border,tt),Pe=z(A==null?void 0:A.shadow,Ue),ke=z(A==null?void 0:A.borderRadius,ct),qe=Se.scrollTop;e.style.cssText="",_e.style.cssText="",J.style.cssText="",we.style.cssText="",Se.style.cssText="",Le.style.cssText="";let Ke=()=>{var Kt;if(qe<=0)return;((Kt=Se.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(Se.scrollTop===qe)return;let Ft=Se.scrollHeight-Se.clientHeight;Ft<=0||(Se.scrollTop=Math.min(qe,Ft))})};if(Y){_e.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"),_e.style.cssText=`
33
35
  position: fixed !important;
34
36
  inset: 0 !important;
35
37
  width: 100% !important;
@@ -41,7 +43,7 @@ _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]
41
43
  flex-direction: column !important;
42
44
  z-index: ${Ce} !important;
43
45
  background-color: var(--persona-surface, #ffffff) !important;
44
- `,ce.style.cssText=`
46
+ `,J.style.cssText=`
45
47
  position: relative !important;
46
48
  display: flex !important;
47
49
  flex-direction: column !important;
@@ -54,7 +56,7 @@ _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]
54
56
  padding: 0 !important;
55
57
  box-shadow: none !important;
56
58
  border-radius: 0 !important;
57
- `,de.style.cssText=`
59
+ `,we.style.cssText=`
58
60
  display: flex !important;
59
61
  flex-direction: column !important;
60
62
  flex: 1 1 0% !important;
@@ -65,11 +67,11 @@ _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]
65
67
  overflow: hidden !important;
66
68
  border-radius: 0 !important;
67
69
  border: none !important;
68
- `,we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",Ie.style.flexShrink="0",W=!0,Ge();return}let yt=(io=(ao=r==null?void 0:r.launcher)==null?void 0:ao.width)!=null?io:r==null?void 0:r.launcherWidth,L=yt!=null?yt:sr;if(!u&&!l)b&&h?(ce.style.width="100%",ce.style.maxWidth="100%"):(ce.style.width=L,ce.style.maxWidth=L);else if(l)if(ar(r).reveal==="emerge"){let Nt=ar(r).width;ce.style.width=Nt,ce.style.maxWidth=Nt}else ce.style.width="100%",ce.style.maxWidth="100%";if(wr(),ce.style.boxShadow=We,ce.style.borderRadius=Le,de.style.border=at,de.style.borderRadius=Le,l&&!Y&&(A==null?void 0:A.border)===void 0&&(de.style.border="none",ar(r).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.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%"),Ne.style.display="flex",Ne.style.flexDirection="column",Ne.style.flex="1 1 0%",Ne.style.minHeight="0",Ne.style.maxHeight="100%",Ne.style.height="100%",b&&(Ne.style.overflow="hidden"),ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.height="100%",ce.style.overflow="hidden",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",Ie.style.flexShrink="0"),Ne.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"),!u&&!b&&!l&&((Ur=hr[be])!=null?Ur:hr["bottom-right"]).split(" ").forEach(Nt=>Ne.classList.add(Nt)),u){let Ft=(ur=(Io=r.launcher)==null?void 0:Io.sidebarWidth)!=null?ur:"420px";Ne.style.cssText=`
70
+ `,Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.overflowY="auto",Le.style.flexShrink="0",j=!0,Ke();return}let gt=(po=(co=r==null?void 0:r.launcher)==null?void 0:co.width)!=null?po:r==null?void 0:r.launcherWidth,I=gt!=null?gt:ar;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(ir(r).reveal==="emerge"){let Kt=ir(r).width;J.style.width=Kt,J.style.maxWidth=Kt}else J.style.width="100%",J.style.maxWidth="100%";if(he(),J.style.boxShadow=Pe,J.style.borderRadius=ke,we.style.border=rt,we.style.borderRadius=ke,c&&!Y&&(A==null?void 0:A.border)===void 0&&(we.style.border="none",ir(r).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.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%"),_e.style.display="flex",_e.style.flexDirection="column",_e.style.flex="1 1 0%",_e.style.minHeight="0",_e.style.maxHeight="100%",_e.style.height="100%",b&&(_e.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",we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.overflow="hidden",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.overflowY="auto",Le.style.flexShrink="0"),_e.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&&((Vr=br[ye])!=null?Vr:br["bottom-right"]).split(" ").forEach(Kt=>_e.classList.add(Kt)),m){let Ot=(gr=(Bo=r.launcher)==null?void 0:Bo.sidebarWidth)!=null?gr:"420px";_e.style.cssText=`
69
71
  position: fixed !important;
70
72
  top: 0 !important;
71
73
  bottom: 0 !important;
72
- width: ${Ft} !important;
74
+ width: ${Ot} !important;
73
75
  height: 100vh !important;
74
76
  max-height: 100vh !important;
75
77
  margin: 0 !important;
@@ -77,8 +79,8 @@ _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]
77
79
  display: flex !important;
78
80
  flex-direction: column !important;
79
81
  z-index: ${Ce} !important;
80
- ${Oe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
81
- `,ce.style.cssText=`
82
+ ${Ne?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
+ `,J.style.cssText=`
82
84
  position: relative !important;
83
85
  display: flex !important;
84
86
  flex-direction: column !important;
@@ -89,9 +91,9 @@ _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]
89
91
  min-height: 0 !important;
90
92
  margin: 0 !important;
91
93
  padding: 0 !important;
92
- box-shadow: ${We} !important;
93
- border-radius: ${Le} !important;
94
- `,ce.style.setProperty("width","100%","important"),ce.style.setProperty("max-width","100%","important"),de.style.cssText=`
94
+ box-shadow: ${Pe} !important;
95
+ border-radius: ${ke} !important;
96
+ `,J.style.setProperty("width","100%","important"),J.style.setProperty("max-width","100%","important"),we.style.cssText=`
95
97
  display: flex !important;
96
98
  flex-direction: column !important;
97
99
  flex: 1 1 0% !important;
@@ -100,29 +102,29 @@ _Details: ${n.message}_`:r}var Js=e=>({isError:!0,content:[{type:"text",text:e}]
100
102
  min-height: 0 !important;
101
103
  max-height: 100% !important;
102
104
  overflow: hidden !important;
103
- border-radius: ${Le} !important;
104
- border: ${at} !important;
105
- `,Ie.style.cssText=`
105
+ border-radius: ${ke} !important;
106
+ border: ${rt} !important;
107
+ `,Le.style.cssText=`
106
108
  flex-shrink: 0 !important;
107
109
  border-top: none !important;
108
110
  padding: 8px 16px 12px 16px !important;
109
- `}if(!b&&!l){let Ft="max-height: -moz-available !important; max-height: stretch !important;",Nt=u?"":"padding-top: 1.25em !important;",gt=u?"":`z-index: ${(an=(Ze=r.launcher)==null?void 0:Ze.zIndex)!=null?an:wn} !important;`;Ne.style.cssText+=Ft+Nt+gt}Ge()};ye(),jo(e,r),ui(e,r),mi(e,r);let ct=[];ct.push(()=>{document.removeEventListener("keydown",Zr)});let Jt=null,on=null;ct.push(()=>{Jt==null||Jt(),Jt=null,on==null||on(),on=null}),Nn&&ct.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),ct.push(()=>{An==null||An(),An=null,Dr(),Ht&&(Ht.remove(),Ht=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),ke&&ct.push(()=>{qe!==null&&(cancelAnimationFrame(qe),qe=null),G==null||G.destroy(),G=null,le==null||le.destroy(),le=null,Q=null});let Cr=null,As=()=>{Cr&&(Cr(),Cr=null),r.colorScheme==="auto"&&(Cr=al(()=>{jo(e,r)}))};As(),ct.push(()=>{Cr&&(Cr(),Cr=null)});let Nr=(nd=r.features)==null?void 0:nd.streamAnimation;if(Nr!=null&&Nr.type&&Nr.type!=="none"){let l=na(Nr.type,Nr.plugins);l&&(cl(l,e),ct.push(()=>Hm(e)))}let Ao=Zm(Lt),Sr=null,F,Ko=l=>{var b,A;if(!F)return;let u=l!=null?l:F.getMessages(),h=((A=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:A.enabled)!==!1?zi(u):null;h?Ao.render(h,F,Ae,u,r.suggestionChipsConfig,{agentPushed:!0}):u.some(R=>R.role==="user")?Ao.render([],F,Ae,u):Ao.render(r.suggestionChips,F,Ae,u,r.suggestionChipsConfig)},Ar=!1,Tr=Tm(),Or=new Map,Er=new Map,cr=new Map,Go=0,ga=Bo()!==null,jn=Ka(),Un=0,dr=null,pr=!1,To=!1,Fr=0,yn=null,Mr=null,Jo=!1,Eo=!1,Qo=null,fa=4,Xo=24,ha=80,Yo=new Map,ft={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ts=(od=(rd=r.voiceRecognition)==null?void 0:rd.autoResume)!=null?od:!1,er=l=>{o.emit("voice:state",{active:ft.active,source:l,timestamp:Date.now()})},Rn=()=>{g(l=>({...l,voiceState:{active:ft.active,timestamp:Date.now(),manuallyDeactivated:ft.manuallyDeactivated}}))},ya=()=>{var b,A;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=Hl(d.voiceState),u=!!l.active,h=Number((A=l.timestamp)!=null?A:0);ft.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Tv&&setTimeout(()=>{var R,q;ft.active||(ft.manuallyDeactivated=!1,((q=(R=r.voiceRecognition)==null?void 0:R.provider)==null?void 0:q.type)==="runtype"?F.toggleVoice().then(()=>{ft.active=F.isVoiceActive(),er("restore"),F.isVoiceActive()&&ts()}):va("restore"))},1e3)},ba=()=>F?hg(F.getMessages()).filter(l=>!l.__skipPersist):[];function no(l){if(!(i!=null&&i.save))return;let h={messages:l?hg(l):F?ba():[],metadata:d,artifacts:On.artifacts,selectedArtifactId:On.selectedId};try{let b=i.save(h);b instanceof Promise&&b.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let rt=null,w=()=>Ne.querySelector("#persona-scroll-container")||we,$=()=>{rt!==null&&(cancelAnimationFrame(rt),rt=null),pr=!1},_=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),To=!1,$()},K=()=>{Fr>0?(Cn.textContent=String(Fr),Cn.style.display="",lt.setAttribute("aria-label",`${Zt()||"Jump to latest"} (${Fr} new)`)):(Cn.textContent="",Cn.style.display="none",lt.setAttribute("aria-label",Zt()||"Jump to latest"))},fe=()=>{Fr!==0&&(Fr=0,K())},_e=()=>nt()==="follow"?!jn.isFollowing():!Uo(we,Xo),Ye=()=>{if(!Wt()||ee){lt.parentNode&&lt.remove(),lt.style.display="none";return}lt.parentNode!==de&&de.appendChild(lt),Pn();let u=Vr(we)>0&&_e();u||fe(),lt.style.display=u?"":"none"},Et=()=>{jn.pause()&&(_(),Ye())},_r=()=>{jn.resume(),fe(),Ye()},Wn=(l=!1)=>{nt()==="follow"&&jn.isFollowing()&&(!l&&!Ar||(dr!==null&&(cancelAnimationFrame(dr),dr=null),To=!0,dr=requestAnimationFrame(()=>{dr=null,To=!1,jn.isFollowing()&&mn(w(),l?220:140)})))},qn=(l,u,h,b=()=>!0)=>{let A=l.scrollTop,R=u(),q=R-A;$();let O=performance.now();pr=!0;let H=se=>1-Math.pow(1-se,3),oe=se=>{if(!b()){$();return}let Y=u();Y!==R&&(R=Y,q=R-A);let be=se-O,Oe=Math.min(be/h,1),Ce=H(Oe),ot=A+q*Ce;l.scrollTop=ot,Un=l.scrollTop,Oe<1?rt=requestAnimationFrame(oe):(l.scrollTop=R,Un=l.scrollTop,rt=null,pr=!1)};rt=requestAnimationFrame(oe)},mn=(l,u=500)=>{let h=Vr(l)-l.scrollTop;if(Math.abs(h)<1){Un=l.scrollTop;return}if(Math.abs(h)>=ha){$(),pr=!0,l.scrollTop=Vr(l),Un=l.scrollTop,pr=!1;return}qn(l,()=>Vr(l),u,()=>jn.isFollowing())},ro=()=>{let l=w();pr=!0,l.scrollTop=Vr(l),Un=l.scrollTop,pr=!1,Ye()},$r=l=>{en.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},gn=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),$(),yn=null,en.style.height="0px"},Hn=l=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var oe;Mr=null;let u=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${u}"]`);if(!h)return;let b=0,A=h;for(;A&&A!==we;)b+=A.offsetTop,A=A.offsetParent;let R=(oe=yn==null?void 0:yn.spacerHeight)!=null?oe:0,q=we.scrollHeight-R,{targetScrollTop:O,spacerHeight:H}=Pm({anchorOffsetTop:b,topOffset:Rt(),viewportHeight:we.clientHeight,contentHeight:q});yn={initialSpacerHeight:H,contentHeightAtAnchor:q,spacerHeight:H},$r(H),qn(we,()=>O,220)})},zn=()=>{if(nt()==="follow"){if(!jn.isFollowing()||Uo(we,1))return;Wn(!Ar);return}if(yn&&yn.initialSpacerHeight>0){let l=we.scrollHeight-yn.spacerHeight,u=Im({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});u!==yn.spacerHeight&&$r(u)}Ye()},Yg=l=>{let u=nt();u==="follow"?(_r(),Wn(!0)):u==="anchor-top"&&Hn(l)},Zg=l=>{let u=new Map;l.forEach(h=>{let b=Yo.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(o.emit("assistant:message",h),!Eo&&nt()!=="anchor-top"&&_e()&&(Fr+=1,K(),Ye())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&o.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&o.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):o.emit("approval:requested",{approval:h.approval,message:h}))}),Yo.clear(),u.forEach((h,b)=>{Yo.set(b,h)})},ef=(l,u,h)=>{var at,We,Le,Ue,Ge,yt;let b=document.createElement("div"),R=(()=>{var De;let L=s.find(He=>He.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(L,De)=>De==null?!1:typeof De=="string"?(L.textContent=De,!0):(L.appendChild(De),!0),O=new Set,H=new Set,oe=s.some(L=>L.renderAskUserQuestion),se=[],Y=[],be=r.enableComponentStreaming!==!1,Oe=s.some(L=>L.renderApproval)&&r.approval!==!1,Ce=[];if(u.forEach(L=>{var Qe,Mt,nn,rr,Kn,ko,Lo,rs,os,zt,Po,ao,io,Ur,Io,ur;O.add(L.id);let De=oe&&co(L),He=Oe&&L.variant==="approval"&&!!L.approval,ge=!De&&L.role==="assistant"&&!L.variant&&be&&Pl(L);if(!He&&cr.has(L.id)){let Ze=l.querySelector(`#wrapper-${L.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),cr.delete(L.id)}if(!ge&&Er.has(L.id)){let Ze=l.querySelector(`#wrapper-${L.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Er.delete(L.id)}let Dt=co(L)?`:${(Qe=L.agentMetadata)!=null&&Qe.askUserQuestionAnswered?"a":"u"}:${(Mt=L.agentMetadata)!=null&&Mt.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Bt=Am(L,Go)+Dt,Ut=De||He||ge?null:Em(Tr,L.id,Bt);if(Ut){b.appendChild(Ut.cloneNode(!0)),co(L)&&((nn=L.toolCall)!=null&&nn.id)&&((rr=L.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((Kn=L.agentMetadata)!=null&&Kn.askUserQuestionAnswered)&&(H.add(L.toolCall.id),js(L,r,X.composerOverlay));return}let vt=null,$t=s.find(Ze=>!!(L.variant==="reasoning"&&Ze.renderReasoning||L.variant==="tool"&&Ze.renderToolCall||!L.variant&&Ze.renderMessage)),Vn=(ko=r.layout)==null?void 0:ko.messages;if(co(L)&&((Lo=L.agentMetadata)==null?void 0:Lo.askUserQuestionAnswered)===!0){Or.delete(L.id);let Ze=l.querySelector(`#wrapper-${L.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(Pa(L)&&((os=(rs=r.features)==null?void 0:rs.suggestReplies)==null?void 0:os.enabled)!==!1)return;if(co(L)&&((Po=(zt=r.features)==null?void 0:zt.askUserQuestion)==null?void 0:Po.enabled)!==!1){let Ze=s.find(an=>typeof an.renderAskUserQuestion=="function");if(Ze&&St.current){let an=Or.get(L.id),Ft=an!==Bt,Nt=null;if(Ft){let{payload:Ct,complete:bn}=po(L),Tn=L.id,Lr=()=>{var pn;return(pn=St.current)==null?void 0:pn.getMessages().find(En=>En.id===Tn)};Nt=Ze.renderAskUserQuestion({message:L,payload:Ct,complete:bn,resolve:pn=>{var Mn;let En=Lr();En&&((Mn=St.current)==null||Mn.resolveAskUserQuestion(En,pn))},dismiss:()=>{var En,Mn,Ro;let pn=Lr();(En=pn==null?void 0:pn.agentMetadata)!=null&&En.awaitingLocalTool&&((Mn=St.current)==null||Mn.markAskUserQuestionResolved(pn),(Ro=St.current)==null||Ro.resolveAskUserQuestion(pn,"(dismissed)"))},config:r})}let gt=an!=null;if(Ft&&Nt===null&&!gt){((ao=L.agentMetadata)==null?void 0:ao.awaitingLocalTool)===!0&&!((io=L.agentMetadata)!=null&&io.askUserQuestionAnswered)&&(H.add(L.toolCall.id),js(L,r,X.composerOverlay));return}let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${L.id}`,Vt.setAttribute("data-wrapper-id",L.id),Vt.setAttribute("data-ask-plugin-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),b.appendChild(Vt),se.push({messageId:L.id,fingerprint:Bt,bubble:Nt});return}else{((Ur=L.agentMetadata)==null?void 0:Ur.awaitingLocalTool)===!0&&!((Io=L.agentMetadata)!=null&&Io.askUserQuestionAnswered)&&(H.add(L.toolCall.id),js(L,r,X.composerOverlay));return}}else if(He){let Ze=s.find(gt=>typeof gt.renderApproval=="function"),Ft=cr.get(L.id)!==Bt,Nt=null;if(Ft&&(Ze!=null&&Ze.renderApproval)){let gt=L.id,Vt=(Ct,bn)=>{var Lr,pn,En;let Tn=(Lr=St.current)==null?void 0:Lr.getMessages().find(Mn=>Mn.id===gt);Tn!=null&&Tn.approval&&(Tn.approval.toolType==="webmcp"?(pn=St.current)==null||pn.resolveWebMcpApproval(Tn.id,Ct):(En=St.current)==null||En.resolveApproval(Tn.approval,Ct,bn))};Nt=Ze.renderApproval({message:L,defaultRenderer:()=>di(L,r),config:r,approve:Ct=>Vt("approved",Ct),deny:Ct=>Vt("denied",Ct)})}if(Ft&&Nt===null){let gt=l.querySelector(`#wrapper-${L.id}`);gt==null||gt.removeAttribute("data-preserve-runtime"),cr.delete(L.id),vt=di(L,r)}else{let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${L.id}`,gt.setAttribute("data-wrapper-id",L.id),gt.setAttribute("data-approval-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),Ce.push({messageId:L.id,fingerprint:Bt,bubble:Nt});return}}else if($t)if(L.variant==="reasoning"&&L.reasoning&&$t.renderReasoning){if(!je)return;vt=$t.renderReasoning({message:L,defaultRenderer:()=>bl(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&$t.renderToolCall){if(!Se)return;vt=$t.renderToolCall({message:L,defaultRenderer:()=>vl(L,r),config:r})}else $t.renderMessage&&(vt=$t.renderMessage({message:L,defaultRenderer:()=>{let Ze=ca(L,h,Vn,r.messageActions,ie,{loadingIndicatorRenderer:R,widgetConfig:r});return L.role!=="user"&&Al(Ze,L,r,F),Ze},config:r}));if(!vt&&ge){let Ze=Il(L);if(Ze){let an=Er.get(L.id),Ft=an!==Bt,Nt=r.wrapComponentDirectiveInBubble!==!1,gt=null;if(Ft){let Vt=Ll(Ze,{config:r,message:L,transform:h});if(Vt)if(Nt){let Ct=document.createElement("div");if(Ct.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ct.id=`bubble-${L.id}`,Ct.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let bn=document.createElement("div");bn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",bn.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ct.appendChild(bn)}Ct.appendChild(Vt),gt=Ct}else{let Ct=document.createElement("div");if(Ct.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ct.id=`bubble-${L.id}`,Ct.setAttribute("data-message-id",L.id),Ct.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let bn=document.createElement("div");bn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",bn.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ct.appendChild(bn)}Ct.appendChild(Vt),gt=Ct}}if(gt||an!=null){let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${L.id}`,Vt.setAttribute("data-wrapper-id",L.id),Vt.setAttribute("data-component-directive-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),Nt||Vt.classList.add("persona-w-full"),b.appendChild(Vt),Y.push({messageId:L.id,fingerprint:Bt,bubble:gt});return}}}if(!vt)if(L.variant==="reasoning"&&L.reasoning){if(!je)return;vt=bl(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!Se)return;vt=vl(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;vt=di(L,r)}else{let Ze=(ur=r.layout)==null?void 0:ur.messages;Ze!=null&&Ze.renderUserMessage&&L.role==="user"?vt=Ze.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):Ze!=null&&Ze.renderAssistantMessage&&L.role==="assistant"?vt=Ze.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):vt=ca(L,h,Ze,r.messageActions,ie,{loadingIndicatorRenderer:R,widgetConfig:r}),L.role!=="user"&&vt&&Al(vt,L,r,F)}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${L.id}`,Xt.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Xt.classList.add("persona-justify-end"),(vt==null?void 0:vt.getAttribute("data-persona-component-directive"))==="true"&&Xt.classList.add("persona-w-full"),Xt.appendChild(vt),Mm(Tr,L.id,Bt,Xt),b.appendChild(Xt)}),X.composerOverlay&&X.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let He=De.getAttribute("data-persona-ask-sheet-for");He&&!H.has(He)&&Oo(X.composerOverlay,He)}),(We=(at=r.features)==null?void 0:at.toolCallDisplay)!=null&&We.grouped){let L=[],De=[];u.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&Se){De.push(He);return}De.length>1&&L.push(De),De=[]}),De.length>1&&L.push(De),L.forEach((He,ge)=>{var Qe,Mt;let Dt=He.map(nn=>Array.from(b.children).find(rr=>rr instanceof HTMLElement&&rr.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Dt.length<2)return;let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-tool-group-${ge}-${He[0].id}`,Bt.setAttribute("data-wrapper-id",`tool-group-${ge}-${He[0].id}`);let Ut=document.createElement("div");Ut.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ut.setAttribute("data-persona-tool-group","true");let vt=document.createElement("div");vt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let $t=`Called ${He.length} tools`,Vn=(Mt=(Qe=r.toolCall)==null?void 0:Qe.renderGroupedSummary)==null?void 0:Mt.call(Qe,{messages:He,toolCalls:He.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:$t,config:r});q(vt,Vn)||(vt.textContent=$t);let Xt=document.createElement("div");Xt.className="persona-tool-group-stack persona-flex persona-flex-col",Ut.append(vt,Xt),Bt.appendChild(Ut),Dt[0].before(Bt),Dt.forEach((nn,rr)=>{let Kn=document.createElement("div");Kn.className="persona-tool-group-item persona-relative",Kn.setAttribute("data-persona-tool-group-item","true"),rr<Dt.length-1&&Kn.setAttribute("data-persona-tool-group-connector","true"),Kn.appendChild(nn),Xt.appendChild(Kn)})})}km(Tr,O);let ot=u.some(L=>L.role==="assistant"&&L.streaming),$e=u[u.length-1],mt=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ar&&u.some(L=>L.role==="user")&&!ot&&!mt){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:bs},De=s.find(ge=>ge.renderLoadingIndicator),He=null;if(De!=null&&De.renderLoadingIndicator&&(He=De.renderLoadingIndicator(L)),He===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(He=r.loadingIndicator.render(L)),He===null&&(He=bs()),He){let ge=document.createElement("div"),Dt=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;ge.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ge.setAttribute("data-typing-indicator","true"),ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ge.appendChild(He);let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id="wrapper-typing-indicator",Bt.setAttribute("data-wrapper-id","typing-indicator"),Bt.appendChild(ge),b.appendChild(Bt)}}if(!Ar&&u.length>0){let L=u[u.length-1],De={config:r,lastMessage:L,messageCount:u.length},He=s.find(Dt=>Dt.renderIdleIndicator),ge=null;if(He!=null&&He.renderIdleIndicator&&(ge=He.renderIdleIndicator(De)),ge===null&&((Ge=r.loadingIndicator)!=null&&Ge.renderIdle)&&(ge=r.loadingIndicator.renderIdle(De)),ge){let Dt=document.createElement("div"),Bt=((yt=r.loadingIndicator)==null?void 0:yt.showBubble)!==!1;Dt.className=Bt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Dt.setAttribute("data-idle-indicator","true"),Dt.appendChild(ge);let Ut=document.createElement("div");Ut.className="persona-flex",Ut.id="wrapper-idle-indicator",Ut.setAttribute("data-wrapper-id","idle-indicator"),Ut.appendChild(Dt),b.appendChild(Ut)}}if(za(l,b),se.length>0)for(let{messageId:L,fingerprint:De,bubble:He}of se){let ge=l.querySelector(`#wrapper-${L}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),Or.set(L,De))}if(Or.size>0)for(let L of Or.keys())O.has(L)||Or.delete(L);if(Y.length>0)for(let{messageId:L,fingerprint:De,bubble:He}of Y){let ge=l.querySelector(`#wrapper-${L}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),Er.set(L,De))}if(Er.size>0)for(let L of Er.keys())O.has(L)||Er.delete(L);if(Ce.length>0)for(let{messageId:L,fingerprint:De,bubble:He}of Ce){let ge=l.querySelector(`#wrapper-${L}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),cr.set(L,De))}if(cr.size>0)for(let L of cr.keys())O.has(L)||cr.delete(L)},Es=(l,u,h)=>{ef(l,u,h),Xr()},Ms=null,tf=()=>{var h;if(Ms)return;let l=b=>{let A=b.composedPath();A.includes(Ne)||et&&A.includes(et)||_t(!1,"user")};Ms=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Vl=()=>{var u;if(!Ms)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("pointerdown",Ms,!0),Ms=null};ct.push(()=>Vl());let ks=null,nf=()=>{var h;if(ks)return;let l=b=>{b.key==="Escape"&&(b.isComposing||_t(!1,"user"))};ks=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Kl=()=>{var u;if(!ks)return;((u=e.ownerDocument)!=null?u:document).removeEventListener("keydown",ks,!0),ks=null};ct.push(()=>Kl());let Ls=!1,Gl=new Set,rf=()=>{var u,h,b,A;let l=(b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((A=r.features)==null?void 0:A.streamAnimation)},Zo=()=>{var mt,at,We,Le;if(!B())return;let l=X.peekBanner,u=X.peekTextNode;if(!l||!u)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(mt=F==null?void 0:F.getMessages())!=null?mt:[],b;for(let Ue=h.length-1;Ue>=0;Ue--){let Ge=h[Ue];if(Ge.role==="assistant"&&Ge.content){b=Ge;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let A=b.content,R=!!b.streaming,q=rf(),O=Qa(q),H=O.type!=="none"?na(O.type,q==null?void 0:q.plugins):null,oe=((at=H==null?void 0:H.isAnimating)==null?void 0:at.call(H,b))===!0,se=H!==null&&(R||oe);se&&H&&!Gl.has(H.name)&&(cl(H,e),Gl.add(H.name));let Y=se&&(H!=null&&H.containerClass)?H.containerClass:null,be=(We=u.dataset.personaPeekStreamClass)!=null?We:null;be&&be!==Y&&(u.classList.remove(be),delete u.dataset.personaPeekStreamClass),Y&&be!==Y&&(u.classList.add(Y),u.dataset.personaPeekStreamClass=Y),se?(u.style.setProperty("--persona-stream-step",`${O.speed}ms`),u.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Oe=se?Xa(A,O.buffer,H,b,R):A;if(se&&O.placeholder==="skeleton"&&R&&(!Oe||!Oe.trim())){let Ue=document.createElement("div"),Ge=oa();Ge.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(Ge),za(u,Ue)}else{let Ue=Math.max(0,Oe.length-100),Ge=Oe.length>100?Oe.slice(-100):Oe,yt=qr(Ge);if(!se||!H){let L=Oe.length>100?`\u2026${Ge}`:Ge;u.textContent!==L&&(u.textContent=L)}else{let L=yt;(H.wrap==="char"||H.wrap==="word")&&(L=ra(yt,H.wrap,`peek-${b.id}`,{skipTags:H.skipTags,startIndex:Ue}));let De=document.createElement("div");if(De.innerHTML=L,H.useCaret&&Ge.length>0){let He=Ya(),ge=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Dt=ge[ge.length-1];Dt!=null&&Dt.parentNode?Dt.parentNode.insertBefore(He,Dt.nextSibling):De.appendChild(He)}za(u,De),(Le=H.onAfterRender)==null||Le.call(H,{container:u,bubble:l,messageId:b.id,message:b,speed:O.speed,duration:O.duration})}}let $e=Ar||Ls;l.classList.toggle("persona-pill-peek--visible",$e)};if(B()){let l=X.peekBanner;if(l){let b=A=>{A.preventDefault(),A.stopPropagation(),_t(!0,"user")};l.addEventListener("pointerdown",b),ct.push(()=>{l.removeEventListener("pointerdown",b)})}let u=()=>{Ls||(Ls=!0,Zo())},h=()=>{Ls&&(Ls=!1,Zo())};ce.addEventListener("pointerenter",u),ce.addEventListener("pointerleave",h),ct.push(()=>{ce.removeEventListener("pointerenter",u),ce.removeEventListener("pointerleave",h)}),et&&(et.addEventListener("pointerenter",u),et.addEventListener("pointerleave",h),ct.push(()=>{et.removeEventListener("pointerenter",u),et.removeEventListener("pointerleave",h)}))}let of=l=>{var be,Oe,Ce,ot,$e,mt,at,We;let u=(Oe=(be=r.launcher)==null?void 0:be.composerBar)!=null?Oe:{},h=(Ce=u.expandedSize)!=null?Ce:"anchored",b=(ot=u.bottomOffset)!=null?ot:"16px",A=u.collapsedMaxWidth,R=($e=u.expandedMaxWidth)!=null?$e:"880px",q=(mt=u.expandedTopOffset)!=null?mt:"5vh",O=(at=u.modalMaxWidth)!=null?at:"880px",H=(We=u.modalMaxHeight)!=null?We:"min(90vh, 800px)",oe="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",Y=Ne.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",et){let Le=et.style;Le.bottom=b,Le.width=A!=null?A:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=O,Y.maxWidth=oe,Y.maxHeight=H,Y.height=H;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${se})`,Y.top=q,Y.width=R,Y.maxWidth=oe}},Ps=()=>{var H,oe,se,Y,be,Oe,Ce,ot;if(!D())return;if(B()){let mt=(se=((oe=(H=r.launcher)==null?void 0:H.composerBar)!=null?oe:{}).expandedSize)!=null?se:"anchored",at=k?"expanded":"collapsed";Ne.dataset.state=at,Ne.dataset.expandedSize=mt,et&&(et.dataset.state=at,et.dataset.expandedSize=mt),Ne.style.removeProperty("display"),Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),of(k),de.style.display=k?"flex":"none",ye(),k?(tf(),nf()):(Vl(),Kl()),Zo();return}let l=dn(r),u=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(be=r.launcher)==null?void 0:be.mobileBreakpoint)!=null?Oe:640,b=(ot=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?ot:!0,A=u.innerWidth<=h,R=b&&A&&C,q=ar(r).reveal;k?(Ne.style.removeProperty("display"),Ne.style.display=l?"flex":"",Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Qt?Qt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(q==="overlay"||q==="push")&&!R?(Ne.style.removeProperty("display"),Ne.style.display="flex",Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ne.style.setProperty("display","none","important"),Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ne.style.display="",Ne.classList.add("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Qt?Qt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},_t=(l,u="user")=>{var R,q;if(!D()||k===l)return;let h=k;k=l,Ps();let b=(()=>{var Ce,ot,$e,mt,at,We,Le,Ue,Ge,yt;let O=(ot=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?ot:!1,H=($e=e.ownerDocument.defaultView)!=null?$e:window,oe=(at=(mt=r.launcher)==null?void 0:mt.mobileFullscreen)!=null?at:!0,se=(Le=(We=r.launcher)==null?void 0:We.mobileBreakpoint)!=null?Le:640,Y=H.innerWidth<=se,be=dn(r)&&oe&&Y,Oe=B()&&((yt=(Ge=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:Ge.expandedSize)!=null?yt:"fullscreen")==="fullscreen";return O||oe&&Y&&C||be||Oe})();if(k&&b){if(!Jt){let O=e.getRootNode(),H=O instanceof ShadowRoot?O.host:e.closest(".persona-host");H&&(Jt=dl(H,(q=(R=r.launcher)==null?void 0:R.zIndex)!=null?q:wn))}on||(on=pl(e.ownerDocument))}else k||(Jt==null||Jt(),Jt=null,on==null||on(),on=null);k&&(Is(),nt()==="follow"?Wn(!0):ro());let A={open:k,source:u,timestamp:Date.now()};k&&!h?o.emit("widget:opened",A):!k&&h&&o.emit("widget:closed",A),o.emit("widget:state",{open:k,launcherEnabled:C,voiceActive:ft.active,streaming:F.isStreaming()})},Ei=l=>{It(l?"stop":"send"),U&&(U.disabled=l),Ao.buttons.forEach(u=>{u.disabled=l}),Ie.dataset.personaComposerStreaming=l?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},Mi=()=>{ft.active||Ae&&Ae.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Mi(),200)});let Jl=()=>{var h,b,A,R,q,O,H,oe,se,Y,be;yr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",hn.textContent=(R=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",Ae.placeholder=(O=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?O:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Oe=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((se=(oe=r.sendButton)==null?void 0:oe.useIcon)!=null&&se)&&!(F!=null&&F.isStreaming())&&(me.textContent=(be=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?be:"Send"),Ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{g(u=>({...u,sessionId:l}))}});let Mo=null,sf=()=>{Mo==null&&(Mo=setInterval(()=>{let l=ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Mo),Mo=null;return}let u=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Wa(u-b))})},100))};F=new Qs(r,{onMessagesChanged(l){var b;Es(ze,l,Pe),sf(),Ko(l),Wn(!Ar),Zg(l);let u=[...l].reverse().find(A=>A.role==="user");l.length===0&&gn(),!Jo||Eo?(Jo=!0,Qo=(b=u==null?void 0:u.id)!=null?b:null):u&&u.id!==Qo&&(Qo=u.id,Yg(u.id));let h=ft.lastUserMessageId;u&&u.id!==h&&(ft.lastUserMessageId=u.id,o.emit("user:message",u)),ft.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),no(l),Zo()},onStatusChanged(l){var b;let u=(b=r.statusIndicator)!=null?b:{};Xe(rn,(A=>{var R,q,O,H;return A==="idle"?(R=u.idleText)!=null?R:vn.idle:A==="connecting"?(q=u.connectingText)!=null?q:vn.connecting:A==="connected"?(O=u.connectedText)!=null?O:vn.connected:A==="error"?(H=u.errorText)!=null?H:vn.error:vn[A]})(l),u,l)},onStreamingChanged(l){Ar=l,Ei(l),F&&Es(ze,F.getMessages(),Pe),l||Wn(!0),Zo()},onVoiceStatusChanged(l){var u,h;if(o.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":jr(),ts();break;case"processing":jr(),pf();break;case"speaking":jr(),uf();break;default:l==="idle"&&F.isBargeInActive()?(jr(),ts(),U==null||U.setAttribute("aria-label","End voice session")):(ft.active=!1,jr(),er("system"),Rn());break}},onArtifactsState(l){On=l,$n(),no()}}),St.current=F;let ki=null;if(F.onReadAloudChange((l,u)=>{var A;Jr=l,Qr=u,Xr();let h=l!=null?l:ki;l&&(ki=l);let b=h&&(A=F.getMessages().find(R=>R.id===h))!=null?A:null;o.emit("message:read-aloud",{messageId:h,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(ki=null)}),Jo=!0,((ad=(sd=r.voiceRecognition)==null?void 0:sd.provider)==null?void 0:ad.type)==="runtype")try{F.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&F.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(le||r.onSSEEvent)&&F.setSSEEventCallback((l,u)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,u),re==null||re.processEvent(l,u),le==null||le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),c&&c.then(l=>{var u,h,b;if(l){if(l.metadata&&(d=Hl(l.metadata),E.syncFromMetadata()),(u=l.messages)!=null&&u.length){Eo=!0;try{F.hydrateMessages(l.messages)}finally{Eo=!1}}(h=l.artifacts)!=null&&h.length&&F.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Ql=()=>{var u,h,b;!B()||k||!((b=(h=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||_t(!0,"auto")},Xl=l=>{var A;if(l.preventDefault(),F.isStreaming()){F.cancel(),re==null||re.reset(),G==null||G.update();return}let u=Ae.value.trim(),h=(A=xt==null?void 0:xt.hasAttachments())!=null?A:!1;if(!u&&!h)return;Ql();let b;h&&(b=[],b.push(...xt.getContentParts()),u&&b.push(Oa(u))),Ae.value="",Ae.style.height="auto",xa(),F.sendMessage(u,{contentParts:b}),h&&xt.clearAttachments()},af=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},Li={...Va},Pi=!1,xa=()=>{Li={...Va}},lf=()=>F.getMessages().filter(l=>l.role==="user").map(l=>{var u;return(u=l.content)!=null?u:""}).filter(l=>l.length>0),cf=l=>{if(!Ae)return;Pi=!0,Ae.value=l,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Pi=!1;let u=Ae.value.length;Ae.setSelectionRange(u,u)},Yl=()=>{Pi||xa()},Zl=l=>{if(Ae){if(af()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=Ae.selectionStart===0&&Ae.selectionEnd===0,h=Sm({direction:l.key==="ArrowUp"?"up":"down",history:lf(),currentValue:Ae.value,atStart:u,state:Li});if(Li=h.state,h.handled){l.preventDefault(),h.value!==void 0&&cf(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(F.isStreaming()){l.preventDefault();return}xa(),l.preventDefault(),me.click()}}},ec=l=>{l.key!=="Escape"||l.isComposing||F.isStreaming()&&l.composedPath().includes(de)&&(F.cancel(),re==null||re.reset(),G==null||G.update(),xa(),l.preventDefault(),l.stopImmediatePropagation())},tc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!xt)return;let u=Mv(l.clipboardData);u.length!==0&&(l.preventDefault(),await xt.handleFiles(u))},tr=null,kr=!1,es=null,ut=null,nc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,va=(l="user")=>{var R,q,O,H,oe,se,Y;if(kr||F.isStreaming())return;let u=nc();if(!u)return;tr=new u;let b=(q=((R=r.voiceRecognition)!=null?R:{}).pauseDuration)!=null?q:2e3;tr.continuous=!0,tr.interimResults=!0,tr.lang="en-US";let A=Ae.value;tr.onresult=be=>{let Oe="",Ce="";for(let $e=0;$e<be.results.length;$e++){let mt=be.results[$e],at=mt[0].transcript;mt.isFinal?Oe+=at+" ":Ce=at}let ot=A+Oe+Ce;Ae.value=ot,es&&clearTimeout(es),(Oe||Ce)&&(es=window.setTimeout(()=>{let $e=Ae.value.trim();$e&&tr&&kr&&(oo(),Ae.value="",Ae.style.height="auto",F.sendMessage($e,{viaVoice:!0}))},b))},tr.onerror=be=>{be.error!=="no-speech"&&oo()},tr.onend=()=>{if(kr){let be=Ae.value.trim();be&&be!==A.trim()&&(Ae.value="",Ae.style.height="auto",F.sendMessage(be,{viaVoice:!0})),oo()}};try{if(tr.start(),kr=!0,ft.active=!0,l!=="system"&&(ft.manuallyDeactivated=!1),er(l),Rn(),U){let be=(O=r.voiceRecognition)!=null?O:{};ut={backgroundColor:U.style.backgroundColor,color:U.style.color,borderColor:U.style.borderColor,iconName:(H=be.iconName)!=null?H:"mic",iconSize:parseFloat((Y=(se=be.iconSize)!=null?se:(oe=r.sendButton)==null?void 0:oe.size)!=null?Y:"40")||24};let Oe=be.recordingBackgroundColor,Ce=be.recordingIconColor,ot=be.recordingBorderColor;if(U.classList.add("persona-voice-recording"),U.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",U.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let $e=U.querySelector("svg");$e&&$e.setAttribute("stroke",Ce)}ot&&(U.style.borderColor=ot),U.setAttribute("aria-label","Stop voice recognition")}}catch{oo("system")}},oo=(l="user")=>{if(kr){if(kr=!1,es&&(clearTimeout(es),es=null),tr){try{tr.stop()}catch{}tr=null}if(ft.active=!1,er(l),Rn(),U){if(U.classList.remove("persona-voice-recording"),ut){U.style.backgroundColor=ut.backgroundColor,U.style.color=ut.color,U.style.borderColor=ut.borderColor;let u=U.querySelector("svg");u&&u.setAttribute("stroke",ut.color||"currentColor"),ut=null}U.setAttribute("aria-label","Start voice recognition")}}},df=(l,u)=>{var at,We,Le,Ue,Ge,yt,L,De,He;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((at=l==null?void 0:l.provider)==null?void 0:at.type)==="runtype",A=((We=l==null?void 0:l.provider)==null?void 0:We.type)==="custom";if(!(h||b||A))return null;let q=y("div","persona-send-button-wrapper"),O=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let H=(Le=l==null?void 0:l.iconName)!=null?Le:"mic",oe=(Ue=u==null?void 0:u.size)!=null?Ue:"40px",se=(Ge=l==null?void 0:l.iconSize)!=null?Ge:oe,Y=parseFloat(se)||24,be=(yt=l==null?void 0:l.backgroundColor)!=null?yt:u==null?void 0:u.backgroundColor,Oe=(L=l==null?void 0:l.iconColor)!=null?L:u==null?void 0:u.textColor;O.style.width=se,O.style.height=se,O.style.minWidth=se,O.style.minHeight=se,O.style.fontSize="18px",O.style.lineHeight="1",Oe?O.style.color=Oe:O.style.color="var(--persona-text, #111827)";let ot=xe(H,Y,Oe||"currentColor",1.5);ot?O.appendChild(ot):O.textContent="\u{1F3A4}",be?O.style.backgroundColor=be:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),q.appendChild(O);let $e=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((He=l==null?void 0:l.showTooltip)!=null?He:!1)&&$e){let ge=y("div","persona-send-button-tooltip");ge.textContent=$e,q.appendChild(ge)}return{micButton:O,micButtonWrapper:q}},Ii=()=>{var u,h,b,A,R;if(!U||ut)return;let l=(u=r.voiceRecognition)!=null?u:{};ut={backgroundColor:U.style.backgroundColor,color:U.style.color,borderColor:U.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((R=(A=l.iconSize)!=null?A:(b=r.sendButton)==null?void 0:b.size)!=null?R:"40")||24}},Ri=(l,u)=>{var R,q,O,H,oe;if(!U)return;let h=U.querySelector("svg");h&&h.remove();let b=(oe=ut==null?void 0:ut.iconSize)!=null?oe:parseFloat((H=(O=(R=r.voiceRecognition)==null?void 0:R.iconSize)!=null?O:(q=r.sendButton)==null?void 0:q.size)!=null?H:"40")||24,A=xe(l,b,u,1.5);A&&U.appendChild(A)},wa=()=>{U&&U.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ts=()=>{var A;if(!U)return;Ii();let l=(A=r.voiceRecognition)!=null?A:{},u=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(wa(),U.classList.add("persona-voice-recording"),U.style.backgroundColor=u!=null?u:"var(--persona-voice-recording-bg, #ef4444)",U.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let R=U.querySelector("svg");R&&R.setAttribute("stroke",h)}b&&(U.style.borderColor=b),U.setAttribute("aria-label","Stop voice recognition")},pf=()=>{var O,H,oe,se,Y,be,Oe,Ce;if(!U)return;Ii();let l=(O=r.voiceRecognition)!=null?O:{},u=F.getVoiceInterruptionMode(),h=(H=l.processingIconName)!=null?H:"loader",b=(se=(oe=l.processingIconColor)!=null?oe:ut==null?void 0:ut.color)!=null?se:"",A=(be=(Y=l.processingBackgroundColor)!=null?Y:ut==null?void 0:ut.backgroundColor)!=null?be:"",R=(Ce=(Oe=l.processingBorderColor)!=null?Oe:ut==null?void 0:ut.borderColor)!=null?Ce:"";wa(),U.classList.add("persona-voice-processing"),U.style.backgroundColor=A,U.style.borderColor=R;let q=b||"currentColor";U.style.color=q,Ri(h,q),U.setAttribute("aria-label","Processing voice input"),u==="none"&&(U.style.cursor="default")},uf=()=>{var oe,se,Y,be,Oe,Ce,ot,$e,mt,at,We,Le;if(!U)return;Ii();let l=(oe=r.voiceRecognition)!=null?oe:{},u=F.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",b=(se=l.speakingIconName)!=null?se:h,A=(Ce=l.speakingIconColor)!=null?Ce:u==="barge-in"?(be=(Y=l.recordingIconColor)!=null?Y:ut==null?void 0:ut.color)!=null?be:"":(Oe=ut==null?void 0:ut.color)!=null?Oe:"",R=(mt=l.speakingBackgroundColor)!=null?mt:u==="barge-in"?(ot=l.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":($e=ut==null?void 0:ut.backgroundColor)!=null?$e:"",q=(Le=l.speakingBorderColor)!=null?Le:u==="barge-in"?(at=l.recordingBorderColor)!=null?at:"":(We=ut==null?void 0:ut.borderColor)!=null?We:"";wa(),U.classList.add("persona-voice-speaking"),U.style.backgroundColor=R,U.style.borderColor=q;let O=A||"currentColor";U.style.color=O,Ri(b,O);let H=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";U.setAttribute("aria-label",H),u==="none"&&(U.style.cursor="default"),u==="barge-in"&&U.classList.add("persona-voice-recording")},jr=()=>{var l,u,h;U&&(wa(),ut&&(U.style.backgroundColor=(l=ut.backgroundColor)!=null?l:"",U.style.color=(u=ut.color)!=null?u:"",U.style.borderColor=(h=ut.borderColor)!=null?h:"",Ri(ut.iconName,ut.color||"currentColor"),ut=null),U.style.cursor="",U.setAttribute("aria-label","Start voice recognition"))},Ca=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=F.getVoiceStatus(),b=F.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Rn(),er("user"),jr()});return}F.toggleVoice().then(()=>{ft.active=F.isVoiceActive(),ft.manuallyDeactivated=!F.isVoiceActive(),Rn(),er("user"),F.isVoiceActive()?ts():jr()});return}if(kr){let h=Ae.value.trim();ft.manuallyDeactivated=!0,Rn(),oo("user"),h&&(Ae.value="",Ae.style.height="auto",F.sendMessage(h))}else ft.manuallyDeactivated=!1,Rn(),va("user")};Dn=Ca,U&&(U.addEventListener("click",Ca),ct.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),jr()):oo("system"),U&&U.removeEventListener("click",Ca)}));let mf=o.on("assistant:complete",()=>{Ts&&(ft.active||ft.manuallyDeactivated||Ts==="assistant"&&!ft.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!ft.active&&!ft.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?F.toggleVoice().then(()=>{ft.active=F.isVoiceActive(),er("auto"),F.isVoiceActive()&&ts()}):va("auto"))},600))});ct.push(mf);let gf=o.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});ct.push(gf);let rc=()=>{_t(!k,"user")},Qt=null,sn=null;if(C&&!B()){let{instance:l,element:u}=fl({config:r,plugins:s,onToggle:rc});Qt=l,l||(sn=u)}Qt?e.appendChild(Qt.element):sn&&e.appendChild(sn),Ps(),Ko(),Jl(),Ei(F.isStreaming()),nt()==="follow"?Wn(!0):ro(),ya(),N&&(!C||B()?setTimeout(()=>Mi(),0):k&&setTimeout(()=>Mi(),200));let Is=()=>{var H,oe,se,Y,be,Oe,Ce,ot,$e,mt,at,We,Le,Ue,Ge,yt,L,De,He,ge,Dt,Bt;if(B()){Pn(),Ps();return}let l=dn(r),u=(oe=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?oe:!1,h=l||u||((Y=(se=r.launcher)==null?void 0:se.fullHeight)!=null?Y:!1),b=(be=e.ownerDocument.defaultView)!=null?be:window,A=(Ce=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ce:!0,R=($e=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?$e:640,q=b.innerWidth<=R,O=A&&q&&C;try{if(O){ye(),jo(e,r);return}if(W&&(W=!1,ye(),jo(e,r)),!C&&!l){ce.style.height="",ce.style.width="";return}if(!u&&!l){let Ut=(at=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?at:r==null?void 0:r.launcherWidth,vt=Ut!=null?Ut:sr;ce.style.width=vt,ce.style.maxWidth=vt}if(wr(),!h){let Ut=b.innerHeight,vt=64,$t=(Le=(We=r.launcher)==null?void 0:We.heightOffset)!=null?Le:0,Vn=Math.max(200,Ut-vt),Xt=Math.min(640,Vn),Qe=Math.max(200,Xt-$t);ce.style.height=`${Qe}px`}}finally{if(Pn(),Ps(),k&&C){let vt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((yt=(Ge=r.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?yt:640),$t=(De=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?De:!1,Vn=(ge=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?ge:!0,Xt=dn(r)&&Vn&&vt,Qe=$t||Vn&&vt&&C||Xt;if(Qe&&!on){let Mt=e.getRootNode(),nn=Mt instanceof ShadowRoot?Mt.host:e.closest(".persona-host");nn&&!Jt&&(Jt=dl(nn,(Bt=(Dt=r.launcher)==null?void 0:Dt.zIndex)!=null?Bt:wn)),on=pl(e.ownerDocument)}else Qe||(Jt==null||Jt(),Jt=null,on==null||on(),on=null)}}};Is();let oc=(id=e.ownerDocument.defaultView)!=null?id:window;if(oc.addEventListener("resize",Is),ct.push(()=>oc.removeEventListener("resize",Is)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Pn()});l.observe(Ie),ct.push(()=>l.disconnect())}Un=we.scrollTop;let sc=Vr(we),ff=()=>{let l=we.getRootNode(),u=typeof l.getSelection=="function"?l.getSelection():null;return u!=null?u:we.ownerDocument.getSelection()},Wi=()=>Lm(ff(),we),ac=()=>{let l=we.scrollTop,u=Vr(we),h=u<sc;if(sc=u,nt()!=="follow"){Un=l,Ye();return}let{action:b,nextLastScrollTop:A}=Ga({following:jn.isFollowing(),currentScrollTop:l,lastScrollTop:Un,nearBottom:Uo(we,Xo),userScrollThreshold:fa,isAutoScrolling:pr||To||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Un=A,b==="resume"){Wi()||_r();return}b==="pause"&&Et()};if(we.addEventListener("scroll",ac,{passive:!0}),ct.push(()=>we.removeEventListener("scroll",ac)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{zn()});l.observe(ze),l.observe(we),ct.push(()=>l.disconnect())}let ic=()=>{nt()==="follow"&&jn.isFollowing()&&Wi()&&Et()},lc=we.ownerDocument;lc.addEventListener("selectionchange",ic),ct.push(()=>{lc.removeEventListener("selectionchange",ic)});let cc=l=>{if(nt()!=="follow")return;let u=Ja({following:jn.isFollowing(),deltaY:l.deltaY,nearBottom:Uo(we,Xo),resumeWhenNearBottom:!0});u==="pause"?Et():u==="resume"&&!Wi()&&_r()};we.addEventListener("wheel",cc,{passive:!0}),ct.push(()=>we.removeEventListener("wheel",cc)),lt.addEventListener("click",()=>{gn(),we.scrollTop=we.scrollHeight,Un=we.scrollTop,_r(),Wn(!0),Ye()}),ct.push(()=>lt.remove()),ct.push(()=>{_(),gn()});let dc=()=>{Ve&&(Sr&&(Ve.removeEventListener("click",Sr),Sr=null),D()?(Ve.style.display="",Sr=()=>{_t(!1,"user")},Ve.addEventListener("click",Sr)):Ve.style.display="none")};dc(),(()=>{let{clearChatButton:l}=X;l&&l.addEventListener("click",()=>{F.clearMessages(),Tr.clear(),_r(),Oo(X.composerOverlay);try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)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 u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),le==null||le.clear(),re==null||re.reset(),G==null||G.update()})})(),Pt&&Pt.addEventListener("submit",Xl),Ae==null||Ae.addEventListener("keydown",Zl),Ae==null||Ae.addEventListener("input",Yl),Ae==null||Ae.addEventListener("paste",tc);let pc=(ld=e.ownerDocument)!=null?ld:document;pc.addEventListener("keydown",ec,!0);let uc="persona-attachment-drop-active",Rs=0,Hi=()=>{Rs=0,de.classList.remove(uc)},ns=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&xt!==null},mc=l=>{!yi(l.dataTransfer)||!ns()||(Rs++,Rs===1&&de.classList.add(uc))},gc=l=>{!yi(l.dataTransfer)||!ns()||(Rs--,Rs<=0&&Hi())},fc=l=>{!yi(l.dataTransfer)||!ns()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},hc=l=>{var h;if(!yi(l.dataTransfer)||!ns())return;l.preventDefault(),l.stopPropagation(),Hi();let u=Array.from((h=l.dataTransfer.files)!=null?h:[]);u.length!==0&&xt.handleFiles(u)},so=!0;de.addEventListener("dragenter",mc,so),de.addEventListener("dragleave",gc,so),e.addEventListener("dragover",fc,so),e.addEventListener("drop",hc,so);let Sa=e.ownerDocument,yc=l=>{ns()&&l.preventDefault()},bc=l=>{ns()&&l.preventDefault()};Sa.addEventListener("dragover",yc),Sa.addEventListener("drop",bc),ct.push(()=>{Pt&&Pt.removeEventListener("submit",Xl),Ae==null||Ae.removeEventListener("keydown",Zl),Ae==null||Ae.removeEventListener("input",Yl),Ae==null||Ae.removeEventListener("paste",tc),pc.removeEventListener("keydown",ec,!0)}),ct.push(()=>{de.removeEventListener("dragenter",mc,so),de.removeEventListener("dragleave",gc,so),e.removeEventListener("dragover",fc,so),e.removeEventListener("drop",hc,so),Sa.removeEventListener("dragover",yc),Sa.removeEventListener("drop",bc),Hi()}),ct.push(()=>{F.cancel()}),Qt?ct.push(()=>{Qt==null||Qt.destroy()}):sn&&ct.push(()=>{sn==null||sn.remove()});let tn={update(l){var bn,Tn,Lr,pn,En,Mn,Ro,Ws,fd,hd,yd,bd,xd,vd,wd,Cd,Sd,Ad,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,Qd,Xd,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,Sp,Ap,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,Qp,Xp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu;let u=r.toolCall,h=r.messageActions,b=(bn=r.layout)==null?void 0:bn.messages,A=r.colorScheme,R=r.loadingIndicator,q=r.iterationDisplay,O=(Tn=r.features)==null?void 0:Tn.showReasoning,H=(Lr=r.features)==null?void 0:Lr.showToolCalls,oe=(pn=r.features)==null?void 0:pn.toolCallDisplay,se=(En=r.features)==null?void 0:En.reasoningDisplay;r={...r,...l},ye(),jo(e,r),ui(e,r),mi(e,r),$n(),r.colorScheme!==A&&As();let Y=gi.getForInstance(r.plugins);s.length=0,s.push(...Y),C=(Ro=(Mn=r.launcher)==null?void 0:Mn.enabled)!=null?Ro:!0,I=(fd=(Ws=r.launcher)==null?void 0:Ws.autoExpand)!=null?fd:!1,je=(yd=(hd=r.features)==null?void 0:hd.showReasoning)!=null?yd:!0,Se=(xd=(bd=r.features)==null?void 0:bd.showToolCalls)!=null?xd:!0,Fe=(wd=(vd=r.features)==null?void 0:vd.scrollToBottom)!=null?wd:{};let be=nt();he=(Sd=(Cd=r.features)==null?void 0:Cd.scrollBehavior)!=null?Sd:{},be!==nt()&&(gn(),_r()),br(),Ye();let Oe=ke;if(ke=(Td=(Ad=r.features)==null?void 0:Ad.showEventStreamToggle)!=null?Td:!1,ke&&!Oe){if(le||(Q=new pa(ae),le=new da(ne,Q),re=re!=null?re:new ua,Q.open().then(()=>le==null?void 0:le.restore()).catch(()=>{}),F.setSSEEventCallback((Z,At)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,Z,At),re==null||re.processEvent(Z,At),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Z,timestamp:Date.now(),payload:JSON.stringify(At)})})),!ht&&Te){let Z=(Md=(Ed=r.features)==null?void 0:Ed.eventStream)==null?void 0:Md.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"+(Z!=null&&Z.toggleButton?" "+Z.toggleButton:"");ht=y("button",At),ht.style.width="28px",ht.style.height="28px",ht.style.color=Ln.actionIconColor,ht.type="button",ht.setAttribute("aria-label","Event Stream"),ht.title="Event Stream";let jt=xe("activity","18px","currentColor",1.5);jt&&ht.appendChild(jt);let it=X.clearChatButtonWrapper,kt=X.closeButtonWrapper,ln=it||kt;ln&&ln.parentNode===Te?Te.insertBefore(ht,ln):Te.appendChild(ht),ht.addEventListener("click",()=>{ee?lr():Wr()})}}else!ke&&Oe&&(lr(),ht&&(ht.remove(),ht=null),le==null||le.clear(),Q==null||Q.destroy(),le=null,Q=null,re==null||re.reset(),re=null);if(((kd=r.launcher)==null?void 0:kd.enabled)===!1&&Qt&&(Qt.destroy(),Qt=null),((Ld=r.launcher)==null?void 0:Ld.enabled)===!1&&sn&&(sn.remove(),sn=null),((Pd=r.launcher)==null?void 0:Pd.enabled)!==!1&&!Qt&&!sn){let{instance:Z,element:At}=fl({config:r,plugins:s,onToggle:rc});Qt=Z,Z||(sn=At),e.appendChild(At)}Qt&&Qt.update(r),ue&&((Id=r.launcher)==null?void 0:Id.title)!==void 0&&(ue.textContent=r.launcher.title),Me&&((Rd=r.launcher)==null?void 0:Rd.subtitle)!==void 0&&(Me.textContent=r.launcher.subtitle);let Ce=(Wd=r.layout)==null?void 0:Wd.header;if((Ce==null?void 0:Ce.layout)!==S&&Te){let Z=Ce?ia(r,Ce,{showClose:D(),onClose:()=>_t(!1,"user")}):yo({config:r,showClose:D(),onClose:()=>_t(!1,"user")});Ke.replaceHeader(Z),Te=Ke.header.element,T=Ke.header.iconHolder,ue=Ke.header.headerTitle,Me=Ke.header.headerSubtitle,Ve=Ke.header.closeButton,S=Ce==null?void 0:Ce.layout}else if(Ce&&(T&&(T.style.display=Ce.showIcon===!1?"none":""),ue&&(ue.style.display=Ce.showTitle===!1?"none":""),Me&&(Me.style.display=Ce.showSubtitle===!1?"none":""),Ve&&(Ve.style.display=Ce.showCloseButton===!1?"none":""),X.clearChatButtonWrapper)){let Z=Ce.showClearChat;if(Z!==void 0){X.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:At}=X;At&&!At.classList.contains("persona-absolute")&&(Z?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let $e=((Hd=r.layout)==null?void 0:Hd.showHeader)!==!1;Te&&(Te.style.display=$e?"":"none");let mt=((Bd=r.layout)==null?void 0:Bd.showFooter)!==!1;Ie&&(Ie.style.display=mt?"":"none"),Pn(),Ye(),C!==P?C?_t(I,"auto"):(k=!0,Ps()):I!==M&&_t(I,"auto"),M=I,P=C,Is(),dc();let Le=JSON.stringify(l.toolCall)!==JSON.stringify(u),Ue=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ge=JSON.stringify((Dd=r.layout)==null?void 0:Dd.messages)!==JSON.stringify(b),yt=((Nd=r.loadingIndicator)==null?void 0:Nd.render)!==(R==null?void 0:R.render)||((Od=r.loadingIndicator)==null?void 0:Od.renderIdle)!==(R==null?void 0:R.renderIdle)||((Fd=r.loadingIndicator)==null?void 0:Fd.showBubble)!==(R==null?void 0:R.showBubble),L=r.iterationDisplay!==q,De=(($d=(_d=r.features)==null?void 0:_d.showReasoning)!=null?$d:!0)!==(O!=null?O:!0)||((Ud=(jd=r.features)==null?void 0:jd.showToolCalls)!=null?Ud:!0)!==(H!=null?H:!0)||JSON.stringify((qd=r.features)==null?void 0:qd.toolCallDisplay)!==JSON.stringify(oe)||JSON.stringify((zd=r.features)==null?void 0:zd.reasoningDisplay)!==JSON.stringify(se);(Le||Ue||Ge||yt||L||De)&&F&&(Go++,Es(ze,F.getMessages(),Pe));let ge=(Vd=r.launcher)!=null?Vd:{},Dt=(Kd=ge.headerIconHidden)!=null?Kd:!1,Bt=(Jd=(Gd=r.layout)==null?void 0:Gd.header)==null?void 0:Jd.showIcon,Ut=Dt||Bt===!1,vt=ge.headerIconName,$t=(Qd=ge.headerIconSize)!=null?Qd:"48px";if(T){let Z=de.querySelector(".persona-border-b-persona-divider"),At=Z==null?void 0:Z.querySelector(".persona-flex-col");if(Ut)T.style.display="none",Z&&At&&!Z.contains(At)&&Z.insertBefore(At,Z.firstChild);else{if(T.style.display="",T.style.height=$t,T.style.width=$t,Z&&At&&(Z.contains(T)?T.nextSibling!==At&&(T.remove(),Z.insertBefore(T,At)):Z.insertBefore(T,At)),vt){let it=parseFloat($t)||24,kt=xe(vt,it*.6,"currentColor",1);kt?T.replaceChildren(kt):T.textContent=(Xd=ge.agentIconText)!=null?Xd:"\u{1F4AC}"}else if(ge.iconUrl){let it=T.querySelector("img");if(it)it.src=ge.iconUrl,it.style.height=$t,it.style.width=$t;else{let kt=document.createElement("img");kt.src=ge.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=$t,kt.style.width=$t,T.replaceChildren(kt)}}else{let it=T.querySelector("svg"),kt=T.querySelector("img");(it||kt)&&T.replaceChildren(),T.textContent=(Yd=ge.agentIconText)!=null?Yd:"\u{1F4AC}"}let jt=T.querySelector("img");jt&&(jt.style.height=$t,jt.style.width=$t)}}let Vn=(ep=(Zd=r.layout)==null?void 0:Zd.header)==null?void 0:ep.showTitle,Xt=(np=(tp=r.layout)==null?void 0:tp.header)==null?void 0:np.showSubtitle;if(ue&&(ue.style.display=Vn===!1?"none":""),Me&&(Me.style.display=Xt===!1?"none":""),Ve){((op=(rp=r.layout)==null?void 0:rp.header)==null?void 0:op.showCloseButton)===!1?Ve.style.display="none":Ve.style.display="";let At=(sp=ge.closeButtonSize)!=null?sp:"32px",jt=(ap=ge.closeButtonPlacement)!=null?ap:"inline";Ve.style.height=At,Ve.style.width=At;let{closeButtonWrapper:it}=X,kt=jt==="top-right",ln=it==null?void 0:it.classList.contains("persona-absolute");if(it&&kt!==ln)if(it.remove(),kt)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(it);else{let dt=(lp=(ip=ge.clearChat)==null?void 0:ip.placement)!=null?lp:"inline",cn=(dp=(cp=ge.clearChat)==null?void 0:cp.enabled)!=null?dp:!0;it.className=cn&&dt==="inline"?"":"persona-ml-auto";let Bn=de.querySelector(".persona-border-b-persona-divider");Bn&&Bn.appendChild(it)}if(Ve.style.color=ge.closeButtonColor||Ln.actionIconColor,ge.closeButtonBackgroundColor?(Ve.style.backgroundColor=ge.closeButtonBackgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let dt=ge.closeButtonBorderWidth||"0px",cn=ge.closeButtonBorderColor||"transparent";Ve.style.border=`${dt} solid ${cn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");ge.closeButtonBorderRadius?(Ve.style.borderRadius=ge.closeButtonBorderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(Ve.style.paddingLeft=ge.closeButtonPaddingX,Ve.style.paddingRight=ge.closeButtonPaddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),ge.closeButtonPaddingY?(Ve.style.paddingTop=ge.closeButtonPaddingY,Ve.style.paddingBottom=ge.closeButtonPaddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let xn=(pp=ge.closeButtonIconName)!=null?pp:"x",mr=(up=ge.closeButtonIconText)!=null?up:"\xD7";Ve.innerHTML="";let kn=xe(xn,"28px","currentColor",1);kn?Ve.appendChild(kn):Ve.textContent=mr;let Gt=(mp=ge.closeButtonTooltipText)!=null?mp:"Close chat",Gn=(gp=ge.closeButtonShowTooltip)!=null?gp:!0;if(Ve.setAttribute("aria-label",Gt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),Gn&&Gt)){let dt=null,cn=()=>{if(dt||!Ve)return;let Wo=Ve.ownerDocument,Hs=Wo.body;if(!Hs)return;dt=Pr(Wo,"div","persona-clear-chat-tooltip"),dt.textContent=Gt;let Bs=Pr(Wo,"div");Bs.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Bs);let Ho=Ve.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(go),dt.style.left=`${Ho.left+Ho.width/2}px`,dt.style.top=`${Ho.top-8}px`,dt.style.transform="translate(-50%, -100%)",Hs.appendChild(dt)},Bn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};it.addEventListener("mouseenter",cn),it.addEventListener("mouseleave",Bn),Ve.addEventListener("focus",cn),Ve.addEventListener("blur",Bn),it._cleanupTooltip=()=>{Bn(),it&&(it.removeEventListener("mouseenter",cn),it.removeEventListener("mouseleave",Bn)),Ve&&(Ve.removeEventListener("focus",cn),Ve.removeEventListener("blur",Bn))}}}let{clearChatButton:Qe,clearChatButtonWrapper:Mt}=X;if(Qe){let Z=(fp=ge.clearChat)!=null?fp:{},At=(hp=Z.enabled)!=null?hp:!0,jt=(bp=(yp=r.layout)==null?void 0:yp.header)==null?void 0:bp.showClearChat,it=jt!==void 0?jt:At,kt=(xp=Z.placement)!=null?xp:"inline";if(Mt){Mt.style.display=it?"":"none";let{closeButtonWrapper:ln}=X;!B()&&ln&&!ln.classList.contains("persona-absolute")&&(it?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let xn=kt==="top-right",mr=Mt.classList.contains("persona-absolute");if(!B()&&xn!==mr&&it){if(Mt.remove(),xn)Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px",de.style.position="relative",de.appendChild(Mt);else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let Gt=de.querySelector(".persona-border-b-persona-divider"),Gn=X.closeButtonWrapper;Gt&&Gn&&Gn.parentElement===Gt?Gt.insertBefore(Mt,Gn):Gt&&Gt.appendChild(Mt)}let kn=X.closeButtonWrapper;kn&&!kn.classList.contains("persona-absolute")&&(xn?kn.classList.add("persona-ml-auto"):kn.classList.remove("persona-ml-auto"))}}if(it){if(!B()){let dt=(vp=Z.size)!=null?vp:"32px";Qe.style.height=dt,Qe.style.width=dt}let ln=(wp=Z.iconName)!=null?wp:"refresh-cw",xn=(Cp=Z.iconColor)!=null?Cp:"";Qe.style.color=xn||Ln.actionIconColor,Qe.innerHTML="";let mr=B()?"14px":"20px",kn=xe(ln,mr,"currentColor",2);if(kn&&Qe.appendChild(kn),Z.backgroundColor?(Qe.style.backgroundColor=Z.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let dt=Z.borderWidth||"0px",cn=Z.borderColor||"transparent";Qe.style.border=`${dt} solid ${cn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");Z.borderRadius?(Qe.style.borderRadius=Z.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),Z.paddingX?(Qe.style.paddingLeft=Z.paddingX,Qe.style.paddingRight=Z.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),Z.paddingY?(Qe.style.paddingTop=Z.paddingY,Qe.style.paddingBottom=Z.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Gt=(Sp=Z.tooltipText)!=null?Sp:"Clear chat",Gn=(Ap=Z.showTooltip)!=null?Ap:!0;if(Qe.setAttribute("aria-label",Gt),Mt&&(Mt._cleanupTooltip&&(Mt._cleanupTooltip(),delete Mt._cleanupTooltip),Gn&&Gt)){let dt=null,cn=()=>{if(dt||!Qe)return;let Wo=Qe.ownerDocument,Hs=Wo.body;if(!Hs)return;dt=Pr(Wo,"div","persona-clear-chat-tooltip"),dt.textContent=Gt;let Bs=Pr(Wo,"div");Bs.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Bs);let Ho=Qe.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(go),dt.style.left=`${Ho.left+Ho.width/2}px`,dt.style.top=`${Ho.top-8}px`,dt.style.transform="translate(-50%, -100%)",Hs.appendChild(dt)},Bn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};Mt.addEventListener("mouseenter",cn),Mt.addEventListener("mouseleave",Bn),Qe.addEventListener("focus",cn),Qe.addEventListener("blur",Bn),Mt._cleanupTooltip=()=>{Bn(),Mt&&(Mt.removeEventListener("mouseenter",cn),Mt.removeEventListener("mouseleave",Bn)),Qe&&(Qe.removeEventListener("focus",cn),Qe.removeEventListener("blur",Bn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[fi],rr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Cs.message,Cs.messageAndClick];E=hi({parsers:nn,handlers:rr,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Pe=yg(r,E,te),F.updateConfig(r),Es(ze,F.getMessages(),Pe),Ko(),Jl(),Ei(F.isStreaming());let Kn=((Tp=r.voiceRecognition)==null?void 0:Tp.enabled)===!0,ko=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Lo=((Mp=(Ep=r.voiceRecognition)==null?void 0:Ep.provider)==null?void 0:Mp.type)==="runtype";if(Kn&&(ko||Lo))if(!U||!st){let Z=df(r.voiceRecognition,r.sendButton);Z&&(U=Z.micButton,st=Z.micButtonWrapper,pt.insertBefore(st,fn),U.addEventListener("click",Ca),U.disabled=F.isStreaming())}else{let Z=(kp=r.voiceRecognition)!=null?kp:{},At=(Lp=r.sendButton)!=null?Lp:{},jt=(Pp=Z.iconName)!=null?Pp:"mic",it=(Ip=At.size)!=null?Ip:"40px",kt=(Rp=Z.iconSize)!=null?Rp:it,ln=parseFloat(kt)||24;U.style.width=kt,U.style.height=kt,U.style.minWidth=kt,U.style.minHeight=kt;let xn=(Hp=(Wp=Z.iconColor)!=null?Wp:At.textColor)!=null?Hp:"currentColor";U.innerHTML="";let mr=xe(jt,ln,xn,2);mr?U.appendChild(mr):U.textContent="\u{1F3A4}";let kn=(Bp=Z.backgroundColor)!=null?Bp:At.backgroundColor;kn?U.style.backgroundColor=kn:U.style.backgroundColor="",xn?U.style.color=xn:U.style.color="var(--persona-text, #111827)",Z.borderWidth?(U.style.borderWidth=Z.borderWidth,U.style.borderStyle="solid"):(U.style.borderWidth="",U.style.borderStyle=""),Z.borderColor?U.style.borderColor=Z.borderColor:U.style.borderColor="",Z.paddingX?(U.style.paddingLeft=Z.paddingX,U.style.paddingRight=Z.paddingX):(U.style.paddingLeft="",U.style.paddingRight=""),Z.paddingY?(U.style.paddingTop=Z.paddingY,U.style.paddingBottom=Z.paddingY):(U.style.paddingTop="",U.style.paddingBottom="");let Gt=st==null?void 0:st.querySelector(".persona-send-button-tooltip"),Gn=(Dp=Z.tooltipText)!=null?Dp:"Start voice recognition";if(((Np=Z.showTooltip)!=null?Np:!1)&&Gn)if(Gt)Gt.textContent=Gn,Gt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Gn,st==null||st.insertBefore(cn,U)}else Gt&&(Gt.style.display="none");st.style.display="",U.disabled=F.isStreaming()}else U&&st&&(st.style.display="none",((Fp=(Op=r.voiceRecognition)==null?void 0:Op.provider)==null?void 0:Fp.type)==="runtype"?F.isVoiceActive()&&F.toggleVoice():kr&&oo());if(((_p=r.attachments)==null?void 0:_p.enabled)===!0)if(!pe||!V){let Z=($p=r.attachments)!=null?$p:{},jt=(Up=((jp=r.sendButton)!=null?jp:{}).size)!=null?Up:"40px";bt||(bt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),bt.style.display="none",Pt.insertBefore(bt,Ae)),Ee||(Ee=document.createElement("input"),Ee.type="file",Ee.accept=((qp=Z.allowedTypes)!=null?qp:zr).join(","),Ee.multiple=((zp=Z.maxFiles)!=null?zp:4)>1,Ee.style.display="none",Ee.setAttribute("aria-label","Attach files"),Pt.insertBefore(Ee,Ae)),pe=y("div","persona-send-button-wrapper"),V=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),V.type="button",V.setAttribute("aria-label",(Vp=Z.buttonTooltipText)!=null?Vp:"Attach file");let it=(Kp=Z.buttonIconName)!=null?Kp:"paperclip",kt=jt,ln=parseFloat(kt)||40,xn=Math.round(ln*.6);V.style.width=kt,V.style.height=kt,V.style.minWidth=kt,V.style.minHeight=kt,V.style.fontSize="18px",V.style.lineHeight="1",V.style.backgroundColor="transparent",V.style.color="var(--persona-primary, #111827)",V.style.border="none",V.style.borderRadius="6px",V.style.transition="background-color 0.15s ease",V.addEventListener("mouseenter",()=>{V.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),V.addEventListener("mouseleave",()=>{V.style.backgroundColor="transparent"});let mr=xe(it,xn,"currentColor",1.5);mr?V.appendChild(mr):V.textContent="\u{1F4CE}",V.addEventListener("click",Gn=>{Gn.preventDefault(),Ee==null||Ee.click()}),pe.appendChild(V);let kn=(Gp=Z.buttonTooltipText)!=null?Gp:"Attach file",Gt=y("div","persona-send-button-tooltip");Gt.textContent=kn,pe.appendChild(Gt),Je.append(pe),!xt&&Ee&&bt&&(xt=fs.fromConfig(Z),xt.setPreviewsContainer(bt),Ee.addEventListener("change",async()=>{xt&&(Ee!=null&&Ee.files)&&(await xt.handleFileSelect(Ee.files),Ee.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(bg(Z.dropOverlay))}else{pe.style.display="";let Z=(Jp=r.attachments)!=null?Jp:{};Ee&&(Ee.accept=((Qp=Z.allowedTypes)!=null?Qp:zr).join(","),Ee.multiple=((Xp=Z.maxFiles)!=null?Xp:4)>1),xt&&xt.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles})}else pe&&(pe.style.display="none"),xt&&xt.clearAttachments(),(Yp=de.querySelector(".persona-attachment-drop-overlay"))==null||Yp.remove();let zt=(Zp=r.sendButton)!=null?Zp:{},Po=(eu=zt.useIcon)!=null?eu:!1,ao=(tu=zt.iconText)!=null?tu:"\u2191",io=zt.iconName,Ur=(nu=zt.tooltipText)!=null?nu:"Send message",Io=(ru=zt.showTooltip)!=null?ru:!1,ur=(ou=zt.size)!=null?ou:"40px",Ze=zt.backgroundColor,an=zt.textColor;if(Po){if(me.style.width=ur,me.style.height=ur,me.style.minWidth=ur,me.style.minHeight=ur,me.style.fontSize="18px",me.style.lineHeight="1",me.innerHTML="",an?me.style.color=an:me.style.color="var(--persona-button-primary-fg, #ffffff)",io){let Z=parseFloat(ur)||24,At=(an==null?void 0:an.trim())||"currentColor",jt=xe(io,Z,At,2);jt?me.appendChild(jt):me.textContent=ao}else me.textContent=ao;me.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ze?(me.style.backgroundColor=Ze,me.classList.remove("persona-bg-persona-primary")):(me.style.backgroundColor="",me.classList.add("persona-bg-persona-primary"))}else me.textContent=(au=(su=r.copy)==null?void 0:su.sendButtonLabel)!=null?au:"Send",me.style.width="",me.style.height="",me.style.minWidth="",me.style.minHeight="",me.style.fontSize="",me.style.lineHeight="",me.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",Ze?(me.style.backgroundColor=Ze,me.classList.remove("persona-bg-persona-accent")):me.classList.add("persona-bg-persona-accent"),an?me.style.color=an:me.classList.add("persona-text-white");zt.borderWidth?(me.style.borderWidth=zt.borderWidth,me.style.borderStyle="solid"):(me.style.borderWidth="",me.style.borderStyle=""),zt.borderColor?me.style.borderColor=zt.borderColor:me.style.borderColor="",zt.paddingX?(me.style.paddingLeft=zt.paddingX,me.style.paddingRight=zt.paddingX):(me.style.paddingLeft="",me.style.paddingRight=""),zt.paddingY?(me.style.paddingTop=zt.paddingY,me.style.paddingBottom=zt.paddingY):(me.style.paddingTop="",me.style.paddingBottom="");let Ft=fn==null?void 0:fn.querySelector(".persona-send-button-tooltip");if(Io&&Ur)if(Ft)Ft.textContent=Ur,Ft.style.display="";else{let Z=document.createElement("div");Z.className="persona-send-button-tooltip",Z.textContent=Ur,fn==null||fn.insertBefore(Z,me)}else Ft&&(Ft.style.display="none");let Nt=(pu=(iu=r.layout)==null?void 0:iu.contentMaxWidth)!=null?pu:B()?(du=(cu=(lu=r.launcher)==null?void 0:lu.composerBar)==null?void 0:cu.contentMaxWidth)!=null?du:"720px":void 0;Nt?(ze.style.maxWidth=Nt,ze.style.marginLeft="auto",ze.style.marginRight="auto",ze.style.width="100%",Pt&&(Pt.style.maxWidth=Nt,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Lt&&(Lt.style.maxWidth=Nt,Lt.style.marginLeft="auto",Lt.style.marginRight="auto")):(ze.style.maxWidth="",ze.style.marginLeft="",ze.style.marginRight="",ze.style.width="",Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""),Lt&&(Lt.style.maxWidth="",Lt.style.marginLeft="",Lt.style.marginRight=""));let gt=(uu=r.statusIndicator)!=null?uu:{},Vt=(mu=gt.visible)!=null?mu:!0;if(rn.style.display=Vt?"":"none",F){let Z=F.getStatus();Xe(rn,(jt=>{var it,kt,ln,xn;return jt==="idle"?(it=gt.idleText)!=null?it:vn.idle:jt==="connecting"?(kt=gt.connectingText)!=null?kt:vn.connecting:jt==="connected"?(ln=gt.connectedText)!=null?ln:vn.connected:jt==="error"?(xn=gt.errorText)!=null?xn:vn.error:vn[jt]})(Z),gt,Z)}rn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Ct=gt.align==="left"?"persona-text-left":gt.align==="center"?"persona-text-center":"persona-text-right";rn.classList.add(Ct)},open(){D()&&_t(!0,"api")},close(){D()&&_t(!1,"api")},toggle(){D()&&_t(!k,"api")},clearChat(){Sn=!1,F.clearMessages(),Tr.clear(),_r();try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}d={},E.syncFromMetadata(),le==null||le.clear(),re==null||re.reset(),G==null||G.update()},setMessage(l){return!Ae||F.isStreaming()?!1:(!k&&D()&&_t(!0,"system"),Ae.value=l,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let u=(l==null?void 0:l.trim())||Ae.value.trim();return u?(!k&&D()&&_t(!0,"system"),Ae.value="",Ae.style.height="auto",F.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return F.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(F.isVoiceActive()||(!k&&D()&&_t(!0,"system"),ft.manuallyDeactivated=!1,Rn(),F.toggleVoice().then(()=>{ft.active=F.isVoiceActive(),er("user"),F.isVoiceActive()&&ts()})),!0):kr?!0:nc()?(!k&&D()&&_t(!0,"system"),ft.manuallyDeactivated=!1,Rn(),va("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{ft.active=!1,ft.manuallyDeactivated=!0,Rn(),er("user"),jr()}),!0):!1:kr?(ft.manuallyDeactivated=!0,Rn(),oo("user"),!0):!1},injectMessage(l){return!k&&D()&&_t(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!k&&D()&&_t(!0,"system");let u=F.injectAssistantMessage(l);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),u},injectUserMessage(l){return!k&&D()&&_t(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!k&&D()&&_t(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!k&&D()&&_t(!0,"system"),F.injectMessageBatch(l)},injectComponentDirective(l){return!k&&D()&&_t(!0,"system"),F.injectComponentDirective(l)},injectTestMessage(l){!k&&D()&&_t(!0,"system"),F.injectTestEvent(l)},async connectStream(l,u){return F.connectStream(l,u)},__pushEventStreamEvent(l){le&&(re==null||re.processEvent(l.type,l.payload),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ke||!le||Wr()},hideEventStream(){ee&&lr()},isEventStreamVisible(){return ee},showArtifacts(){ir(r)&&(Sn=!1,$n(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(Sn=!0,$n())},upsertArtifact(l){return ir(r)?(Sn=!1,F.upsertArtifact(l)):null},selectArtifact(l){ir(r)&&F.selectArtifact(l)},clearArtifacts(){ir(r)&&F.clearArtifacts()},getArtifacts(){var l;return(l=F==null?void 0:F.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=F==null?void 0:F.getSelectedArtifactId())!=null?l:null},focusInput(){return C&&!k&&!B()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(l,u,h){let A=F.getMessages().find(R=>{var q;return R.variant==="approval"&&((q=R.approval)==null?void 0:q.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){F.resolveWebMcpApproval(A.id,u);return}return F.resolveApproval(A.approval,u,h)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){g(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return D()&&k},isVoiceActive(){return ft.active},toggleReadAloud(l){F.toggleReadAloud(l)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(l){return F.getReadAloudState(l)},onReadAloudChange(l){return F.onReadAloudChange(l)},getState(){return{open:D()&&k,launcherEnabled:C,voiceActive:ft.active,streaming:F.isStreaming()}},showCSATFeedback(l){!k&&D()&&_t(!0,"system");let u=ze.querySelector(".persona-feedback-container");u&&u.remove();let h=Rl({onSubmit:async(b,A)=>{var R;F.isClientTokenMode()&&await F.submitCSATFeedback(b,A),(R=l==null?void 0:l.onSubmit)==null||R.call(l,b,A)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&D()&&_t(!0,"system");let u=ze.querySelector(".persona-feedback-container");u&&u.remove();let h=Wl({onSubmit:async(b,A)=>{var R;F.isClientTokenMode()&&await F.submitNPSFeedback(b,A),(R=l==null?void 0:l.onSubmit)==null||R.call(l,b,A)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return F.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return F.submitNPSFeedback(l,u)},destroy(){Mo!=null&&(clearInterval(Mo),Mo=null),ct.forEach(l=>l()),Ne.remove(),et==null||et.remove(),Qt==null||Qt.destroy(),sn==null||sn.remove(),Sr&&Ve.removeEventListener("click",Sr)}};if((((cd=n==null?void 0:n.debugTools)!=null?cd:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={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=u,ct.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",u),ct.push(()=>{window.removeEventListener("persona:focusInput",u)}),ke){let O=oe=>{let se=oe.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&tn.showEventStream()},H=oe=>{let se=oe.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",H),ct.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",H)})}let h=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&tn.showArtifacts()},b=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&tn.hideArtifacts()},A=O=>{let H=O.detail;H!=null&&H.instanceId&&H.instanceId!==l||H!=null&&H.artifact&&tn.upsertArtifact(H.artifact)},R=O=>{let H=O.detail;H!=null&&H.instanceId&&H.instanceId!==l||typeof(H==null?void 0:H.id)=="string"&&tn.selectArtifact(H.id)},q=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",q),ct.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",q)})}let nr=kv(r.persistState);if(nr&&D()){let l=Lv(nr.storage),u=`${nr.keyPrefix}widget-open`,h=`${nr.keyPrefix}widget-voice`,b=`${nr.keyPrefix}widget-voice-mode`;if(l){let A=((dd=nr.persist)==null?void 0:dd.openState)&&l.getItem(u)==="true",R=((pd=nr.persist)==null?void 0:pd.voiceState)&&l.getItem(h)==="true",q=((ud=nr.persist)==null?void 0:ud.voiceState)&&l.getItem(b)==="true";if(A&&setTimeout(()=>{tn.open(),setTimeout(()=>{var O;if(R||q)tn.startVoiceRecognition();else if((O=nr.persist)!=null&&O.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(md=nr.persist)!=null&&md.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(gd=nr.persist)!=null&&gd.voiceState&&(o.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),o.on("user:message",O=>{l.setItem(b,O.viaVoice?"true":"false")})),nr.clearOnChatClear){let O=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(b)},H=()=>O();window.addEventListener("persona:clear-chat",H),ct.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&D()&&setTimeout(()=>{tn.open()},0),Zo(),ga||xu().then(()=>{F&&(Go++,Tr.clear(),Es(ze,F.getMessages(),Pe))}).catch(()=>{}),tn};var Pv=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Iv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Rv=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Wv=(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 s=r.offsetHeight>0;r.style.height="100%";let o=r.offsetHeight>0;r.remove(),!(!s||o)&&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.")},xg=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!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"},Fl=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=""},vg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Fl(e)},Dl=e=>{e.style.transition=""},Nl=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=""},Ol=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},bi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Hv=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Bv=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},wg=(e,t,n,r,s,o,a)=>{var x,v,E,C,I,N;let i=ar(o),d=i.reveal==="push";Hv(e,t,n,r,d),Bv(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",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,m=(C=(E=o==null?void 0:o.launcher)==null?void 0:E.mobileBreakpoint)!=null?C:640,f=c!=null?c.innerWidth<=m:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Nl(t),Dl(r),vg(r),Ol(n),bi(s,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((N=(I=o==null?void 0:o.launcher)==null?void 0:I.zIndex)!=null?N: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"),vg(r),Iv(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",Nl(t),Dl(r),Ol(n),bi(s,r);let M=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=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=S,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",Dl(r),Fl(r),bi(s,r);let M=Pv(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),S=i.animate?"margin-left 180ms ease":"none",W=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=S,t.style.marginLeft=`${W}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="",Nl(t),Fl(r),Ol(n),bi(s,r);let M=i.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!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",Rv(r,i.maxHeight),r.style.overflow=M||W?"hidden":"visible",r.style.transition=S,M&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Dv=(e,t)=>{let n=e.ownerDocument.createElement("div");return xg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){xg(n,r)},destroy(){n.remove()}}},Nv=(e,t)=>{var N,M,P,S;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),m=(M=(N=t==null?void 0:t.launcher)==null?void 0:N.enabled)==null||M?(S=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?S:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),ar(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{wg(a,i,d,c,p,t,m)}),f.observe(a))},v=!1,E=()=>{wg(a,i,d,c,p,t,m),x(),m&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Wv(a,ar(t)))},C=a.ownerDocument.defaultView,I=()=>{E()};return C==null||C.addEventListener("resize",I),ar(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),E(),{mode:"docked",host:p,shell:a,syncWidgetState(W){let B=W.launcherEnabled?W.open:!0;m!==B&&(m=B,E())},updateConfig(W){var B,D;t=W,((D=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)!=null?D:!0)===!1&&(m=!0),E()},destroy(){C==null||C.removeEventListener("resize",I),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},xi=(e,t)=>dn(t)?Nv(e,t):Dv(e,t);var _l={},Ov=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},Fv=()=>{try{if(typeof _l!="undefined"&&_l.url)return new URL("../widget.css",_l.url).href}catch{}return null},Cg=(e,t)=>{let n=Fv(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Sg=e=>{var E;let t=Ov(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=xi(t,s),a,i=[],d=(C,I)=>{var S,W;let M=!((W=(S=I==null?void 0:I.launcher)==null?void 0:S.enabled)!=null?W:!0)||dn(I),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 B=C.attachShadow({mode:"open"});B.appendChild(P),Cg(B,r)}else C.appendChild(P),Cg(C,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},m=()=>{let C=d(o.host,s);a=Bl(C,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(C=>C()),i=[],a.destroy()};m(),(E=e.onChatReady)==null||E.call(e);let g=C=>{f(),o.destroy(),o=xi(t,C),s=C,m()},x={update(C){var W,B,D,k,j,z;let I={...s,...C,launcher:{...(W=s==null?void 0:s.launcher)!=null?W:{},...(B=C==null?void 0:C.launcher)!=null?B:{},dock:{...(k=(D=s==null?void 0:s.launcher)==null?void 0:D.dock)!=null?k:{},...(z=(j=C==null?void 0:C.launcher)==null?void 0:j.dock)!=null?z:{}}}},N=dn(s),M=dn(I),P=ho(s),S=ho(I);if(N!==M||P!==S){g(I);return}s=I,o.updateConfig(s),a.update(C),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(x,{get(C,I,N){if(I==="host")return o.host;if(I in C)return Reflect.get(C,I,N);let M=a[I];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var kg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),_v=new Set(["button","a","input","select","textarea","details","summary"]),$v=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),$l=/\b(product|card|item|listing|result)\b/i,Ul=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,jv=3e3,Uv=100;function Lg(e){let t=typeof e.className=="string"?e.className:"";if($l.test(t)||e.id&&$l.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&$l.test(r.value))return!0}return!1}function Pg(e){var t;return Ul.test(((t=e.textContent)!=null?t:"").trim())}function Ig(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function qv(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ag(e){let t=e.match(Ul);return t?t[0]:null}function Tg(e){var r,s,o;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&&((s=t.textContent)!=null&&s.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(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function zv(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var Vv="commerce-card",Kv="result-card";function Eg(e){return!Lg(e)||!Pg(e)||!Ig(e)&&!qv(e)?0:5200}function Mg(e){var r;return!Lg(e)||Pg(e)||!Ig(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 Rg=[{id:Vv,scoreElement(e){return Eg(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||Ul.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(Eg(e)===0)return null;let{title:n,href:r}=Tg(e),s=(p=(c=Ag(((d=e.textContent)!=null?d:"").trim()))!=null?c:Ag(t.text))!=null?p:"",o=zv(e);return[r&&n?`[${n}](${r})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
110
- `)}},{id:Kv,scoreElement(e){return Mg(e)},formatSummary(e,t){if(Mg(e)===0)return null;let{title:n,href:r}=Tg(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
111
- `)}}];function Gv(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Jv(e){var p,m,f,g,x,v,E,C,I,N,M,P,S;let t=(p=e.options)!=null?p:{},n=(f=(m=t.maxElements)!=null?m:e.maxElements)!=null?f:80,r=(x=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?x:".persona-host",s=(E=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,o=(I=(C=t.visibleOnly)!=null?C:e.visibleOnly)!=null?I:!0,a=(N=t.root)!=null?N:e.root,i=(M=t.mode)!=null?M:"structured",d=(P=t.maxCandidates)!=null?P:Math.max(500,n*10),c=(S=e.rules)!=null?S:Rg;return i==="simple"&&e.rules&&e.rules.length>0?(Gv(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function jl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Qv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Xv(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"||_v.has(t)||n&&$v.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Wg(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 Yv(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);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 c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Hg(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${jl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Qv){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${jl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>jl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function Zv(e){return e==="static"?Uv:jv}function Bg(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:Hg(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Xv(e),attributes:Yv(e)}}function ew(e,t,n,r){let s=Zv(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function tw(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 nw(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(kg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Wg(c)){i=a.nextNode();continue}let m=Bg(c,e.maxTextLength),f=m.text.length>0,g=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(E=>E==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(m.selector)){i=a.nextNode();continue}r.add(m.selector);let{score:x,formattingRule:v}=ew(c,m,e.rules,n);s.push({el:c,domIndex:o,enriched:m,score:x,formattingRule:v}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return m!==f?m-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;tw(d,c)||d.push(c)}return d.sort((c,p)=>{let m=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return m!==f?m-f:m===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(p=g)}let m={...c.enriched};return p&&(m.formattedSummary=p),m})}function rw(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,c=d.tagName.toLowerCase();if(kg.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Wg(d)){o=s.nextNode();continue}let p=Bg(d,e.maxTextLength),m=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!m&&!f){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.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 ow(e={}){var r;let t=Jv(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?rw(t,n):nw(t,n):[]}var vi=100;function sw(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"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 Ot="max-height: -moz-available !important; max-height: stretch !important;",Kt=m?"":"padding-top: 1.25em !important;",Ft=m?"":`z-index: ${(Xe=(Ir=r.launcher)==null?void 0:Ir.zIndex)!=null?Xe:Sn} !important;`;_e.style.cssText+=Ot+Kt+Ft}Ke()};Cr(),zo(e,r),fi(e,r),hi(e,r);let ut=[];ut.push(()=>{document.removeEventListener("keydown",no)});let sn=null,an=null;ut.push(()=>{sn==null||sn(),sn=null,an==null||an(),an=null}),Fn&&ut.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),ut.push(()=>{Ln==null||Ln(),Ln=null,$r(),Ht&&(Ht.remove(),Ht=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),ne&&ut.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),ve==null||ve.destroy(),ve=null,K==null||K.destroy(),K=null,We=null});let Ar=null,Ls=()=>{Ar&&(Ar(),Ar=null),r.colorScheme==="auto"&&(Ar=ll(()=>{zo(e,r)}))};Ls(),ut.push(()=>{Ar&&(Ar(),Ar=null)}),ut.push(a);let jr=(sd=r.features)==null?void 0:sd.streamAnimation;if(jr!=null&&jr.type&&jr.type!=="none"){let c=ia(jr.type,jr.plugins);c&&(pl(c,e),ut.push(()=>$m(e)))}let ko=dg(Qe),Sr=null,$,Yo=c=>{var b,A;if(!$)return;let m=c!=null?c:$.getMessages(),h=((A=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:A.enabled)!==!1?Ki(m):null;h?ko.render(h,$,Ee,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(B=>B.role==="user")?ko.render([],$,Ee,m):ko.render(r.suggestionChips,$,Ee,m,r.suggestionChipsConfig)},Er=!1,Tr=Rm(),Ur=new Map,Mr=new Map,pr=new Map,Zo=0,xa=Oo()!==null,Un=Qa(),qn=0,ur=null,mr=!1,Lo=!1,qr=0,vn=null,kr=null,es=!1,Po=!1,ts=null,va=4,ns=24,wa=80,rs=new Map,dt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ps=(id=(ad=r.voiceRecognition)==null?void 0:ad.autoResume)!=null?id:!1,er=c=>{i.emit("voice:state",{active:dt.active,source:c,timestamp:Date.now()})},Dn=()=>{x(c=>({...c,voiceState:{active:dt.active,timestamp:Date.now(),manuallyDeactivated:dt.manuallyDeactivated}}))},os=()=>{var b,A;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Nl(p.voiceState),m=!!c.active,h=Number((A=c.timestamp)!=null?A:0);dt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<Kv&&setTimeout(()=>{var B,z;dt.active||(dt.manuallyDeactivated=!1,((z=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:z.type)==="runtype"?$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),er("restore"),$.isVoiceActive()&&is()}):Aa("restore"))},1e3)},st=()=>$?Mg($.getMessages()).filter(c=>!c.__skipPersist):[];function w(c){if(!(l!=null&&l.save))return;let h={messages:c?Mg(c):$?st():[],metadata:p,artifacts:_n.artifacts,selectedArtifactId:_n.selectedId};try{let b=l.save(h);b instanceof Promise&&b.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let q=null,U=()=>_e.querySelector("#persona-scroll-container")||Se,Q=()=>{q!==null&&(cancelAnimationFrame(q),q=null),mr=!1},fe=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),Lo=!1,Q()},Fe=()=>{qr>0?(Tn.textContent=String(qr),Tn.style.display="",$t.setAttribute("aria-label",`${bt()||"Jump to latest"} (${qr} new)`)):(Tn.textContent="",Tn.style.display="none",$t.setAttribute("aria-label",bt()||"Jump to latest"))},mt=()=>{qr!==0&&(qr=0,Fe())},Lt=()=>vt()==="follow"?!Un.isFollowing():!Vo(Se,ns),zn=()=>{if(!Wt()||X){$t.parentNode&&$t.remove(),$t.style.display="none";return}$t.parentNode!==we&&we.appendChild($t),Mn();let m=Jr(Se)>0&&Lt();m||mt(),$t.style.display=m?"":"none"},Lr=()=>{Un.pause()&&(fe(),zn())},gn=()=>{Un.resume(),mt(),zn()},Zt=(c=!1)=>{vt()==="follow"&&Un.isFollowing()&&(!c&&!Er||(ur!==null&&(cancelAnimationFrame(ur),ur=null),Lo=!0,ur=requestAnimationFrame(()=>{ur=null,Lo=!1,Un.isFollowing()&&ao(U(),c?220:140)})))},so=(c,m,h,b=()=>!0)=>{let A=c.scrollTop,B=m(),z=B-A;Q();let _=performance.now();mr=!0;let D=ae=>1-Math.pow(1-ae,3),se=ae=>{if(!b()){Q();return}let Y=m();Y!==B&&(B=Y,z=B-A);let ye=ae-_,Ne=Math.min(ye/h,1),Ce=D(Ne),tt=A+z*Ce;c.scrollTop=tt,qn=c.scrollTop,Ne<1?q=requestAnimationFrame(se):(c.scrollTop=B,qn=c.scrollTop,q=null,mr=!1)};q=requestAnimationFrame(se)},ao=(c,m=500)=>{let h=Jr(c)-c.scrollTop;if(Math.abs(h)<1){qn=c.scrollTop;return}if(Math.abs(h)>=wa){Q(),mr=!0,c.scrollTop=Jr(c),qn=c.scrollTop,mr=!1;return}so(c,()=>Jr(c),m,()=>Un.isFollowing())},Pn=()=>{let c=U();mr=!0,c.scrollTop=Jr(c),qn=c.scrollTop,mr=!1,zn()},In=c=>{xn.style.height=`${Math.max(0,Math.round(c))}px`,vn&&(vn.spacerHeight=Math.max(0,c))},wn=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),Q(),vn=null,xn.style.height="0px"},df=c=>{kr!==null&&cancelAnimationFrame(kr),kr=requestAnimationFrame(()=>{var se;kr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=Se.querySelector(`[data-message-id="${m}"]`);if(!h)return;let b=0,A=h;for(;A&&A!==Se;)b+=A.offsetTop,A=A.offsetParent;let B=(se=vn==null?void 0:vn.spacerHeight)!=null?se:0,z=Se.scrollHeight-B,{targetScrollTop:_,spacerHeight:D}=Nm({anchorOffsetTop:b,topOffset:mn(),viewportHeight:Se.clientHeight,contentHeight:z});vn={initialSpacerHeight:D,contentHeightAtAnchor:z,spacerHeight:D},In(D),so(Se,()=>_,220)})},pf=()=>{if(vt()==="follow"){if(!Un.isFollowing()||Vo(Se,1))return;Zt(!Er);return}if(vn&&vn.initialSpacerHeight>0){let c=Se.scrollHeight-vn.spacerHeight,m=Om({initialSpacerHeight:vn.initialSpacerHeight,contentHeightAtAnchor:vn.contentHeightAtAnchor,currentContentHeight:c});m!==vn.spacerHeight&&In(m)}zn()},uf=c=>{let m=vt();m==="follow"?(gn(),Zt(!0)):m==="anchor-top"&&df(c)},mf=c=>{let m=new Map;c.forEach(h=>{let b=rs.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!Po&&vt()!=="anchor-top"&&Lt()&&(qr+=1,Fe(),zn())),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}))}),rs.clear(),m.forEach((h,b)=>{rs.set(b,h)})},gf=(c,m,h)=>{var rt,Pe,ke,qe,Ke,gt;let b=document.createElement("div"),B=(()=>{var He;let I=o.find(Ie=>Ie.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((He=r.loadingIndicator)!=null&&He.render)return r.loadingIndicator.render})(),z=(I,He)=>He==null?!1:typeof He=="string"?(I.textContent=He,!0):(I.appendChild(He),!0),_=new Set,D=new Set,se=o.some(I=>I.renderAskUserQuestion),ae=[],Y=[],ye=r.enableComponentStreaming!==!1,Ne=r.approval!==!1,Ce=[];if(m.forEach(I=>{var Je,Tt,on,rr,Kn,Ro,Wo,cs,ds,Qt,Ho,co,po,Vr,Bo,gr,Ir;_.add(I.id);let He=se&&mo(I),Ie=Ne&&I.variant==="approval"&&!!I.approval,ue=!He&&I.role==="assistant"&&!I.variant&&ye&&Wl(I);if(!Ie&&pr.has(I.id)){let Xe=c.querySelector(`#wrapper-${I.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),pr.delete(I.id)}if(!ue&&Mr.has(I.id)){let Xe=c.querySelector(`#wrapper-${I.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),Mr.delete(I.id)}let Nt=mo(I)?`:${(Je=I.agentMetadata)!=null&&Je.askUserQuestionAnswered?"a":"u"}:${(Tt=I.agentMetadata)!=null&&Tt.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",Bt=Im(I,Zo)+Nt,Gt=He||Ie||ue?null:Wm(Tr,I.id,Bt);if(Gt){b.appendChild(Gt.cloneNode(!0)),mo(I)&&((on=I.toolCall)!=null&&on.id)&&((rr=I.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((Kn=I.agentMetadata)!=null&&Kn.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,ze.composerOverlay));return}let ft=null,zt=o.find(Xe=>!!(I.variant==="reasoning"&&Xe.renderReasoning||I.variant==="tool"&&Xe.renderToolCall||!I.variant&&Xe.renderMessage)),Vn=(Ro=r.layout)==null?void 0:Ro.messages;if(mo(I)&&((Wo=I.agentMetadata)==null?void 0:Wo.askUserQuestionAnswered)===!0){Ur.delete(I.id);let Xe=c.querySelector(`#wrapper-${I.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime");return}if(Wa(I)&&((ds=(cs=r.features)==null?void 0:cs.suggestReplies)==null?void 0:ds.enabled)!==!1)return;if(mo(I)&&((Ho=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Ho.enabled)!==!1){let Xe=o.find(Ot=>typeof Ot.renderAskUserQuestion=="function");if(Xe&&Ct.current){let Ot=Ur.get(I.id),Kt=Ot!==Bt,Ft=null;if(Kt){let{payload:jt,complete:fn}=go(I),Gn=I.id,Rr=()=>{var hn;return(hn=Ct.current)==null?void 0:hn.getMessages().find(yn=>yn.id===Gn)};Ft=Xe.renderAskUserQuestion({message:I,payload:jt,complete:fn,resolve:hn=>{var or;let yn=Rr();yn&&((or=Ct.current)==null||or.resolveAskUserQuestion(yn,hn))},dismiss:()=>{var yn,or,uo;let hn=Rr();(yn=hn==null?void 0:hn.agentMetadata)!=null&&yn.awaitingLocalTool&&((or=Ct.current)==null||or.markAskUserQuestionResolved(hn),(uo=Ct.current)==null||uo.resolveAskUserQuestion(hn,"(dismissed)"))},config:r})}let Xt=Ot!=null;if(Kt&&Ft===null&&!Xt){((co=I.agentMetadata)==null?void 0:co.awaitingLocalTool)===!0&&!((po=I.agentMetadata)!=null&&po.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,ze.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),ae.push({messageId:I.id,fingerprint:Bt,bubble:Ft});return}else{((Vr=I.agentMetadata)==null?void 0:Vr.awaitingLocalTool)===!0&&!((Bo=I.agentMetadata)!=null&&Bo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,ze.composerOverlay));return}}else if(Ie){let Xe=(gr=o.find(Xt=>typeof Xt.renderApproval=="function"))!=null?gr:s,Kt=pr.get(I.id)!==Bt,Ft=null;if(Kt&&(Xe!=null&&Xe.renderApproval)){let Xt=I.id,Mt=(jt,fn)=>{var Rr,hn,yn;let Gn=(Rr=Ct.current)==null?void 0:Rr.getMessages().find(or=>or.id===Xt);Gn!=null&&Gn.approval&&(Gn.approval.toolType==="webmcp"?(hn=Ct.current)==null||hn.resolveWebMcpApproval(Gn.id,jt):(yn=Ct.current)==null||yn.resolveApproval(Gn.approval,jt,fn))};Ft=Xe.renderApproval({message:I,defaultRenderer:()=>mi(I,r),config:r,approve:jt=>Mt("approved",jt),deny:jt=>Mt("denied",jt)})}if(Kt&&Ft===null){let Xt=c.querySelector(`#wrapper-${I.id}`);Xt==null||Xt.removeAttribute("data-preserve-runtime"),pr.delete(I.id),ft=mi(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),Ce.push({messageId:I.id,fingerprint:Bt,bubble:Ft});return}}else if(zt)if(I.variant==="reasoning"&&I.reasoning&&zt.renderReasoning){if(!xe)return;ft=zt.renderReasoning({message:I,defaultRenderer:()=>vl(I,r),config:r})}else if(I.variant==="tool"&&I.toolCall&&zt.renderToolCall){if(!Te)return;ft=zt.renderToolCall({message:I,defaultRenderer:()=>Cl(I,r),config:r})}else zt.renderMessage&&(ft=zt.renderMessage({message:I,defaultRenderer:()=>{let Xe=ga(I,h,Vn,r.messageActions,ge,{loadingIndicatorRenderer:B,widgetConfig:r});return I.role!=="user"&&Ml(Xe,I,r,$),Xe},config:r}));if(!ft&&ue){let Xe=Hl(I);if(Xe){let Ot=Mr.get(I.id),Kt=Ot!==Bt,Ft=r.wrapComponentDirectiveInBubble!==!1,Xt=null;if(Kt){let Mt=Rl(Xe,{config:r,message:I,transform:h});if(Mt)if(Ft){let jt=document.createElement("div");if(jt.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(" "),jt.id=`bubble-${I.id}`,jt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let fn=document.createElement("div");fn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",fn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),jt.appendChild(fn)}jt.appendChild(Mt),Xt=jt}else{let jt=document.createElement("div");if(jt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",jt.id=`bubble-${I.id}`,jt.setAttribute("data-message-id",I.id),jt.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let fn=document.createElement("div");fn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",fn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),jt.appendChild(fn)}jt.appendChild(Mt),Xt=jt}}if(Xt||Ot!=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"),Ft||Mt.classList.add("persona-w-full"),b.appendChild(Mt),Y.push({messageId:I.id,fingerprint:Bt,bubble:Xt});return}}}if(!ft)if(I.variant==="reasoning"&&I.reasoning){if(!xe)return;ft=vl(I,r)}else if(I.variant==="tool"&&I.toolCall){if(!Te)return;ft=Cl(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;ft=mi(I,r)}else{let Xe=(Ir=r.layout)==null?void 0:Ir.messages;Xe!=null&&Xe.renderUserMessage&&I.role==="user"?ft=Xe.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):Xe!=null&&Xe.renderAssistantMessage&&I.role==="assistant"?ft=Xe.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):ft=ga(I,h,Xe,r.messageActions,ge,{loadingIndicatorRenderer:B,widgetConfig:r}),I.role!=="user"&&ft&&Ml(ft,I,r,$)}let nn=document.createElement("div");nn.className="persona-flex",nn.id=`wrapper-${I.id}`,nn.setAttribute("data-wrapper-id",I.id),I.role==="user"&&nn.classList.add("persona-justify-end"),(ft==null?void 0:ft.getAttribute("data-persona-component-directive"))==="true"&&nn.classList.add("persona-w-full"),nn.appendChild(ft),Hm(Tr,I.id,Bt,nn),b.appendChild(nn)}),ze.composerOverlay&&ze.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Ie=He.getAttribute("data-persona-ask-sheet-for");Ie&&!D.has(Ie)&&$o(ze.composerOverlay,Ie)}),(Pe=(rt=r.features)==null?void 0:rt.toolCallDisplay)!=null&&Pe.grouped){let I=[],He=[];m.forEach(Ie=>{if(Ie.variant==="tool"&&Ie.toolCall&&Te){He.push(Ie);return}He.length>1&&I.push(He),He=[]}),He.length>1&&I.push(He),I.forEach((Ie,ue)=>{var Je,Tt;let Nt=Ie.map(on=>Array.from(b.children).find(rr=>rr instanceof HTMLElement&&rr.getAttribute("data-wrapper-id")===on.id)).filter(on=>!!on);if(Nt.length<2)return;let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-tool-group-${ue}-${Ie[0].id}`,Bt.setAttribute("data-wrapper-id",`tool-group-${ue}-${Ie[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.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 zt=`Called ${Ie.length} tools`,Vn=(Tt=(Je=r.toolCall)==null?void 0:Je.renderGroupedSummary)==null?void 0:Tt.call(Je,{messages:Ie,toolCalls:Ie.map(on=>on.toolCall).filter(on=>!!on),defaultSummary:zt,config:r});z(ft,Vn)||(ft.textContent=zt);let nn=document.createElement("div");nn.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(ft,nn),Bt.appendChild(Gt),Nt[0].before(Bt),Nt.forEach((on,rr)=>{let Kn=document.createElement("div");Kn.className="persona-tool-group-item persona-relative",Kn.setAttribute("data-persona-tool-group-item","true"),rr<Nt.length-1&&Kn.setAttribute("data-persona-tool-group-connector","true"),Kn.appendChild(on),nn.appendChild(Kn)})})}Bm(Tr,_);let tt=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(Er&&m.some(I=>I.role==="user")&&!tt&&!ct){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:As},He=o.find(ue=>ue.renderLoadingIndicator),Ie=null;if(He!=null&&He.renderLoadingIndicator&&(Ie=He.renderLoadingIndicator(I)),Ie===null&&((ke=r.loadingIndicator)!=null&&ke.render)&&(Ie=r.loadingIndicator.render(I)),Ie===null&&(Ie=As()),Ie){let ue=document.createElement("div"),Nt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;ue.className=Nt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ue.setAttribute("data-typing-indicator","true"),ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ue.appendChild(Ie);let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id="wrapper-typing-indicator",Bt.setAttribute("data-wrapper-id","typing-indicator"),Bt.appendChild(ue),b.appendChild(Bt)}}if(!Er&&m.length>0){let I=m[m.length-1],He={config:r,lastMessage:I,messageCount:m.length},Ie=o.find(Nt=>Nt.renderIdleIndicator),ue=null;if(Ie!=null&&Ie.renderIdleIndicator&&(ue=Ie.renderIdleIndicator(He)),ue===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(ue=r.loadingIndicator.renderIdle(He)),ue){let Nt=document.createElement("div"),Bt=((gt=r.loadingIndicator)==null?void 0:gt.showBubble)!==!1;Nt.className=Bt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Nt.setAttribute("data-idle-indicator","true"),Nt.appendChild(ue);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(Nt),b.appendChild(Gt)}}if(Ga(c,b),ae.length>0)for(let{messageId:I,fingerprint:He,bubble:Ie}of ae){let ue=c.querySelector(`#wrapper-${I}`);ue&&Ie!==null&&(ue.replaceChildren(Ie),ue.setAttribute("data-bubble-fp",He),Ur.set(I,He))}if(Ur.size>0)for(let I of Ur.keys())_.has(I)||Ur.delete(I);if(Y.length>0)for(let{messageId:I,fingerprint:He,bubble:Ie}of Y){let ue=c.querySelector(`#wrapper-${I}`);ue&&Ie!==null&&(ue.replaceChildren(Ie),ue.setAttribute("data-bubble-fp",He),Mr.set(I,He))}if(Mr.size>0)for(let I of Mr.keys())_.has(I)||Mr.delete(I);if(Ce.length>0)for(let{messageId:I,fingerprint:He,bubble:Ie}of Ce){let ue=c.querySelector(`#wrapper-${I}`);ue&&Ie!==null&&(ue.replaceChildren(Ie),ue.setAttribute("data-bubble-fp",He),pr.set(I,He))}if(pr.size>0)for(let I of pr.keys())_.has(I)||pr.delete(I)},Is=(c,m,h)=>{gf(c,m,h),eo()},Rs=null,ff=()=>{var h;if(Rs)return;let c=b=>{let A=b.composedPath();A.includes(_e)||Ve&&A.includes(Ve)||qt(!1,"user")};Rs=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Jl=()=>{var m;if(!Rs)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Rs,!0),Rs=null};ut.push(()=>Jl());let Ws=null,hf=()=>{var h;if(Ws)return;let c=b=>{b.key==="Escape"&&(b.isComposing||qt(!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};ut.push(()=>Ql());let Hs=!1,Xl=new Set,yf=()=>{var m,h,b,A;let c=(b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return c||((A=r.features)==null?void 0:A.streamAnimation)},ss=()=>{var ct,rt,Pe,ke;if(!W())return;let c=ze.peekBanner,m=ze.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 qe=h.length-1;qe>=0;qe--){let Ke=h[qe];if(Ke.role==="assistant"&&Ke.content){b=Ke;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let A=b.content,B=!!b.streaming,z=yf(),_=Za(z),D=_.type!=="none"?ia(_.type,z==null?void 0:z.plugins):null,se=((rt=D==null?void 0:D.isAnimating)==null?void 0:rt.call(D,b))===!0,ae=D!==null&&(B||se);ae&&D&&!Xl.has(D.name)&&(pl(D,e),Xl.add(D.name));let Y=ae&&(D!=null&&D.containerClass)?D.containerClass:null,ye=(Pe=m.dataset.personaPeekStreamClass)!=null?Pe:null;ye&&ye!==Y&&(m.classList.remove(ye),delete m.dataset.personaPeekStreamClass),Y&&ye!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),ae?(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 Ne=ae?ei(A,_.buffer,D,b,B):A;if(ae&&_.placeholder==="skeleton"&&B&&(!Ne||!Ne.trim())){let qe=document.createElement("div"),Ke=ca();Ke.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ke),Ga(m,qe)}else{let qe=Math.max(0,Ne.length-100),Ke=Ne.length>100?Ne.slice(-100):Ne,gt=Kr(Ke);if(!ae||!D){let I=Ne.length>100?`\u2026${Ke}`:Ke;m.textContent!==I&&(m.textContent=I)}else{let I=gt;(D.wrap==="char"||D.wrap==="word")&&(I=la(gt,D.wrap,`peek-${b.id}`,{skipTags:D.skipTags,startIndex:qe}));let He=document.createElement("div");if(He.innerHTML=I,D.useCaret&&Ke.length>0){let Ie=ti(),ue=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Nt=ue[ue.length-1];Nt!=null&&Nt.parentNode?Nt.parentNode.insertBefore(Ie,Nt.nextSibling):He.appendChild(Ie)}Ga(m,He),(ke=D.onAfterRender)==null||ke.call(D,{container:m,bubble:c,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let Ue=Er||Hs;c.classList.toggle("persona-pill-peek--visible",Ue)};if(W()){let c=ze.peekBanner;if(c){let b=A=>{A.preventDefault(),A.stopPropagation(),qt(!0,"user")};c.addEventListener("pointerdown",b),ut.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Hs||(Hs=!0,ss())},h=()=>{Hs&&(Hs=!1,ss())};J.addEventListener("pointerenter",m),J.addEventListener("pointerleave",h),ut.push(()=>{J.removeEventListener("pointerenter",m),J.removeEventListener("pointerleave",h)}),Ve&&(Ve.addEventListener("pointerenter",m),Ve.addEventListener("pointerleave",h),ut.push(()=>{Ve.removeEventListener("pointerenter",m),Ve.removeEventListener("pointerleave",h)}))}let bf=c=>{var ye,Ne,Ce,tt,Ue,ct,rt,Pe;let m=(Ne=(ye=r.launcher)==null?void 0:ye.composerBar)!=null?Ne:{},h=(Ce=m.expandedSize)!=null?Ce:"anchored",b=(tt=m.bottomOffset)!=null?tt:"16px",A=m.collapsedMaxWidth,B=(Ue=m.expandedMaxWidth)!=null?Ue:"880px",z=(ct=m.expandedTopOffset)!=null?ct:"5vh",_=(rt=m.modalMaxWidth)!=null?rt:"880px",D=(Pe=m.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",se="calc(100vw - 32px)",ae="var(--persona-pill-area-height, 80px)",Y=_e.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",Ve){let ke=Ve.style;ke.bottom=b,ke.width=A!=null?A:""}if(c&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=_,Y.maxWidth=se,Y.maxHeight=D,Y.height=D;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${ae})`,Y.top=z,Y.width=B,Y.maxWidth=se}},Bs=()=>{var D,se,ae,Y,ye,Ne,Ce,tt;if(!O())return;if(W()){let ct=(ae=((se=(D=r.launcher)==null?void 0:D.composerBar)!=null?se:{}).expandedSize)!=null?ae:"anchored",rt=N?"expanded":"collapsed";_e.dataset.state=rt,_e.dataset.expandedSize=ct,Ve&&(Ve.dataset.state=rt,Ve.dataset.expandedSize=ct),_e.style.removeProperty("display"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),bf(N),we.style.display=N?"flex":"none",Cr(),N?(ff(),hf()):(Jl(),Ql()),ss();return}let c=pn(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Ne=(ye=r.launcher)==null?void 0:ye.mobileBreakpoint)!=null?Ne:640,b=(tt=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?tt:!0,A=m.innerWidth<=h,B=b&&A&&M,z=ir(r).reveal;N?(_e.style.removeProperty("display"),_e.style.display=c?"flex":"",_e.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"),tn?tn.element.style.display="none":ln&&(ln.style.display="none")):(c?c&&(z==="overlay"||z==="push")&&!B?(_e.style.removeProperty("display"),_e.style.display="flex",_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.setProperty("display","none","important"),_e.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(_e.style.display="",_e.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")),tn?tn.element.style.display=c?"none":"":ln&&(ln.style.display=c?"none":""))},qt=(c,m="user")=>{var B,z;if(!O()||N===c)return;let h=N;N=c,Bs();let b=(()=>{var Ce,tt,Ue,ct,rt,Pe,ke,qe,Ke,gt;let _=(tt=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?tt:!1,D=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,se=(rt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?rt:!0,ae=(ke=(Pe=r.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?ke:640,Y=D.innerWidth<=ae,ye=pn(r)&&se&&Y,Ne=W()&&((gt=(Ke=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ke.expandedSize)!=null?gt:"fullscreen")==="fullscreen";return _||se&&Y&&M||ye||Ne})();if(N&&b){if(!sn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(sn=ul(D,(z=(B=r.launcher)==null?void 0:B.zIndex)!=null?z:Sn))}an||(an=ml(e.ownerDocument))}else N||(sn==null||sn(),sn=null,an==null||an(),an=null);N&&(Ds(),vt()==="follow"?Zt(!0):Pn());let A={open:N,source:m,timestamp:Date.now()};N&&!h?i.emit("widget:opened",A):!N&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:N,launcherEnabled:M,voiceActive:dt.active,streaming:$.isStreaming()})},Li=c=>{Rt(c?"stop":"send"),P&&(P.disabled=c),ko.buttons.forEach(m=>{m.disabled=c}),Le.dataset.personaComposerStreaming=c?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Pi=()=>{dt.active||Ee&&Ee.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Pi(),200)});let Yl=()=>{var h,b,A,B,z,_,D,se,ae,Y,ye;Nr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",H.textContent=(B=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",Ee.placeholder=(_=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?_:"How can I help...";let c=Se.querySelector("[data-persona-intro-card]");if(c){let Ne=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Ne?"":"none",Ne?(Se.classList.remove("persona-gap-3"),Se.classList.add("persona-gap-6")):(Se.classList.remove("persona-gap-6"),Se.classList.add("persona-gap-3"))}!((ae=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&ae)&&!($!=null&&$.isStreaming())&&($e.textContent=(ye=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ye:"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 Io=null,xf=()=>{Io==null&&(Io=setInterval(()=>{let c=Ze.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Io),Io=null;return}let m=Date.now();c.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Da(m-b))})},100))};$=new ta(r,{onMessagesChanged(c){var b;Is(Ze,c,ee),xf(),Yo(c),Zt(!Er),mf(c);let m=[...c].reverse().find(A=>A.role==="user");c.length===0&&wn(),!es||Po?(es=!0,ts=(b=m==null?void 0:m.id)!=null?b:null):m&&m.id!==ts&&(ts=m.id,uf(m.id));let h=dt.lastUserMessageId;m&&m.id!==h&&(dt.lastUserMessageId=m.id,i.emit("user:message",m)),dt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),w(c),ss()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Pt(Yt,(A=>{var B,z,_,D;return A==="idle"?(B=m.idleText)!=null?B:An.idle:A==="connecting"?(z=m.connectingText)!=null?z:An.connecting:A==="connected"?(_=m.connectedText)!=null?_:An.connected:A==="error"?(D=m.errorText)!=null?D:An.error:An[A]})(c),m,c)},onStreamingChanged(c){Er=c,Li(c),$&&Is(Ze,$.getMessages(),ee),c||Zt(!0),ss()},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":zr(),is();break;case"processing":zr(),Sf();break;case"speaking":zr(),Ef();break;default:c==="idle"&&$.isBargeInActive()?(zr(),is(),P==null||P.setAttribute("aria-label","End voice session")):(dt.active=!1,zr(),er("system"),Dn());break}},onArtifactsState(c){_n=c,Bn(),w()}}),Ct.current=$;let Ii=null;if($.onReadAloudChange((c,m)=>{var A;Yr=c,Zr=m,eo();let h=c!=null?c:Ii;c&&(Ii=c);let b=h&&(A=$.getMessages().find(B=>B.id===h))!=null?A:null;i.emit("message:read-aloud",{messageId:h,message:b,state:m,timestamp:Date.now()}),m==="idle"&&(Ii=null)}),es=!0,((cd=(ld=r.voiceRecognition)==null?void 0:ld.provider)==null?void 0:cd.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)}),(K||r.onSSEEvent)&&$.setSSEEventCallback((c,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,c,m),G==null||G.processEvent(c,m),K==null||K.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=Nl(c.metadata),k.syncFromMetadata()),(m=c.messages)!=null&&m.length){Po=!0;try{$.hydrateMessages(c.messages)}finally{Po=!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 Zl=()=>{var m,h,b;!W()||N||!((b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||qt(!0,"auto")},ec=c=>{var A;if(c.preventDefault(),$.isStreaming()){$.cancel(),G==null||G.reset(),ve==null||ve.update();return}let m=Ee.value.trim(),h=(A=wt==null?void 0:wt.hasAttachments())!=null?A:!1;if(!m&&!h)return;Zl();let b;h&&(b=[],b.push(...wt.getContentParts()),m&&b.push($a(m))),Ee.value="",Ee.style.height="auto",Ca(),$.sendMessage(m,{contentParts:b}),h&&wt.clearAttachments()},vf=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Ri={...Ja},Wi=!1,Ca=()=>{Ri={...Ja}},wf=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),Cf=c=>{if(!Ee)return;Wi=!0,Ee.value=c,Ee.dispatchEvent(new Event("input",{bubbles:!0})),Wi=!1;let m=Ee.value.length;Ee.setSelectionRange(m,m)},tc=()=>{Wi||Ca()},nc=c=>{if(Ee){if(vf()&&(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=Pm({direction:c.key==="ArrowUp"?"up":"down",history:wf(),currentValue:Ee.value,atStart:m,state:Ri});if(Ri=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Cf(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Ca(),c.preventDefault(),$e.click()}}},rc=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(we)&&($.cancel(),G==null||G.reset(),ve==null||ve.update(),Ca(),c.preventDefault(),c.stopImmediatePropagation())},oc=async c=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!wt)return;let m=Jv(c.clipboardData);m.length!==0&&(c.preventDefault(),await wt.handleFiles(m))},tr=null,Pr=!1,as=null,lt=null,sc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Aa=(c="user")=>{var B,z,_,D,se,ae,Y;if(Pr||$.isStreaming())return;let m=sc();if(!m)return;tr=new m;let b=(z=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?z:2e3;tr.continuous=!0,tr.interimResults=!0,tr.lang="en-US";let A=Ee.value;tr.onresult=ye=>{let Ne="",Ce="";for(let Ue=0;Ue<ye.results.length;Ue++){let ct=ye.results[Ue],rt=ct[0].transcript;ct.isFinal?Ne+=rt+" ":Ce=rt}let tt=A+Ne+Ce;Ee.value=tt,as&&clearTimeout(as),(Ne||Ce)&&(as=window.setTimeout(()=>{let Ue=Ee.value.trim();Ue&&tr&&Pr&&(io(),Ee.value="",Ee.style.height="auto",$.sendMessage(Ue,{viaVoice:!0}))},b))},tr.onerror=ye=>{ye.error!=="no-speech"&&io()},tr.onend=()=>{if(Pr){let ye=Ee.value.trim();ye&&ye!==A.trim()&&(Ee.value="",Ee.style.height="auto",$.sendMessage(ye,{viaVoice:!0})),io()}};try{if(tr.start(),Pr=!0,dt.active=!0,c!=="system"&&(dt.manuallyDeactivated=!1),er(c),Dn(),P){let ye=(_=r.voiceRecognition)!=null?_:{};lt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(D=ye.iconName)!=null?D:"mic",iconSize:parseFloat((Y=(ae=ye.iconSize)!=null?ae:(se=r.sendButton)==null?void 0:se.size)!=null?Y:"40")||24};let Ne=ye.recordingBackgroundColor,Ce=ye.recordingIconColor,tt=ye.recordingBorderColor;if(P.classList.add("persona-voice-recording"),P.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let Ue=P.querySelector("svg");Ue&&Ue.setAttribute("stroke",Ce)}tt&&(P.style.borderColor=tt),P.setAttribute("aria-label","Stop voice recognition")}}catch{io("system")}},io=(c="user")=>{if(Pr){if(Pr=!1,as&&(clearTimeout(as),as=null),tr){try{tr.stop()}catch{}tr=null}if(dt.active=!1,er(c),Dn(),P){if(P.classList.remove("persona-voice-recording"),lt){P.style.backgroundColor=lt.backgroundColor,P.style.color=lt.color,P.style.borderColor=lt.borderColor;let m=P.querySelector("svg");m&&m.setAttribute("stroke",lt.color||"currentColor"),lt=null}P.setAttribute("aria-label","Start voice recognition")}}},Af=(c,m)=>{var rt,Pe,ke,qe,Ke,gt,I,He,Ie;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",A=((Pe=c==null?void 0:c.provider)==null?void 0:Pe.type)==="custom";if(!(h||b||A))return null;let z=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=(ke=c==null?void 0:c.iconName)!=null?ke:"mic",se=(qe=m==null?void 0:m.size)!=null?qe:"40px",ae=(Ke=c==null?void 0:c.iconSize)!=null?Ke:se,Y=parseFloat(ae)||24,ye=(gt=c==null?void 0:c.backgroundColor)!=null?gt:m==null?void 0:m.backgroundColor,Ne=(I=c==null?void 0:c.iconColor)!=null?I:m==null?void 0:m.textColor;_.style.width=ae,_.style.height=ae,_.style.minWidth=ae,_.style.minHeight=ae,_.style.fontSize="18px",_.style.lineHeight="1",Ne?_.style.color=Ne:_.style.color="var(--persona-text, #111827)";let tt=me(D,Y,Ne||"currentColor",1.5);tt?_.appendChild(tt):_.textContent="\u{1F3A4}",ye?_.style.backgroundColor=ye:_.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),z.appendChild(_);let Ue=(He=c==null?void 0:c.tooltipText)!=null?He:"Start voice recognition";if(((Ie=c==null?void 0:c.showTooltip)!=null?Ie:!1)&&Ue){let ue=y("div","persona-send-button-tooltip");ue.textContent=Ue,z.appendChild(ue)}return{micButton:_,micButtonWrapper:z}},Hi=()=>{var m,h,b,A,B;if(!P||lt)return;let c=(m=r.voiceRecognition)!=null?m:{};lt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((B=(A=c.iconSize)!=null?A:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Bi=(c,m)=>{var B,z,_,D,se;if(!P)return;let h=P.querySelector("svg");h&&h.remove();let b=(se=lt==null?void 0:lt.iconSize)!=null?se:parseFloat((D=(_=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?_:(z=r.sendButton)==null?void 0:z.size)!=null?D:"40")||24,A=me(c,b,m,1.5);A&&P.appendChild(A)},Sa=()=>{P&&P.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},is=()=>{var A;if(!P)return;Hi();let c=(A=r.voiceRecognition)!=null?A:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,b=c.recordingBorderColor;if(Sa(),P.classList.add("persona-voice-recording"),P.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let B=P.querySelector("svg");B&&B.setAttribute("stroke",h)}b&&(P.style.borderColor=b),P.setAttribute("aria-label","Stop voice recognition")},Sf=()=>{var _,D,se,ae,Y,ye,Ne,Ce;if(!P)return;Hi();let c=(_=r.voiceRecognition)!=null?_:{},m=$.getVoiceInterruptionMode(),h=(D=c.processingIconName)!=null?D:"loader",b=(ae=(se=c.processingIconColor)!=null?se:lt==null?void 0:lt.color)!=null?ae:"",A=(ye=(Y=c.processingBackgroundColor)!=null?Y:lt==null?void 0:lt.backgroundColor)!=null?ye:"",B=(Ce=(Ne=c.processingBorderColor)!=null?Ne:lt==null?void 0:lt.borderColor)!=null?Ce:"";Sa(),P.classList.add("persona-voice-processing"),P.style.backgroundColor=A,P.style.borderColor=B;let z=b||"currentColor";P.style.color=z,Bi(h,z),P.setAttribute("aria-label","Processing voice input"),m==="none"&&(P.style.cursor="default")},Ef=()=>{var se,ae,Y,ye,Ne,Ce,tt,Ue,ct,rt,Pe,ke;if(!P)return;Hi();let c=(se=r.voiceRecognition)!=null?se:{},m=$.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(ae=c.speakingIconName)!=null?ae:h,A=(Ce=c.speakingIconColor)!=null?Ce:m==="barge-in"?(ye=(Y=c.recordingIconColor)!=null?Y:lt==null?void 0:lt.color)!=null?ye:"":(Ne=lt==null?void 0:lt.color)!=null?Ne:"",B=(ct=c.speakingBackgroundColor)!=null?ct:m==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Ue=lt==null?void 0:lt.backgroundColor)!=null?Ue:"",z=(ke=c.speakingBorderColor)!=null?ke:m==="barge-in"?(rt=c.recordingBorderColor)!=null?rt:"":(Pe=lt==null?void 0:lt.borderColor)!=null?Pe:"";Sa(),P.classList.add("persona-voice-speaking"),P.style.backgroundColor=B,P.style.borderColor=z;let _=A||"currentColor";P.style.color=_,Bi(b,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";P.setAttribute("aria-label",D),m==="none"&&(P.style.cursor="default"),m==="barge-in"&&P.classList.add("persona-voice-recording")},zr=()=>{var c,m,h;P&&(Sa(),lt&&(P.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",P.style.color=(m=lt.color)!=null?m:"",P.style.borderColor=(h=lt.borderColor)!=null?h:"",Bi(lt.iconName,lt.color||"currentColor"),lt=null),P.style.cursor="",P.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(()=>{dt.active=!1,dt.manuallyDeactivated=!0,Dn(),er("user"),zr()});return}$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),dt.manuallyDeactivated=!$.isVoiceActive(),Dn(),er("user"),$.isVoiceActive()?is():zr()});return}if(Pr){let h=Ee.value.trim();dt.manuallyDeactivated=!0,Dn(),io("user"),h&&(Ee.value="",Ee.style.height="auto",$.sendMessage(h))}else dt.manuallyDeactivated=!1,Dn(),Aa("user")};xr=Ea,P&&(P.addEventListener("click",Ea),ut.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),zr()):io("system"),P&&P.removeEventListener("click",Ea)}));let Tf=i.on("assistant:complete",()=>{Ps&&(dt.active||dt.manuallyDeactivated||Ps==="assistant"&&!dt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!dt.active&&!dt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),er("auto"),$.isVoiceActive()&&is()}):Aa("auto"))},600))});ut.push(Tf);let Mf=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ut.push(Mf);let ac=()=>{qt(!N,"user")},tn=null,ln=null;if(M&&!W()){let{instance:c,element:m}=yl({config:r,plugins:o,onToggle:ac});tn=c,c||(ln=m)}tn?e.appendChild(tn.element):ln&&e.appendChild(ln),Bs(),Yo(),Yl(),Li($.isStreaming()),vt()==="follow"?Zt(!0):Pn(),os(),L&&(!M||W()?setTimeout(()=>Pi(),0):N&&setTimeout(()=>Pi(),200));let Ds=()=>{var D,se,ae,Y,ye,Ne,Ce,tt,Ue,ct,rt,Pe,ke,qe,Ke,gt,I,He,Ie,ue,Nt,Bt;if(W()){Mn(),Bs();return}let c=pn(r),m=(se=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?se:!1,h=c||m||((Y=(ae=r.launcher)==null?void 0:ae.fullHeight)!=null?Y:!1),b=(ye=e.ownerDocument.defaultView)!=null?ye:window,A=(Ce=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ce:!0,B=(Ue=(tt=r.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Ue:640,z=b.innerWidth<=B,_=A&&z&&M;try{if(_){Cr(),zo(e,r);return}if(j&&(j=!1,Cr(),zo(e,r)),!M&&!c){J.style.height="",J.style.width="";return}if(!m&&!c){let Gt=(rt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?rt:r==null?void 0:r.launcherWidth,ft=Gt!=null?Gt:ar;J.style.width=ft,J.style.maxWidth=ft}if(he(),!h){let Gt=b.innerHeight,ft=64,zt=(ke=(Pe=r.launcher)==null?void 0:Pe.heightOffset)!=null?ke:0,Vn=Math.max(200,Gt-ft),nn=Math.min(640,Vn),Je=Math.max(200,nn-zt);J.style.height=`${Je}px`}}finally{if(Mn(),Bs(),N&&M){let ft=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((gt=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?gt:640),zt=(He=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?He:!1,Vn=(ue=(Ie=r.launcher)==null?void 0:Ie.mobileFullscreen)!=null?ue:!0,nn=pn(r)&&Vn&&ft,Je=zt||Vn&&ft&&M||nn;if(Je&&!an){let Tt=e.getRootNode(),on=Tt instanceof ShadowRoot?Tt.host:e.closest(".persona-host");on&&!sn&&(sn=ul(on,(Bt=(Nt=r.launcher)==null?void 0:Nt.zIndex)!=null?Bt:Sn)),an=ml(e.ownerDocument)}else Je||(sn==null||sn(),sn=null,an==null||an(),an=null)}}};Ds();let ic=(dd=e.ownerDocument.defaultView)!=null?dd:window;if(ic.addEventListener("resize",Ds),ut.push(()=>ic.removeEventListener("resize",Ds)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Mn()});c.observe(Le),ut.push(()=>c.disconnect())}qn=Se.scrollTop;let lc=Jr(Se),kf=()=>{let c=Se.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:Se.ownerDocument.getSelection()},Di=()=>Dm(kf(),Se),cc=()=>{let c=Se.scrollTop,m=Jr(Se),h=m<lc;if(lc=m,vt()!=="follow"){qn=c,zn();return}let{action:b,nextLastScrollTop:A}=Xa({following:Un.isFollowing(),currentScrollTop:c,lastScrollTop:qn,nearBottom:Vo(Se,ns),userScrollThreshold:va,isAutoScrolling:mr||Lo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(qn=A,b==="resume"){Di()||gn();return}b==="pause"&&Lr()};if(Se.addEventListener("scroll",cc,{passive:!0}),ut.push(()=>Se.removeEventListener("scroll",cc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{pf()});c.observe(Ze),c.observe(Se),ut.push(()=>c.disconnect())}let dc=()=>{vt()==="follow"&&Un.isFollowing()&&Di()&&Lr()},pc=Se.ownerDocument;pc.addEventListener("selectionchange",dc),ut.push(()=>{pc.removeEventListener("selectionchange",dc)});let uc=c=>{if(vt()!=="follow")return;let m=Ya({following:Un.isFollowing(),deltaY:c.deltaY,nearBottom:Vo(Se,ns),resumeWhenNearBottom:!0});m==="pause"?Lr():m==="resume"&&!Di()&&gn()};Se.addEventListener("wheel",uc,{passive:!0}),ut.push(()=>Se.removeEventListener("wheel",uc)),$t.addEventListener("click",()=>{wn(),Se.scrollTop=Se.scrollHeight,qn=Se.scrollTop,gn(),Zt(!0),zn()}),ut.push(()=>$t.remove()),ut.push(()=>{fe(),wn()});let mc=()=>{V&&(Sr&&(V.removeEventListener("click",Sr),Sr=null),O()?(V.style.display="",Sr=()=>{qt(!1,"user")},V.addEventListener("click",Sr)):V.style.display="none")};mc(),(()=>{let{clearChatButton:c}=ze;c&&c.addEventListener("click",()=>{$.clearMessages(),Tr.clear(),gn(),$o(ze.composerOverlay);try{localStorage.removeItem(ks),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ks}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ks)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={},k.syncFromMetadata(),K==null||K.clear(),G==null||G.reset(),ve==null||ve.update()})})(),Dt&&Dt.addEventListener("submit",ec),Ee==null||Ee.addEventListener("keydown",nc),Ee==null||Ee.addEventListener("input",tc),Ee==null||Ee.addEventListener("paste",oc);let gc=(pd=e.ownerDocument)!=null?pd:document;gc.addEventListener("keydown",rc,!0);let fc="persona-attachment-drop-active",Ns=0,Ni=()=>{Ns=0,we.classList.remove(fc)},ls=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&wt!==null},hc=c=>{!vi(c.dataTransfer)||!ls()||(Ns++,Ns===1&&we.classList.add(fc))},yc=c=>{!vi(c.dataTransfer)||!ls()||(Ns--,Ns<=0&&Ni())},bc=c=>{!vi(c.dataTransfer)||!ls()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},xc=c=>{var h;if(!vi(c.dataTransfer)||!ls())return;c.preventDefault(),c.stopPropagation(),Ni();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&wt.handleFiles(m)},lo=!0;we.addEventListener("dragenter",hc,lo),we.addEventListener("dragleave",yc,lo),e.addEventListener("dragover",bc,lo),e.addEventListener("drop",xc,lo);let Ta=e.ownerDocument,vc=c=>{ls()&&c.preventDefault()},wc=c=>{ls()&&c.preventDefault()};Ta.addEventListener("dragover",vc),Ta.addEventListener("drop",wc),ut.push(()=>{Dt&&Dt.removeEventListener("submit",ec),Ee==null||Ee.removeEventListener("keydown",nc),Ee==null||Ee.removeEventListener("input",tc),Ee==null||Ee.removeEventListener("paste",oc),gc.removeEventListener("keydown",rc,!0)}),ut.push(()=>{we.removeEventListener("dragenter",hc,lo),we.removeEventListener("dragleave",yc,lo),e.removeEventListener("dragover",bc,lo),e.removeEventListener("drop",xc,lo),Ta.removeEventListener("dragover",vc),Ta.removeEventListener("drop",wc),Ni()}),ut.push(()=>{$.cancel()}),tn?ut.push(()=>{tn==null||tn.destroy()}):ln&&ut.push(()=>{ln==null||ln.remove()});let rn={update(c){var jt,fn,Gn,Rr,hn,yn,or,uo,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Qd,Xd,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,Ep,Tp,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu;let m=r.toolCall,h=r.messageActions,b=(jt=r.layout)==null?void 0:jt.messages,A=r.colorScheme,B=r.loadingIndicator,z=r.iterationDisplay,_=(fn=r.features)==null?void 0:fn.showReasoning,D=(Gn=r.features)==null?void 0:Gn.showToolCalls,se=(Rr=r.features)==null?void 0:Rr.toolCallDisplay,ae=(hn=r.features)==null?void 0:hn.reasoningDisplay;r={...r,...c},Cr(),zo(e,r),fi(e,r),hi(e,r),Bn(),r.colorScheme!==A&&Ls();let Y=yi.getForInstance(r.plugins);o.length=0,o.push(...Y),M=(or=(yn=r.launcher)==null?void 0:yn.enabled)!=null?or:!0,E=(bd=(uo=r.launcher)==null?void 0:uo.autoExpand)!=null?bd:!1,xe=(vd=(xd=r.features)==null?void 0:xd.showReasoning)!=null?vd:!0,Te=(Cd=(wd=r.features)==null?void 0:wd.showToolCalls)!=null?Cd:!0,be=(Sd=(Ad=r.features)==null?void 0:Ad.scrollToBottom)!=null?Sd:{};let ye=vt();le=(Td=(Ed=r.features)==null?void 0:Ed.scrollBehavior)!=null?Td:{},ye!==vt()&&(wn(),gn()),cr(),zn();let Ne=ne;if(ne=(kd=(Md=r.features)==null?void 0:Md.showEventStreamToggle)!=null?kd:!1,ne&&!Ne){if(K||(We=new ha(re),K=new fa(Oe,We),G=G!=null?G:new ya,We.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),$.setSSEEventCallback((te,At)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,te,At),G==null||G.processEvent(te,At),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(At)})})),!pt&&De){let te=(Pd=(Ld=r.features)==null?void 0:Ld.eventStream)==null?void 0:Pd.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"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");pt=y("button",At),pt.style.width="28px",pt.style.height="28px",pt.style.color=Wn.actionIconColor,pt.type="button",pt.setAttribute("aria-label","Event Stream"),pt.title="Event Stream";let Vt=me("activity","18px","currentColor",1.5);Vt&&pt.appendChild(Vt);let ot=ze.clearChatButtonWrapper,kt=ze.closeButtonWrapper,cn=ot||kt;cn&&cn.parentNode===De?De.insertBefore(pt,cn):De.appendChild(pt),pt.addEventListener("click",()=>{X?dr():Or()})}}else!ne&&Ne&&(dr(),pt&&(pt.remove(),pt=null),K==null||K.clear(),We==null||We.destroy(),K=null,We=null,G==null||G.reset(),G=null);if(((Id=r.launcher)==null?void 0:Id.enabled)===!1&&tn&&(tn.destroy(),tn=null),((Rd=r.launcher)==null?void 0:Rd.enabled)===!1&&ln&&(ln.remove(),ln=null),((Wd=r.launcher)==null?void 0:Wd.enabled)!==!1&&!tn&&!ln){let{instance:te,element:At}=yl({config:r,plugins:o,onToggle:ac});tn=te,te||(ln=At),e.appendChild(At)}tn&&tn.update(r),Be&&((Hd=r.launcher)==null?void 0:Hd.title)!==void 0&&(Be.textContent=r.launcher.title),je&&((Bd=r.launcher)==null?void 0:Bd.subtitle)!==void 0&&(je.textContent=r.launcher.subtitle);let Ce=(Dd=r.layout)==null?void 0:Dd.header;if((Ce==null?void 0:Ce.layout)!==F&&De){let te=Ce?ua(r,Ce,{showClose:O(),onClose:()=>qt(!1,"user")}):wo({config:r,showClose:O(),onClose:()=>qt(!1,"user")});Ye.replaceHeader(te),De=Ye.header.element,pe=Ye.header.iconHolder,Be=Ye.header.headerTitle,je=Ye.header.headerSubtitle,V=Ye.header.closeButton,F=Ce==null?void 0:Ce.layout}else if(Ce&&(pe&&(pe.style.display=Ce.showIcon===!1?"none":""),Be&&(Be.style.display=Ce.showTitle===!1?"none":""),je&&(je.style.display=Ce.showSubtitle===!1?"none":""),V&&(V.style.display=Ce.showCloseButton===!1?"none":""),ze.clearChatButtonWrapper)){let te=Ce.showClearChat;if(te!==void 0){ze.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:At}=ze;At&&!At.classList.contains("persona-absolute")&&(te?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let Ue=((Nd=r.layout)==null?void 0:Nd.showHeader)!==!1;De&&(De.style.display=Ue?"":"none");let ct=((Od=r.layout)==null?void 0:Od.showFooter)!==!1;Le&&(Le.style.display=ct?"":"none"),Mn(),zn(),M!==R?M?qt(E,"auto"):(N=!0,Bs()):E!==C&&qt(E,"auto"),C=E,R=M,Ds(),mc();let ke=JSON.stringify(c.toolCall)!==JSON.stringify(m),qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((Fd=r.layout)==null?void 0:Fd.messages)!==JSON.stringify(b),gt=((_d=r.loadingIndicator)==null?void 0:_d.render)!==(B==null?void 0:B.render)||(($d=r.loadingIndicator)==null?void 0:$d.renderIdle)!==(B==null?void 0:B.renderIdle)||((jd=r.loadingIndicator)==null?void 0:jd.showBubble)!==(B==null?void 0:B.showBubble),I=r.iterationDisplay!==z,He=((qd=(Ud=r.features)==null?void 0:Ud.showReasoning)!=null?qd:!0)!==(_!=null?_:!0)||((Vd=(zd=r.features)==null?void 0:zd.showToolCalls)!=null?Vd:!0)!==(D!=null?D:!0)||JSON.stringify((Kd=r.features)==null?void 0:Kd.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((Gd=r.features)==null?void 0:Gd.reasoningDisplay)!==JSON.stringify(ae);(ke||qe||Ke||gt||I||He)&&$&&(Zo++,Is(Ze,$.getMessages(),ee));let ue=(Jd=r.launcher)!=null?Jd:{},Nt=(Qd=ue.headerIconHidden)!=null?Qd:!1,Bt=(Yd=(Xd=r.layout)==null?void 0:Xd.header)==null?void 0:Yd.showIcon,Gt=Nt||Bt===!1,ft=ue.headerIconName,zt=(Zd=ue.headerIconSize)!=null?Zd:"48px";if(pe){let te=we.querySelector(".persona-border-b-persona-divider"),At=te==null?void 0:te.querySelector(".persona-flex-col");if(Gt)pe.style.display="none",te&&At&&!te.contains(At)&&te.insertBefore(At,te.firstChild);else{if(pe.style.display="",pe.style.height=zt,pe.style.width=zt,te&&At&&(te.contains(pe)?pe.nextSibling!==At&&(pe.remove(),te.insertBefore(pe,At)):te.insertBefore(pe,At)),ft){let ot=parseFloat(zt)||24,kt=me(ft,ot*.6,"currentColor",1);kt?pe.replaceChildren(kt):pe.textContent=(ep=ue.agentIconText)!=null?ep:"\u{1F4AC}"}else if(ue.iconUrl){let ot=pe.querySelector("img");if(ot)ot.src=ue.iconUrl,ot.style.height=zt,ot.style.width=zt;else{let kt=document.createElement("img");kt.src=ue.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=zt,kt.style.width=zt,pe.replaceChildren(kt)}}else{let ot=pe.querySelector("svg"),kt=pe.querySelector("img");(ot||kt)&&pe.replaceChildren(),pe.textContent=(tp=ue.agentIconText)!=null?tp:"\u{1F4AC}"}let Vt=pe.querySelector("img");Vt&&(Vt.style.height=zt,Vt.style.width=zt)}}let Vn=(rp=(np=r.layout)==null?void 0:np.header)==null?void 0:rp.showTitle,nn=(sp=(op=r.layout)==null?void 0:op.header)==null?void 0:sp.showSubtitle;if(Be&&(Be.style.display=Vn===!1?"none":""),je&&(je.style.display=nn===!1?"none":""),V){((ip=(ap=r.layout)==null?void 0:ap.header)==null?void 0:ip.showCloseButton)===!1?V.style.display="none":V.style.display="";let At=(lp=ue.closeButtonSize)!=null?lp:"32px",Vt=(cp=ue.closeButtonPlacement)!=null?cp:"inline";V.style.height=At,V.style.width=At;let{closeButtonWrapper:ot}=ze,kt=Vt==="top-right",cn=ot==null?void 0:ot.classList.contains("persona-absolute");if(ot&&kt!==cn)if(ot.remove(),kt)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",we.style.position="relative",we.appendChild(ot);else{let at=(pp=(dp=ue.clearChat)==null?void 0:dp.placement)!=null?pp:"inline",dn=(mp=(up=ue.clearChat)==null?void 0:up.enabled)!=null?mp:!0;ot.className=dn&&at==="inline"?"":"persona-ml-auto";let Nn=we.querySelector(".persona-border-b-persona-divider");Nn&&Nn.appendChild(ot)}if(V.style.color=ue.closeButtonColor||Wn.actionIconColor,ue.closeButtonBackgroundColor?(V.style.backgroundColor=ue.closeButtonBackgroundColor,V.classList.remove("hover:persona-bg-gray-100")):(V.style.backgroundColor="",V.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let at=ue.closeButtonBorderWidth||"0px",dn=ue.closeButtonBorderColor||"transparent";V.style.border=`${at} solid ${dn}`,V.classList.remove("persona-border-none")}else V.style.border="",V.classList.add("persona-border-none");ue.closeButtonBorderRadius?(V.style.borderRadius=ue.closeButtonBorderRadius,V.classList.remove("persona-rounded-full")):(V.style.borderRadius="",V.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(V.style.paddingLeft=ue.closeButtonPaddingX,V.style.paddingRight=ue.closeButtonPaddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ue.closeButtonPaddingY?(V.style.paddingTop=ue.closeButtonPaddingY,V.style.paddingBottom=ue.closeButtonPaddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Cn=(gp=ue.closeButtonIconName)!=null?gp:"x",fr=(fp=ue.closeButtonIconText)!=null?fp:"\xD7";V.innerHTML="";let Rn=me(Cn,"28px","currentColor",1);Rn?V.appendChild(Rn):V.textContent=fr;let en=(hp=ue.closeButtonTooltipText)!=null?hp:"Close chat",Jn=(yp=ue.closeButtonShowTooltip)!=null?yp:!0;if(V.setAttribute("aria-label",en),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),Jn&&en)){let at=null,dn=()=>{if(at||!V)return;let Do=V.ownerDocument,Os=Do.body;if(!Os)return;at=Hr(Do,"div","persona-clear-chat-tooltip"),at.textContent=en;let Fs=Hr(Do,"div");Fs.className="persona-clear-chat-tooltip-arrow",at.appendChild(Fs);let No=V.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(bo),at.style.left=`${No.left+No.width/2}px`,at.style.top=`${No.top-8}px`,at.style.transform="translate(-50%, -100%)",Os.appendChild(at)},Nn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};ot.addEventListener("mouseenter",dn),ot.addEventListener("mouseleave",Nn),V.addEventListener("focus",dn),V.addEventListener("blur",Nn),ot._cleanupTooltip=()=>{Nn(),ot&&(ot.removeEventListener("mouseenter",dn),ot.removeEventListener("mouseleave",Nn)),V&&(V.removeEventListener("focus",dn),V.removeEventListener("blur",Nn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Tt}=ze;if(Je){let te=(bp=ue.clearChat)!=null?bp:{},At=(xp=te.enabled)!=null?xp:!0,Vt=(wp=(vp=r.layout)==null?void 0:vp.header)==null?void 0:wp.showClearChat,ot=Vt!==void 0?Vt:At,kt=(Cp=te.placement)!=null?Cp:"inline";if(Tt){Tt.style.display=ot?"":"none";let{closeButtonWrapper:cn}=ze;!W()&&cn&&!cn.classList.contains("persona-absolute")&&(ot?cn.classList.remove("persona-ml-auto"):cn.classList.add("persona-ml-auto"));let Cn=kt==="top-right",fr=Tt.classList.contains("persona-absolute");if(!W()&&Cn!==fr&&ot){if(Tt.remove(),Cn)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",we.style.position="relative",we.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let en=we.querySelector(".persona-border-b-persona-divider"),Jn=ze.closeButtonWrapper;en&&Jn&&Jn.parentElement===en?en.insertBefore(Tt,Jn):en&&en.appendChild(Tt)}let Rn=ze.closeButtonWrapper;Rn&&!Rn.classList.contains("persona-absolute")&&(Cn?Rn.classList.add("persona-ml-auto"):Rn.classList.remove("persona-ml-auto"))}}if(ot){if(!W()){let at=(Ap=te.size)!=null?Ap:"32px";Je.style.height=at,Je.style.width=at}let cn=(Sp=te.iconName)!=null?Sp:"refresh-cw",Cn=(Ep=te.iconColor)!=null?Ep:"";Je.style.color=Cn||Wn.actionIconColor,Je.innerHTML="";let fr=W()?"14px":"20px",Rn=me(cn,fr,"currentColor",2);if(Rn&&Je.appendChild(Rn),te.backgroundColor?(Je.style.backgroundColor=te.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let at=te.borderWidth||"0px",dn=te.borderColor||"transparent";Je.style.border=`${at} solid ${dn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");te.borderRadius?(Je.style.borderRadius=te.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),te.paddingX?(Je.style.paddingLeft=te.paddingX,Je.style.paddingRight=te.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),te.paddingY?(Je.style.paddingTop=te.paddingY,Je.style.paddingBottom=te.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let en=(Tp=te.tooltipText)!=null?Tp:"Clear chat",Jn=(Mp=te.showTooltip)!=null?Mp:!0;if(Je.setAttribute("aria-label",en),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),Jn&&en)){let at=null,dn=()=>{if(at||!Je)return;let Do=Je.ownerDocument,Os=Do.body;if(!Os)return;at=Hr(Do,"div","persona-clear-chat-tooltip"),at.textContent=en;let Fs=Hr(Do,"div");Fs.className="persona-clear-chat-tooltip-arrow",at.appendChild(Fs);let No=Je.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(bo),at.style.left=`${No.left+No.width/2}px`,at.style.top=`${No.top-8}px`,at.style.transform="translate(-50%, -100%)",Os.appendChild(at)},Nn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};Tt.addEventListener("mouseenter",dn),Tt.addEventListener("mouseleave",Nn),Je.addEventListener("focus",dn),Je.addEventListener("blur",Nn),Tt._cleanupTooltip=()=>{Nn(),Tt&&(Tt.removeEventListener("mouseenter",dn),Tt.removeEventListener("mouseleave",Nn)),Je&&(Je.removeEventListener("focus",dn),Je.removeEventListener("blur",Nn))}}}}let on=r.actionParsers&&r.actionParsers.length?r.actionParsers:[bi],rr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ms.message,Ms.messageAndClick];k=xi({parsers:on,handlers:rr,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=kg(r,k,de),$.updateConfig(r),Is(Ze,$.getMessages(),ee),Yo(),Yl(),Li($.isStreaming());let Kn=((kp=r.voiceRecognition)==null?void 0:kp.enabled)===!0,Ro=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Wo=((Pp=(Lp=r.voiceRecognition)==null?void 0:Lp.provider)==null?void 0:Pp.type)==="runtype";if(Kn&&(Ro||Wo))if(!P||!ce){let te=Af(r.voiceRecognition,r.sendButton);te&&(P=te.micButton,ce=te.micButtonWrapper,ht.insertBefore(ce,un),P.addEventListener("click",Ea),P.disabled=$.isStreaming())}else{let te=(Ip=r.voiceRecognition)!=null?Ip:{},At=(Rp=r.sendButton)!=null?Rp:{},Vt=(Wp=te.iconName)!=null?Wp:"mic",ot=(Hp=At.size)!=null?Hp:"40px",kt=(Bp=te.iconSize)!=null?Bp:ot,cn=parseFloat(kt)||24;P.style.width=kt,P.style.height=kt,P.style.minWidth=kt,P.style.minHeight=kt;let Cn=(Np=(Dp=te.iconColor)!=null?Dp:At.textColor)!=null?Np:"currentColor";P.innerHTML="";let fr=me(Vt,cn,Cn,2);fr?P.appendChild(fr):P.textContent="\u{1F3A4}";let Rn=(Op=te.backgroundColor)!=null?Op:At.backgroundColor;Rn?P.style.backgroundColor=Rn:P.style.backgroundColor="",Cn?P.style.color=Cn:P.style.color="var(--persona-text, #111827)",te.borderWidth?(P.style.borderWidth=te.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),te.borderColor?P.style.borderColor=te.borderColor:P.style.borderColor="",te.paddingX?(P.style.paddingLeft=te.paddingX,P.style.paddingRight=te.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),te.paddingY?(P.style.paddingTop=te.paddingY,P.style.paddingBottom=te.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let en=ce==null?void 0:ce.querySelector(".persona-send-button-tooltip"),Jn=(Fp=te.tooltipText)!=null?Fp:"Start voice recognition";if(((_p=te.showTooltip)!=null?_p:!1)&&Jn)if(en)en.textContent=Jn,en.style.display="";else{let dn=document.createElement("div");dn.className="persona-send-button-tooltip",dn.textContent=Jn,ce==null||ce.insertBefore(dn,P)}else en&&(en.style.display="none");ce.style.display="",P.disabled=$.isStreaming()}else P&&ce&&(ce.style.display="none",((jp=($p=r.voiceRecognition)==null?void 0:$p.provider)==null?void 0:jp.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Pr&&io());if(((Up=r.attachments)==null?void 0:Up.enabled)===!0)if(!Et||!Me){let te=(qp=r.attachments)!=null?qp:{},Vt=(Vp=((zp=r.sendButton)!=null?zp:{}).size)!=null?Vp:"40px";Ut||(Ut=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ut.style.display="none",Dt.insertBefore(Ut,Ee)),et||(et=document.createElement("input"),et.type="file",et.accept=((Kp=te.allowedTypes)!=null?Kp:Gr).join(","),et.multiple=((Gp=te.maxFiles)!=null?Gp:4)>1,et.style.display="none",et.setAttribute("aria-label","Attach files"),Dt.insertBefore(et,Ee)),Et=y("div","persona-send-button-wrapper"),Me=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Me.type="button",Me.setAttribute("aria-label",(Jp=te.buttonTooltipText)!=null?Jp:"Attach file");let ot=(Qp=te.buttonIconName)!=null?Qp:"paperclip",kt=Vt,cn=parseFloat(kt)||40,Cn=Math.round(cn*.6);Me.style.width=kt,Me.style.height=kt,Me.style.minWidth=kt,Me.style.minHeight=kt,Me.style.fontSize="18px",Me.style.lineHeight="1",Me.style.backgroundColor="transparent",Me.style.color="var(--persona-primary, #111827)",Me.style.border="none",Me.style.borderRadius="6px",Me.style.transition="background-color 0.15s ease",Me.addEventListener("mouseenter",()=>{Me.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Me.addEventListener("mouseleave",()=>{Me.style.backgroundColor="transparent"});let fr=me(ot,Cn,"currentColor",1.5);fr?Me.appendChild(fr):Me.textContent="\u{1F4CE}",Me.addEventListener("click",Jn=>{Jn.preventDefault(),et==null||et.click()}),Et.appendChild(Me);let Rn=(Xp=te.buttonTooltipText)!=null?Xp:"Attach file",en=y("div","persona-send-button-tooltip");en.textContent=Rn,Et.appendChild(en),It.append(Et),!wt&&et&&Ut&&(wt=vs.fromConfig(te),wt.setPreviewsContainer(Ut),et.addEventListener("change",async()=>{wt&&(et!=null&&et.files)&&(await wt.handleFileSelect(et.files),et.value="")})),we.querySelector(".persona-attachment-drop-overlay")||we.appendChild(Lg(te.dropOverlay))}else{Et.style.display="";let te=(Yp=r.attachments)!=null?Yp:{};et&&(et.accept=((Zp=te.allowedTypes)!=null?Zp:Gr).join(","),et.multiple=((eu=te.maxFiles)!=null?eu:4)>1),wt&&wt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else Et&&(Et.style.display="none"),wt&&wt.clearAttachments(),(tu=we.querySelector(".persona-attachment-drop-overlay"))==null||tu.remove();let Qt=(nu=r.sendButton)!=null?nu:{},Ho=(ru=Qt.useIcon)!=null?ru:!1,co=(ou=Qt.iconText)!=null?ou:"\u2191",po=Qt.iconName,Vr=(su=Qt.tooltipText)!=null?su:"Send message",Bo=(au=Qt.showTooltip)!=null?au:!1,gr=(iu=Qt.size)!=null?iu:"40px",Ir=Qt.backgroundColor,Xe=Qt.textColor;if(Ho){if($e.style.width=gr,$e.style.height=gr,$e.style.minWidth=gr,$e.style.minHeight=gr,$e.style.fontSize="18px",$e.style.lineHeight="1",$e.innerHTML="",Xe?$e.style.color=Xe:$e.style.color="var(--persona-button-primary-fg, #ffffff)",po){let te=parseFloat(gr)||24,At=(Xe==null?void 0:Xe.trim())||"currentColor",Vt=me(po,te,At,2);Vt?$e.appendChild(Vt):$e.textContent=co}else $e.textContent=co;$e.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ir?($e.style.backgroundColor=Ir,$e.classList.remove("persona-bg-persona-primary")):($e.style.backgroundColor="",$e.classList.add("persona-bg-persona-primary"))}else $e.textContent=(cu=(lu=r.copy)==null?void 0:lu.sendButtonLabel)!=null?cu:"Send",$e.style.width="",$e.style.height="",$e.style.minWidth="",$e.style.minHeight="",$e.style.fontSize="",$e.style.lineHeight="",$e.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",Ir?($e.style.backgroundColor=Ir,$e.classList.remove("persona-bg-persona-accent")):$e.classList.add("persona-bg-persona-accent"),Xe?$e.style.color=Xe:$e.classList.add("persona-text-white");Qt.borderWidth?($e.style.borderWidth=Qt.borderWidth,$e.style.borderStyle="solid"):($e.style.borderWidth="",$e.style.borderStyle=""),Qt.borderColor?$e.style.borderColor=Qt.borderColor:$e.style.borderColor="",Qt.paddingX?($e.style.paddingLeft=Qt.paddingX,$e.style.paddingRight=Qt.paddingX):($e.style.paddingLeft="",$e.style.paddingRight=""),Qt.paddingY?($e.style.paddingTop=Qt.paddingY,$e.style.paddingBottom=Qt.paddingY):($e.style.paddingTop="",$e.style.paddingBottom="");let Ot=un==null?void 0:un.querySelector(".persona-send-button-tooltip");if(Bo&&Vr)if(Ot)Ot.textContent=Vr,Ot.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Vr,un==null||un.insertBefore(te,$e)}else Ot&&(Ot.style.display="none");let Kt=(gu=(du=r.layout)==null?void 0:du.contentMaxWidth)!=null?gu:W()?(mu=(uu=(pu=r.launcher)==null?void 0:pu.composerBar)==null?void 0:uu.contentMaxWidth)!=null?mu:"720px":void 0;Kt?(Ze.style.maxWidth=Kt,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",Dt&&(Dt.style.maxWidth=Kt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Qe&&(Qe.style.maxWidth=Kt,Qe.style.marginLeft="auto",Qe.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),Qe&&(Qe.style.maxWidth="",Qe.style.marginLeft="",Qe.style.marginRight=""));let Ft=(fu=r.statusIndicator)!=null?fu:{},Xt=(hu=Ft.visible)!=null?hu:!0;if(Yt.style.display=Xt?"":"none",$){let te=$.getStatus();Pt(Yt,(Vt=>{var ot,kt,cn,Cn;return Vt==="idle"?(ot=Ft.idleText)!=null?ot:An.idle:Vt==="connecting"?(kt=Ft.connectingText)!=null?kt:An.connecting:Vt==="connected"?(cn=Ft.connectedText)!=null?cn:An.connected:Vt==="error"?(Cn=Ft.errorText)!=null?Cn:An.error:An[Vt]})(te),Ft,te)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mt=Ft.align==="left"?"persona-text-left":Ft.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(Mt)},open(){O()&&qt(!0,"api")},close(){O()&&qt(!1,"api")},toggle(){O()&&qt(!N,"api")},clearChat(){kn=!1,$.clearMessages(),Tr.clear(),gn();try{localStorage.removeItem(ks),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ks}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ks)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={},k.syncFromMetadata(),K==null||K.clear(),G==null||G.reset(),ve==null||ve.update()},setMessage(c){return!Ee||$.isStreaming()?!1:(!N&&O()&&qt(!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()&&qt(!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()&&qt(!0,"system"),dt.manuallyDeactivated=!1,Dn(),$.toggleVoice().then(()=>{dt.active=$.isVoiceActive(),er("user"),$.isVoiceActive()&&is()})),!0):Pr?!0:sc()?(!N&&O()&&qt(!0,"system"),dt.manuallyDeactivated=!1,Dn(),Aa("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(()=>{dt.active=!1,dt.manuallyDeactivated=!0,Dn(),er("user"),zr()}),!0):!1:Pr?(dt.manuallyDeactivated=!0,Dn(),io("user"),!0):!1},injectMessage(c){return!N&&O()&&qt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!N&&O()&&qt(!0,"system");let m=$.injectAssistantMessage(c);return Z&&(Z=!1,Ae&&(clearTimeout(Ae),Ae=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!N&&O()&&qt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!N&&O()&&qt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!N&&O()&&qt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!N&&O()&&qt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!N&&O()&&qt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,m){return $.connectStream(c,m)},__pushEventStreamEvent(c){K&&(G==null||G.processEvent(c.type,c.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ne||!K||Or()},hideEventStream(){X&&dr()},isEventStreamVisible(){return X},showArtifacts(){lr(r)&&(kn=!1,Bn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){lr(r)&&(kn=!0,Bn())},upsertArtifact(c){return lr(r)?(kn=!1,$.upsertArtifact(c)):null},selectArtifact(c){lr(r)&&$.selectArtifact(c)},clearArtifacts(){lr(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 M&&!N&&!W()||!Ee?!1:(Ee.focus(),!0)},async resolveApproval(c,m,h){let A=$.getMessages().find(B=>{var z;return B.variant==="approval"&&((z=B.approval)==null?void 0:z.id)===c});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${c}`);if(A.approval.toolType==="webmcp"){$.resolveWebMcpApproval(A.id,m);return}return $.resolveApproval(A.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 dt.active},toggleReadAloud(c){$.toggleReadAloud(c)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(c){return $.getReadAloudState(c)},onReadAloudChange(c){return $.onReadAloudChange(c)},getState(){return{open:O()&&N,launcherEnabled:M,voiceActive:dt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!N&&O()&&qt(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=Bl({onSubmit:async(b,A)=>{var B;$.isClientTokenMode()&&await $.submitCSATFeedback(b,A),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,A)},onDismiss:c==null?void 0:c.onDismiss,...c});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!N&&O()&&qt(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=Dl({onSubmit:async(b,A)=>{var B;$.isClientTokenMode()&&await $.submitNPSFeedback(b,A),(B=c==null?void 0:c.onSubmit)==null||B.call(c,b,A)},onDismiss:c==null?void 0:c.onDismiss,...c});Ze.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(){Io!=null&&(clearInterval(Io),Io=null),ut.forEach(c=>c()),_e.remove(),Ve==null||Ve.remove(),tn==null||tn.destroy(),ln==null||ln.remove(),Sr&&V.removeEventListener("click",Sr)}};if((((ud=n==null?void 0:n.debugTools)!=null?ud:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:rn,getMessages:rn.getMessages,getStatus:rn.getStatus,getMetadata:rn.getPersistentMetadata,updateMetadata:rn.updatePersistentMetadata,clearHistory:()=>rn.clearChat(),setVoiceActive:h=>h?rn.startVoiceRecognition():rn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ut.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)&&rn.focusInput()};if(window.addEventListener("persona:focusInput",m),ut.push(()=>{window.removeEventListener("persona:focusInput",m)}),ne){let _=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===c)&&rn.showEventStream()},D=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===c)&&rn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),ut.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&rn.showArtifacts()},b=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&rn.hideArtifacts()},A=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||D!=null&&D.artifact&&rn.upsertArtifact(D.artifact)},B=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||typeof(D==null?void 0:D.id)=="string"&&rn.selectArtifact(D.id)},z=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&rn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",z),ut.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",z)})}let nr=Qv(r.persistState);if(nr&&O()){let c=Xv(nr.storage),m=`${nr.keyPrefix}widget-open`,h=`${nr.keyPrefix}widget-voice`,b=`${nr.keyPrefix}widget-voice-mode`;if(c){let A=((md=nr.persist)==null?void 0:md.openState)&&c.getItem(m)==="true",B=((gd=nr.persist)==null?void 0:gd.voiceState)&&c.getItem(h)==="true",z=((fd=nr.persist)==null?void 0:fd.voiceState)&&c.getItem(b)==="true";if(A&&setTimeout(()=>{rn.open(),setTimeout(()=>{var _;if(B||z)rn.startVoiceRecognition();else if((_=nr.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(hd=nr.persist)!=null&&hd.openState&&(i.on("widget:opened",()=>{c.setItem(m,"true")}),i.on("widget:closed",()=>{c.setItem(m,"false")})),(yd=nr.persist)!=null&&yd.voiceState&&(i.on("voice:state",_=>{c.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{c.setItem(b,_.viaVoice?"true":"false")})),nr.clearOnChatClear){let _=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(b)},D=()=>_();window.addEventListener("persona:clear-chat",D),ut.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return f&&O()&&setTimeout(()=>{rn.open()},0),ss(),xa||Cu().then(()=>{$&&(Zo++,Tr.clear(),Is(Ze,$.getMessages(),ee))}).catch(()=>{}),rn};var Yv=(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},Zv=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},ew=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},tw=(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.")},Pg=(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"},jl=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=""},Ig=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",jl(e)},Fl=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=""},$l=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},wi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},nw=(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))},rw=(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)},Rg=(e,t,n,r,o,s,a)=>{var v,x,T,S,k,M;let i=ir(s),d=i.reveal==="push";nw(e,t,n,r,d),rw(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=(S=(T=s==null?void 0:s.launcher)==null?void 0:T.mobileBreakpoint)!=null?S:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),_l(t),Fl(r),Ig(r),$l(n),wi(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((M=(k=s==null?void 0:s.launcher)==null?void 0:k.zIndex)!=null?M:Sn),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"),Ig(r),Zv(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),Fl(r),$l(n),wi(o,r);let E=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":L;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=E,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Fl(r),jl(r),wi(o,r);let E=Yv(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",R=i.side==="right"?a?-E:0:a?0:-E;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=`${L+E}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=`${L}px`,n.style.maxWidth=`${L}px`,n.style.minWidth=`${L}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),jl(r),$l(n),wi(o,r);let E=i.reveal==="emerge";E?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=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 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",ew(r,i.maxHeight),r.style.overflow=E||R?"hidden":"visible",r.style.transition=C,E&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},ow=(e,t)=>{let n=e.ownerDocument.createElement("div");return Pg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Pg(n,r)},destroy(){n.remove()}}},sw=(e,t)=>{var M,E,L,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=(E=(M=t==null?void 0:t.launcher)==null?void 0:M.enabled)==null||E?(C=(L=t==null?void 0:t.launcher)==null?void 0:L.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 f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),ir(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Rg(a,i,d,l,p,t,u)}),f.observe(a))},x=!1,T=()=>{Rg(a,i,d,l,p,t,u),v(),u&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,tw(a,ir(t)))},S=a.ownerDocument.defaultView,k=()=>{T()};return S==null||S.addEventListener("resize",k),ir(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),T(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let F=R.launcherEnabled?R.open:!0;u!==F&&(u=F,T())},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),T()},destroy(){S==null||S.removeEventListener("resize",k),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Ci=(e,t)=>pn(t)?sw(e,t):ow(e,t);var Ul={},aw=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},iw=()=>{try{if(typeof Ul!="undefined"&&Ul.url)return new URL("../widget.css",Ul.url).href}catch{}return null},Wg=(e,t)=>{let n=iw(),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)}},Hg=e=>{var T;let t=aw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Ci(t,o),a,i=[],d=(S,k)=>{var C,R;let E=!((R=(C=k==null?void 0:k.launcher)==null?void 0:C.enabled)!=null?R:!0)||pn(k),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),E&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),n){let F=S.attachShadow({mode:"open"});F.appendChild(L),Wg(F,r)}else S.appendChild(L),Wg(S,r);return t.id&&L.setAttribute("data-persona-instance",t.id),L},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let S=d(s.host,o);a=Ol(S,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};u(),(T=e.onChatReady)==null||T.call(e);let g=S=>{f(),s.destroy(),s=Ci(t,S),o=S,u()},v={update(S){var R,F,j,W,O,N;let k={...o,...S,launcher:{...(R=o==null?void 0:o.launcher)!=null?R:{},...(F=S==null?void 0:S.launcher)!=null?F:{},dock:{...(W=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?W:{},...(N=(O=S==null?void 0:S.launcher)==null?void 0:O.dock)!=null?N:{}}}},M=pn(o),E=pn(k),L=vo(o),C=vo(k);if(M!==E||L!==C){g(k);return}o=k,s.updateConfig(o),a.update(S),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(S,k,M){if(k==="host")return s.host;if(k in S)return Reflect.get(S,k,M);let E=a[k];return typeof E=="function"?E.bind(a):E}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Fg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),lw=new Set(["button","a","input","select","textarea","details","summary"]),cw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ql=/\b(product|card|item|listing|result)\b/i,Vl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,dw=3e3,pw=100;function _g(e){let t=typeof e.className=="string"?e.className:"";if(ql.test(t)||e.id&&ql.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ql.test(r.value))return!0}return!1}function $g(e){var t;return Vl.test(((t=e.textContent)!=null?t:"").trim())}function jg(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 uw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Bg(e){let t=e.match(Vl);return t?t[0]:null}function Dg(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 mw(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 gw="commerce-card",fw="result-card";function Ng(e){return!_g(e)||!$g(e)||!jg(e)&&!uw(e)?0:5200}function Og(e){var r;return!_g(e)||$g(e)||!jg(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 Ug=[{id:gw,scoreElement(e){return Ng(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||Vl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Ng(e)===0)return null;let{title:n,href:r}=Dg(e),o=(p=(l=Bg(((d=e.textContent)!=null?d:"").trim()))!=null?l:Bg(t.text))!=null?p:"",s=mw(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:fw,scoreElement(e){return Og(e)},formatSummary(e,t){if(Og(e)===0)return null;let{title:n,href:r}=Dg(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
+ `)}}];function hw(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function yw(e){var p,u,f,g,v,x,T,S,k,M,E,L,C;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(v=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",o=(T=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?T:200,s=(k=(S=t.visibleOnly)!=null?S:e.visibleOnly)!=null?k:!0,a=(M=t.root)!=null?M:e.root,i=(E=t.mode)!=null?E:"structured",d=(L=t.maxCandidates)!=null?L:Math.max(500,n*10),l=(C=e.rules)!=null?C:Ug;return i==="simple"&&e.rules&&e.rules.length>0?(hw(),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 bw=["data-testid","data-product","data-action","data-id","data-name","data-type"];function xw(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"||lw.has(t)||n&&cw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function qg(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 vw(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 zg(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 bw){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 ww(e){return e==="static"?pw:dw}function Vg(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:zg(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:xw(e),attributes:vw(e)}}function Cw(e,t,n,r){let o=ww(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 Aw(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 Sw(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(Fg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!qg(l)){i=a.nextNode();continue}let u=Vg(l,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(T=>T==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=Cw(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,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f: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;Aw(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let g=l.formattingRule.formatSummary(l.el,l.enriched,n);g&&(p=g)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function Ew(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(Fg.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!qg(d)){s=o.nextNode();continue}let p=Vg(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){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 Tw(e={}){var r;let t=yw(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Ew(t,n):Sw(t,n):[]}var Ai=100;function Mw(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:
112
114
  ${a.map(i=>`- ${i.split(`
113
115
  `).join(`
114
116
  `)}`).join(`
115
- `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,vi)}" (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,Ai)}" (clickable)`);r.push(`Interactive elements:
116
118
  ${a.join(`
117
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,vi)}" (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,Ai)}" (navigable)`);r.push(`Navigation links:
118
120
  ${a.join(`
119
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,vi)}" (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,Ai)}" (input)`);r.push(`Form inputs:
120
122
  ${a.join(`
121
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,vi)}"`);r.push(`Content:
123
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Ai)}"`);r.push(`Content:
122
124
  ${a.join(`
123
125
  `)}`)}return r.join(`
124
126
 
125
- `)}function aw(){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 iw(){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 lw(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:Rr(e.colors.primary,.95),100:Rr(e.colors.primary,.9),200:Rr(e.colors.primary,.8),300:Rr(e.colors.primary,.7),400:Rr(e.colors.primary,.6),500:e.colors.primary,600:Rr(e.colors.primary,.8),700:Rr(e.colors.primary,.7),800:Rr(e.colors.primary,.6),900:Rr(e.colors.primary,.5),950:Rr(e.colors.primary,.45)}}),{...t,palette:n}}}}function cw(){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 Rr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function pw(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var uw={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"}}},Dg={components:{panel:{borderRadius:"0",shadow:"none"}}},Ng={id:"shop",label:"Shopping Assistant",config:{theme:uw,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?"]}},Og={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Dg}},Fg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Dg}},_g={shop:Ng,minimal:Og,fullscreen:Fg};function mw(e){return _g[e]}var gw=Sg;function Kr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function fw(e){if(e)return{getHeaders:Kr(e.getHeaders),onFeedback:Kr(e.onFeedback),onCopy:Kr(e.onCopy),requestMiddleware:Kr(e.requestMiddleware),actionHandlers:Kr(e.actionHandlers),actionParsers:Kr(e.actionParsers),postprocessMessage:Kr(e.postprocessMessage),contextProviders:Kr(e.contextProviders),streamParser:Kr(e.streamParser)}}var $g=`({ text, message }: any) => {
127
+ `)}function kw(){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 Lw(){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 Pw(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:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function Iw(){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 Rw(){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 Dr(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 Ww(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Hw={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"}}},Kg={components:{panel:{borderRadius:"0",shadow:"none"}}},Gg={id:"shop",label:"Shopping Assistant",config:{theme:Hw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:ar},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?"]}},Jg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Kg}},Qg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Kg}},Xg={shop:Gg,minimal:Jg,fullscreen:Qg};function Bw(e){return Xg[e]}var Dw=Hg;function Qr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Nw(e){if(e)return{getHeaders:Qr(e.getHeaders),onFeedback:Qr(e.onFeedback),onCopy:Qr(e.onCopy),requestMiddleware:Qr(e.requestMiddleware),actionHandlers:Qr(e.actionHandlers),actionParsers:Qr(e.actionParsers),postprocessMessage:Qr(e.postprocessMessage),contextProviders:Qr(e.contextProviders),streamParser:Qr(e.streamParser)}}var Yg=`({ text, message }: any) => {
126
128
  const jsonSource = (message as any).rawContent || text || message.content;
127
129
  if (!jsonSource || typeof jsonSource !== 'string') return null;
128
130
  let cleanJson = jsonSource
@@ -135,7 +137,7 @@ ${a.join(`
135
137
  if (parsed.action) return { type: parsed.action, payload: parsed };
136
138
  } catch (e) { return null; }
137
139
  return null;
138
- }`,jg=`function(ctx) {
140
+ }`,Zg=`function(ctx) {
139
141
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
140
142
  if (!jsonSource || typeof jsonSource !== 'string') return null;
141
143
  var cleanJson = jsonSource
@@ -148,7 +150,7 @@ ${a.join(`
148
150
  if (parsed.action) return { type: parsed.action, payload: parsed };
149
151
  } catch (e) { return null; }
150
152
  return null;
151
- }`,Ug=`(action: any, context: any) => {
153
+ }`,ef=`(action: any, context: any) => {
152
154
  if (action.type !== 'nav_then_click') return;
153
155
  const payload = action.payload || action.raw || {};
154
156
  const url = payload?.page;
@@ -165,7 +167,7 @@ ${a.join(`
165
167
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
166
168
  window.location.href = targetUrl;
167
169
  return { handled: true, displayText: text };
168
- }`,qg=`function(action, context) {
170
+ }`,tf=`function(action, context) {
169
171
  if (action.type !== 'nav_then_click') return;
170
172
  var payload = action.payload || action.raw || {};
171
173
  var url = payload.page;
@@ -182,26 +184,26 @@ ${a.join(`
182
184
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
183
185
  window.location.href = targetUrl;
184
186
  return { handled: true, displayText: text };
185
- }`,hw=`(parsed: any) => {
187
+ }`,Ow=`(parsed: any) => {
186
188
  if (!parsed || typeof parsed !== 'object') return null;
187
189
  if (parsed.action === 'nav_then_click') return 'Navigating...';
188
190
  if (parsed.action === 'message') return parsed.text || '';
189
191
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
190
192
  return parsed.text || null;
191
- }`,yw=`function(parsed) {
193
+ }`,Fw=`function(parsed) {
192
194
  if (!parsed || typeof parsed !== 'object') return null;
193
195
  if (parsed.action === 'nav_then_click') return 'Navigating...';
194
196
  if (parsed.action === 'message') return parsed.text || '';
195
197
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
196
198
  return parsed.text || null;
197
- }`;function bw(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 wi(e){var t,n;return(n=(t=e.parserType)!=null?t:bw(e.streamParser))!=null?n:"plain"}function Ci(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function Si(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(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 Ai(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Ti(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="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} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function ql(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 zg(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),zg(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function xo(e,t,n,r){n&&(e.push(`${r}${t}: {`),zg(e,n,`${r} `),e.push(`${r}},`))}function ma(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function xw(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:fw(n.hooks)}:void 0;return t==="esm"?vw(r,s):t==="script-installer"?Sw(r,s):t==="script-advanced"?Tw(r,s):t==="react-component"?ww(r,s):t==="react-advanced"?Cw(r,s):Aw(r,s)}function vw(e,t){let n=t==null?void 0:t.hooks,r=wi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ma(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&xo(o,"theme",e.theme," "),e.launcher&&xo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ci(e," ")),o.push(...Si(e," ",n)),o.push(...Ai(e," ")),o.push(...Ti(e," ")),o.push(...ql(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
198
- `)}function ww(e,t){let n=t==null?void 0:t.hooks,r=wi(e),s=r!=="plain",o=["// 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: '${ma(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&xo(o,"theme",e.theme," "),e.launcher&&xo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ci(e," ")),o.push(...Si(e," ",n)),o.push(...Ai(e," ")),o.push(...Ti(e," ")),o.push(...ql(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
199
- `)}function Cw(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: '${ma(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&xo(r,"theme",e.theme," "),e.launcher&&xo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),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(...Ci(e," ")),r.push(...Si(e," ",n)),r.push(...Ai(e," ")),r.push(...Ti(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(${hw}),`)),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(` ${$g}`),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(` ${$g}`),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(` ${Ug}`),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(` ${Ug}`),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(`
200
- `)}function Vg(e){var s;let t=wi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),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),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};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&&(o.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 c={};Object.entries(d).forEach(([p,m])=>{p!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(c[p]=m)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function Sw(e,t){let n=Vg(e),s=!!(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,o=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/install.global.js" data-config='${o}'></script>`}function Aw(e,t){let n=t==null?void 0:t.hooks,r=wi(e),s=r!=="plain",o=["<!-- 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: '${ma(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&xo(o,"theme",e.theme," "),e.launcher&&xo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ci(e," ")),o.push(...Si(e," ",n)),o.push(...Ai(e," ")),o.push(...Ti(e," ")),o.push(...ql(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
201
- `)}function Tw(e,t){let n=t==null?void 0:t.hooks,r=Vg(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
199
+ }`;function _w(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 Si(e){var t,n;return(n=(t=e.parserType)!=null?t:_w(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 Ti(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 Mi(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 ki(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 Kl(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 nf(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}: {`),nf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function Ao(e,t,n,r){n&&(e.push(`${r}${t}: {`),nf(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 $w(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:Nw(n.hooks)}:void 0;return t==="esm"?jw(r,o):t==="script-installer"?zw(r,o):t==="script-advanced"?Kw(r,o):t==="react-component"?Uw(r,o):t==="react-advanced"?qw(r,o):Vw(r,o)}function jw(e,t){let n=t==null?void 0:t.hooks,r=Si(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.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ao(s,"theme",e.theme," "),e.launcher&&Ao(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(...Ti(e," ",n)),s.push(...Mi(e," ")),s.push(...ki(e," ")),s.push(...Kl(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 Uw(e,t){let n=t==null?void 0:t.hooks,r=Si(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.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ao(s,"theme",e.theme," "),e.launcher&&Ao(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(...Ti(e," ",n)),s.push(...Mi(e," ")),s.push(...ki(e," ")),s.push(...Kl(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 qw(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.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ao(r,"theme",e.theme," "),e.launcher&&Ao(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(...Ti(e," ",n)),r.push(...Mi(e," ")),r.push(...ki(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(${Ow}),`)),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(` ${Yg}`),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(` ${Yg}`),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(` ${ef}`),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(` ${ef}`),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 rf(e){var o;let t=Si(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),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 zw(e,t){let n=rf(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 Vw(e,t){let n=t==null?void 0:t.hooks,r=Si(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: '${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.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ao(s,"theme",e.theme," "),e.launcher&&Ao(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(...Ti(e," ",n)),s.push(...Mi(e," ")),s.push(...ki(e," ")),s.push(...Kl(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 Kw(e,t){let n=t==null?void 0:t.hooks,r=rf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
202
204
  `).map((a,i)=>i===0?a:" "+a).join(`
203
- `)};`,""," // 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&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${yw});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${jg}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${jg}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${qg}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${qg}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.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: '${ma(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>"),o.join(`
204
- `)}var Kg={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Gg=.1,Jg=.15,Qg=1.5,zl=24,Xg=40,Ew=`
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(${Fw});`),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(` ${Zg}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Zg}`),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(` ${tf}`),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(` ${tf}`),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 of={desktop:{w:1280,h:800},mobile:{w:390,h:844}},sf=.1,af=.15,lf=1.5,Gl=24,cf=40,Gw=`
205
207
  /* \u2500\u2500 Root \u2500\u2500 */
206
208
  .persona-dc-root {
207
209
  display: flex;
@@ -352,7 +354,7 @@ ${a.join(`
352
354
  .persona-dc-stage {
353
355
  height: 550px;
354
356
  min-height: 400px;
355
- padding: ${zl}px;
357
+ padding: ${Gl}px;
356
358
  overflow: auto;
357
359
  background: #f0f1f3;
358
360
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -442,5 +444,5 @@ ${a.join(`
442
444
  min-height: 300px;
443
445
  }
444
446
  }
445
- `;function Mw(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Ew,document.head.appendChild(e)}function kw(e,t){let n=e.clientWidth-zl*2-Xg,r=e.clientHeight-zl*2-Xg;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Lw(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="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 Pw(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Mw();let p=Math.max(0,Math.min(r,n.length-1)),m=s,f=o,g=null,x=1,v=!1,E=y("div","persona-dc-root"),C=y("div","persona-dc-toolbar"),I=y("div","persona-dc-toolbar-lead"),N=y("div","persona-dc-toolbar-trail"),M=qt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>ee(-1)}),P=y("div");P.style.position="relative";let S=y("button","persona-dc-title-btn");S.type="button",S.setAttribute("aria-expanded","false"),S.setAttribute("aria-haspopup","listbox");let W=y("span","persona-dc-title-text"),B=y("span","persona-dc-title-chevron"),D=xe("chevron-down",12,"currentColor",2);D&&B.appendChild(D),S.append(W,B);let k=y("div","persona-dc-dropdown");k.setAttribute("role","listbox"),k.style.display="none";let j=!1;function z(){k.innerHTML="";for(let ve=0;ve<n.length;ve++){let Xe=n[ve],Ke=y("button","persona-dc-dropdown-item");Ke.type="button",Ke.setAttribute("role","option"),Ke.setAttribute("aria-current",ve===p?"true":"false");let Ne=y("span");if(Ne.textContent=Xe.title,Ke.appendChild(Ne),Xe.description){let ce=y("span","persona-dc-dropdown-desc");ce.textContent=Xe.description,Ke.appendChild(ce)}Ke.addEventListener("click",()=>{Pe(),qe(ve)}),k.appendChild(Ke)}}function te(){j=!j,k.style.display=j?"":"none",S.setAttribute("aria-expanded",j?"true":"false"),j&&z()}function Pe(){j&&(j=!1,k.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",ve=>{ve.stopPropagation(),te()});let je=()=>Pe();document.addEventListener("click",je),P.append(S,k);let Se=qt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ee(1)}),ke=y("span","persona-dc-counter");I.append(M,P,Se,ke);let Fe=null;i&&(Fe=ni({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:ve=>{m=ve,ne.dataset.device=m,g=null,J()}}),N.appendChild(Fe.element));let he=null;if(a){let ve=y("div","persona-dc-zoom-controls"),Xe=qt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ce=g!=null?g:x;g=Math.max(Jg,ce-Gg),J()}});he=y("span","persona-dc-zoom-level"),he.title="Reset to 100%",he.style.cursor="pointer",he.addEventListener("click",()=>{g=1,J()});let Ke=qt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ce=g!=null?g:x;g=Math.min(Qg,ce+Gg),J()}}),Ne=qt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,J()}});ve.append(Xe,he,Ke,Ne),N.appendChild(ve)}if(d){let ve=y("div","persona-dc-separator");N.appendChild(ve);let Xe=ni({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:Ke=>{f=Ke,ne.dataset.colorScheme=f,re()}});N.appendChild(Xe.element)}let Be=y("div","persona-dc-separator");N.appendChild(Be);let ae=qt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});N.appendChild(ae),C.append(I,N);let Q=y("div","persona-dc-stage"),ne=y("div","persona-dc-iframe-wrapper");ne.dataset.device=m,ne.dataset.colorScheme=f;let le=y("iframe","persona-dc-iframe");le.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),le.setAttribute("loading","lazy"),le.title=n[p].title,ne.appendChild(le),Q.appendChild(ne),E.append(C,Q),e.appendChild(E);function re(){var ve;try{let Xe=(ve=le.contentDocument)==null?void 0:ve.body;if(!Xe)return;f==="dark"?Xe.classList.add("theme-dark"):Xe.classList.remove("theme-dark")}catch{}}le.addEventListener("load",()=>re());function G(){let ve=n[p];W.textContent=ve.title,ke.textContent=`${p+1} / ${n.length}`,le.title=ve.title}function ee(ve){let Xe=((p+ve)%n.length+n.length)%n.length;qe(Xe)}function qe(ve){ve<0||ve>=n.length||(p=ve,le.src=n[p].url,G(),c==null||c(p,n[p]))}function J(){var Ke;if(v)return;let ve=(Ke=Kg[m])!=null?Ke:Kg.desktop;x=kw(Q,ve);let Xe=Math.max(Jg,Math.min(Qg,g!=null?g:x));Lw(ne,le,ve,Xe,m),he&&(he.textContent=`${Math.round(Xe*100)}%`)}let ie=new ResizeObserver(()=>J());ie.observe(Q),G(),le.src=n[p].url,requestAnimationFrame(()=>J());function Re(){v||(v=!0,ie.disconnect(),document.removeEventListener("click",je),E.remove())}return{element:E,goTo:qe,next:()=>ee(1),prev:()=>ee(-1),getIndex:()=>p,setDevice(ve){m=ve,ne.dataset.device=ve,Fe==null||Fe.setSelected(ve),g=null,J()},setColorScheme(ve){f=ve,ne.dataset.colorScheme=ve},setZoom(ve){g=ve,J()},destroy:Re}}export{zu as ASK_USER_QUESTION_CLIENT_TOOL,qu as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Ea as ASK_USER_QUESTION_TOOL_NAME,ps as AgentWidgetClient,Qs as AgentWidgetSession,fs as AttachmentManager,$o as BrowserSpeechEngine,ym as DEFAULT_COMPONENTS,nl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,fm as DEFAULT_PALETTE,hm as DEFAULT_SEMANTIC,Ot as DEFAULT_WIDGET_CONFIG,_g as PRESETS,Fg as PRESET_FULLSCREEN,Og as PRESET_MINIMAL,Ng as PRESET_SHOP,gs as ReadAloudController,Ui as SUGGEST_REPLIES_CLIENT_TOOL,$u as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Ir as SUGGEST_REPLIES_TOOL_NAME,Gb as THEME_ZONES,fr as VERSION,lo as WEBMCP_TOOL_PREFIX,Os as WebMcpBridge,aw as accessibilityPlugin,iw as animationsPlugin,jo as applyThemeVariables,ys as attachHeaderToContainer,lw as brandPlugin,la as buildComposer,Bm as buildDefaultHeader,yo as buildHeader,ia as buildHeaderWithLayout,Dm as buildMinimalHeader,Ia as builtInClientToolsForDispatch,ow as collectEnrichedPageContext,bo as componentRegistry,hi as createActionManager,Bl as createAgentExperience,ah as createAskUserQuestionBubble,Zi as createBestAvailableVoiceProvider,Px as createBubbleWithLayout,Rl as createCSATFeedback,ul as createComboButton,Sv as createComponentMiddleware,kl as createComponentStreamParser,Au as createDefaultSanitizer,Pw as createDemoCarousel,Sf as createDirectivePostprocessor,qo as createDropdownMenu,dh as createFlexibleJsonStreamParser,qt as createIconButton,wh as createImagePart,Ji as createJsonStreamParser,ti as createLabelButton,Ml as createLocalStorageAdapter,Aa as createMarkdownProcessor,is as createMarkdownProcessorFromConfig,Vm as createMessageActions,Wl as createNPSFeedback,Ki as createPlainTextParser,pw as createPlugin,Gi as createRegexJsonParser,ca as createStandardBubble,Oa as createTextPart,Ys as createTheme,al as createThemeObserver,ni as createToggleGroup,bs as createTypingIndicator,_o as createVoiceProvider,xi as createWidgetHostLayout,Qi as createXmlParser,gw as default,Cs as defaultActionHandlers,fi as defaultJsonActionParser,Rg as defaultParseRules,qa as detectColorScheme,Af as directivePostprocessor,js as ensureAskUserQuestionSheet,qr as escapeHtml,Il as extractComponentDirectiveFromMessage,Ch as fileToImagePart,sw as formatEnrichedContext,us as generateAssistantMessageId,xw as generateCodeSnippet,hh as generateMessageId,Hg as generateStableSelector,Vs as generateUserMessageId,Zs as getActiveTheme,wm as getColorScheme,bh as getDisplayText,Nm as getHeaderLayout,vh as getImageParts,mw as getPreset,Pl as hasComponentDirective,xh as hasImages,ml as headerLayouts,dw as highContrastPlugin,Sg as initAgentWidget,co as isAskUserQuestionMessage,Cv as isComponentDirectiveType,dn as isDockedMountMode,Pa as isSuggestRepliesMessage,_a as isVoiceSupported,Do as isWebMcpToolName,zi as latestAgentSuggestions,ox as listRegisteredStreamAnimations,wu as markdownPostprocessor,rl as mergeWithDefaults,yh as normalizeContent,po as parseAskUserQuestionPayload,ju as parseSuggestRepliesPayload,Gs as pickBestVoice,gi as pluginRegistry,cw as reducedMotionPlugin,nx as registerStreamAnimationPlugin,Oo as removeAskUserQuestionSheet,Ll as renderComponentDirective,zm as renderLoadingIndicatorWithFallback,xe as renderLucideIcon,ar as resolveDockConfig,Ns as resolveSanitizer,ol as resolveTokens,Ni as stripWebMcpPrefix,sl as themeToCssVariables,rx as unregisterStreamAnimationPlugin,Sh as validateImageFile,bm as validateTheme};
447
+ `;function Jw(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Gw,document.head.appendChild(e)}function Qw(e,t){let n=e.clientWidth-Gl*2-cf,r=e.clientHeight-Gl*2-cf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function Xw(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 Yw(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");Jw();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,g=null,v=1,x=!1,T=y("div","persona-dc-root"),S=y("div","persona-dc-toolbar"),k=y("div","persona-dc-toolbar-lead"),M=y("div","persona-dc-toolbar-trail"),E=Jt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>G(-1)}),L=y("div");L.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 Ge=n[ge],nt=y("button","persona-dc-dropdown-item");nt.type="button",nt.setAttribute("role","option"),nt.setAttribute("aria-current",ge===p?"true":"false");let Pt=y("span");if(Pt.textContent=Ge.title,nt.appendChild(Pt),Ge.description){let Ye=y("span","persona-dc-dropdown-desc");Ye.textContent=Ge.description,nt.appendChild(Ye)}nt.addEventListener("click",()=>{Ae(),ve(ge)}),W.appendChild(nt)}}function Z(){O=!O,W.style.display=O?"":"none",C.setAttribute("aria-expanded",O?"true":"false"),O&&N()}function Ae(){O&&(O=!1,W.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",ge=>{ge.stopPropagation(),Z()});let de=()=>Ae();document.addEventListener("click",de),L.append(C,W);let ee=Jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>G(1)}),xe=y("span","persona-dc-counter");k.append(E,L,ee,xe);let Te=null;i&&(Te=si({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ge=>{u=ge,re.dataset.device=u,g=null,X()}}),M.appendChild(Te.element));let ne=null;if(a){let ge=y("div","persona-dc-zoom-controls"),Ge=Jt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ye=g!=null?g:v;g=Math.max(af,Ye-sf),X()}});ne=y("span","persona-dc-zoom-level"),ne.title="Reset to 100%",ne.style.cursor="pointer",ne.addEventListener("click",()=>{g=1,X()});let nt=Jt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ye=g!=null?g:v;g=Math.min(lf,Ye+sf),X()}}),Pt=Jt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,X()}});ge.append(Ge,ne,nt,Pt),M.appendChild(ge)}if(d){let ge=y("div","persona-dc-separator");M.appendChild(ge);let Ge=si({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:nt=>{f=nt,re.dataset.colorScheme=f,Oe()}});M.appendChild(Ge.element)}let be=y("div","persona-dc-separator");M.appendChild(be);let le=Jt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});M.appendChild(le),S.append(k,M);let oe=y("div","persona-dc-stage"),re=y("div","persona-dc-iframe-wrapper");re.dataset.device=u,re.dataset.colorScheme=f;let We=y("iframe","persona-dc-iframe");We.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),We.setAttribute("loading","lazy"),We.title=n[p].title,re.appendChild(We),oe.appendChild(re),T.append(S,oe),e.appendChild(T);function Oe(){var ge;try{let Ge=(ge=We.contentDocument)==null?void 0:ge.body;if(!Ge)return;f==="dark"?Ge.classList.add("theme-dark"):Ge.classList.remove("theme-dark")}catch{}}We.addEventListener("load",()=>Oe());function K(){let ge=n[p];R.textContent=ge.title,xe.textContent=`${p+1} / ${n.length}`,We.title=ge.title}function G(ge){let Ge=((p+ge)%n.length+n.length)%n.length;ve(Ge)}function ve(ge){ge<0||ge>=n.length||(p=ge,We.src=n[p].url,K(),l==null||l(p,n[p]))}function X(){var nt;if(x)return;let ge=(nt=of[u])!=null?nt:of.desktop;v=Qw(oe,ge);let Ge=Math.max(af,Math.min(lf,g!=null?g:v));Xw(re,We,ge,Ge,u),ne&&(ne.textContent=`${Math.round(Ge*100)}%`)}let ie=new ResizeObserver(()=>X());ie.observe(oe),K(),We.src=n[p].url,requestAnimationFrame(()=>X());function Re(){x||(x=!0,ie.disconnect(),document.removeEventListener("click",de),T.remove())}return{element:T,goTo:ve,next:()=>G(1),prev:()=>G(-1),getIndex:()=>p,setDevice(ge){u=ge,re.dataset.device=ge,Te==null||Te.setSelected(ge),g=null,X()},setColorScheme(ge){f=ge,re.dataset.colorScheme=ge},setZoom(ge){g=ge,X()},destroy:Re}}export{Yu as ASK_USER_QUESTION_CLIENT_TOOL,Xu as ASK_USER_QUESTION_PARAMETERS_SCHEMA,La as ASK_USER_QUESTION_TOOL_NAME,hs as AgentWidgetClient,ta as AgentWidgetSession,vs as AttachmentManager,qo as BrowserSpeechEngine,Sm as DEFAULT_COMPONENTS,ol as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,ar as DEFAULT_FLOATING_LAUNCHER_WIDTH,Cm as DEFAULT_PALETTE,Am as DEFAULT_SEMANTIC,_t as DEFAULT_WIDGET_CONFIG,Xg as PRESETS,Qg as PRESET_FULLSCREEN,Jg as PRESET_MINIMAL,Gg as PRESET_SHOP,xs as ReadAloudController,zi as SUGGEST_REPLIES_CLIENT_TOOL,Gu as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Br as SUGGEST_REPLIES_TOOL_NAME,dx as THEME_ZONES,yr as VERSION,Wr as WEBMCP_TOOL_PREFIX,js as WebMcpBridge,kw as accessibilityPlugin,Lw as animationsPlugin,zo as applyThemeVariables,Cs as attachHeaderToContainer,Pw as brandPlugin,ma as buildComposer,jm as buildDefaultHeader,wo as buildHeader,ua as buildHeaderWithLayout,Um as buildMinimalHeader,Ha as builtInClientToolsForDispatch,Tw as collectEnrichedPageContext,Co as componentRegistry,xi as createActionManager,Ol as createAgentExperience,Ch as createAskUserQuestionBubble,tl as createBestAvailableVoiceProvider,Vx as createBubbleWithLayout,Bl as createCSATFeedback,gl as createComboButton,zv as createComponentMiddleware,Il as createComponentStreamParser,Mu as createDefaultSanitizer,Yw as createDemoCarousel,Df as createDirectivePostprocessor,Ko as createDropdownMenu,Th as createFlexibleJsonStreamParser,Jt as createIconButton,Nh as createImagePart,Xi as createJsonStreamParser,oi as createLabelButton,Pl as createLocalStorageAdapter,Ma as createMarkdownProcessor,ms as createMarkdownProcessorFromConfig,Zm as createMessageActions,Dl as createNPSFeedback,Ji as createPlainTextParser,Ww as createPlugin,Qi as createRegexJsonParser,ga as createStandardBubble,$a as createTextPart,ra as createTheme,ll as createThemeObserver,si as createToggleGroup,As as createTypingIndicator,Uo as createVoiceProvider,Ci as createWidgetHostLayout,Yi as createXmlParser,Dw as default,Ms as defaultActionHandlers,bi as defaultJsonActionParser,Ug as defaultParseRules,Ka as detectColorScheme,Nf as directivePostprocessor,Ks as ensureAskUserQuestionSheet,Kr as escapeHtml,Hl as extractComponentDirectiveFromMessage,Oh as fileToImagePart,Mw as formatEnrichedContext,ys as generateAssistantMessageId,$w as generateCodeSnippet,Rh as generateMessageId,zg as generateStableSelector,Xs as generateUserMessageId,oa as getActiveTheme,km as getColorScheme,Hh as getDisplayText,qm as getHeaderLayout,Dh as getImageParts,Bw as getPreset,Wl as hasComponentDirective,Bh as hasImages,fl as headerLayouts,Rw as highContrastPlugin,Hg as initAgentWidget,mo as isAskUserQuestionMessage,qv as isComponentDirectiveType,pn as isDockedMountMode,Wa as isSuggestRepliesMessage,Ua as isVoiceSupported,Fo as isWebMcpToolName,Ki as latestAgentSuggestions,vx as listRegisteredStreamAnimations,Su as markdownPostprocessor,sl as mergeWithDefaults,Wh as normalizeContent,go as parseAskUserQuestionPayload,Ju as parseSuggestRepliesPayload,Zs as pickBestVoice,yi as pluginRegistry,Iw as reducedMotionPlugin,bx as registerStreamAnimationPlugin,$o as removeAskUserQuestionSheet,Rl as renderComponentDirective,Ym as renderLoadingIndicatorWithFallback,me as renderLucideIcon,ir as resolveDockConfig,$s as resolveSanitizer,al as resolveTokens,Fi as stripWebMcpPrefix,il as themeToCssVariables,xx as unregisterStreamAnimationPlugin,Fh as validateImageFile,Em as validateTheme};
446
448
  //# sourceMappingURL=index.js.map