@runtypelabs/persona 3.36.0 → 3.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,20 @@
1
- "use strict";var hg=Object.create;var Fa=Object.defineProperty;var yg=Object.getOwnPropertyDescriptor;var bg=Object.getOwnPropertyNames;var vg=Object.getPrototypeOf,xg=Object.prototype.hasOwnProperty;var js=(n,e)=>()=>(n&&(e=n(n=0)),e);var Bi=(n,e)=>{for(var t in e)Fa(n,t,{get:e[t],enumerable:!0})},Vp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of bg(e))!xg.call(n,o)&&o!==t&&Fa(n,o,{get:()=>e[o],enumerable:!(r=yg(e,o))||r.enumerable});return n};var Kp=(n,e,t)=>(t=n!=null?hg(vg(n)):{},Vp(e||!n||!n.__esModule?Fa(t,"default",{value:n,enumerable:!0}):t,n)),wg=n=>Vp(Fa({},"__esModule",{value:!0}),n);var Xp={};Bi(Xp,{DOMPurify:()=>Qp.default,Marked:()=>Gp.Marked});var Gp,Qp,Jp=js(()=>{"use strict";Gp=require("marked"),Qp=Kp(require("dompurify"),1)});var hs,Yi=js(()=>{"use strict";hs=class{constructor(e=24e3,t={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=e;let r=Math.max(0,(o=t.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),t=o,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.pcmToFloat32(t);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let t of e)this.scheduleSamples(t)}scheduleSamples(e){if(e.length===0)return;let t=this.ensureContext(),r=t.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=t.createBufferSource();o.buffer=r,o.connect(t.destination);let s=t.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),r=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Sf(n){return n.replace(/\/+$/,"")}async function Tf(n){var e,t;try{let r=await n.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${n.status}`}: ${r.detail}`:(t=r.error)!=null?t:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var ti,Bu=js(()=>{"use strict";Yi();ti=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,t;return(t=this.playerPromise)!=null?t:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new hs(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,t){let r=++this.generation;this.run(r,e,t)}async run(e,t,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var u;e===this.generation&&((u=r.onStart)==null||u.call(r))}),d.onFinished(()=>{var u;e===this.generation&&((u=r.onEnd)==null||u.call(r))});let c=`${Sf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,g=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!g.ok||!g.body)throw new Error(await Tf(g));let f=g.body.getReader();for(;;){let{done:u,value:m}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(u)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var ni,Du=js(()=>{"use strict";ni=class{constructor(e,t,r={}){this.primary=e;this.fallback=t;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,t){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=t.onStart)==null||o.call(t)},onEnd:()=>{var o;return(o=t.onEnd)==null?void 0:o.call(t)},onError:o=>{var s,a,i;if(r){(s=t.onError)==null||s.call(t,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,t)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,t,r,o;(t=(e=this.primary).destroy)==null||t.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Nu={};Bi(Nu,{FallbackSpeechEngine:()=>ni,RuntypeSpeechEngine:()=>ti});var Fu=js(()=>{"use strict";Bu();Du()});var Wy={};Bi(Wy,{createThemePreview:()=>cg});module.exports=wg(Wy);var Yp=null,Vs=null,ls=null;var Zp=()=>Vs?Promise.resolve(Vs):ls||(Yp?(ls=Yp().then(n=>(Vs=n,n)),ls):(ls=Promise.resolve().then(()=>(Jp(),Xp)).then(n=>(Vs=n,n)),ls)),cs=()=>Vs;var Cg=n=>{if(n)return n},Di=n=>{let e=null;return t=>{var o,s;let r=cs();if(!r)return ho(t);if(!e){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;e=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Cg(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},Oa=n=>n?Di({markedOptions:n.options,renderer:n.renderer}):Di(),Fy=Di();var ho=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Ag={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Sg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Tg=()=>{let n=null;return e=>{let t=cs();if(!t)return ho(e);if(!n){let{DOMPurify:r}=t;n=r(typeof window!="undefined"?window:void 0),n.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Sg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,Ag)}},_a=n=>n===!1?null:typeof n=="function"?n:Tg();var No="webmcp:",Ni=new Map,eu=n=>{var e;Ni.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&Ni.set(t.name,r)}},Fi=n=>Ni.get(ou(n)),$a={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},tu=null;function ru(n){if(n.length===0)return"0:empty";let e=n.map(t=>{var r,o;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(o=t.origin)!=null?o:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${n.length}:${Mg(e.join(""))}`}function nu(n,e){let t=3735928559^e,r=1103547991^e;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);t=Math.imul(t^s,2654435761),r=Math.imul(r^s,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Mg(n){let e=nu(n,0).toString(36),t=nu(n,2654435761).toString(36);return`${e}.${t}`}var qa=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let t;try{t=await e.getTools()}catch(o){return $a.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}eu(t);let r=typeof location!="undefined"?location.origin:"";return t.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=kg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return vr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return vr(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=ou(e),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return vr(`Failed to read WebMCP registry: ${x}`)}eu(a);let i=a.find(v=>v.name===s);if(!i)return vr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return vr("Aborted by cancel()");let d=Fi(s),c={toolName:s,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return vr("User declined the tool call.");if(r!=null&&r.aborted)return vr("Aborted by cancel()");let g=new AbortController,f=!1,u=setTimeout(()=>{f=!0,g.abort()},this.timeoutMs),m=()=>g.abort();r&&(r.aborted?g.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,Wg(t),{signal:g.signal});return Lg(v)}catch(v){if(f)return vr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return vr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return vr(x)}finally{clearTimeout(u),r&&r.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(tu?await tu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){$a.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,$a.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var r;let t=(r=this.confirmHandler)!=null?r:Pg;try{return await t(e)}catch(o){return $a.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Eg(e,r))}},ou=n=>n.startsWith(No)?n.slice(No.length):n,Ks=n=>n.startsWith(No),Eg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},kg=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Lg=n=>{if(n==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Rg(e)}]}},vr=n=>({isError:!0,content:[{type:"text",text:n}]}),Pg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Ig(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
1
+ "use strict";var vg=Object.create;var _a=Object.defineProperty;var xg=Object.getOwnPropertyDescriptor;var wg=Object.getOwnPropertyNames;var Cg=Object.getPrototypeOf,Ag=Object.prototype.hasOwnProperty;var zs=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ni=(n,t)=>{for(var e in t)_a(n,e,{get:t[e],enumerable:!0})},Kp=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wg(t))!Ag.call(n,o)&&o!==e&&_a(n,o,{get:()=>t[o],enumerable:!(r=xg(t,o))||r.enumerable});return n};var Gp=(n,t,e)=>(e=n!=null?vg(Cg(n)):{},Kp(t||!n||!n.__esModule?_a(e,"default",{value:n,enumerable:!0}):e,n)),Sg=n=>Kp(_a({},"__esModule",{value:!0}),n);var Jp={};Ni(Jp,{DOMPurify:()=>Xp.default,Marked:()=>Qp.Marked});var Qp,Xp,Yp=zs(()=>{"use strict";Qp=require("marked"),Xp=Gp(require("dompurify"),1)});var fs,el=zs(()=>{"use strict";fs=class{constructor(t=24e3,e={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=e.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let e=typeof window!="undefined"?window:void 0;if(!e)throw new Error("AudioPlaybackManager requires a browser environment");let r=e.AudioContext||e.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let e=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),e=o,this.remainder=null}if(e.length%2!==0&&(this.remainder=new Uint8Array([e[e.length-1]]),e=e.subarray(0,e.length-1)),e.length===0)return;let r=this.pcmToFloat32(e);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let e of t)this.scheduleSamples(e)}scheduleSamples(t){if(t.length===0)return;let e=this.ensureContext(),r=e.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=e.createBufferSource();o.buffer=r,o.connect(e.destination);let s=e.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let e of t)e()}}pcmToFloat32(t){let e=Math.floor(t.length/2),r=new Float32Array(e),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<e;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Mf(n){return n.replace(/\/+$/,"")}async function kf(n){var t,e;try{let r=await n.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${n.status}`}: ${r.detail}`:(e=r.error)!=null?e:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var ri,Fu=zs(()=>{"use strict";el();ri=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,e;return(e=this.playerPromise)!=null?e:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new fs(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,e){let r=++this.generation;this.run(r,t,e)}async run(t,e,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var u;t===this.generation&&((u=r.onStart)==null||u.call(r))}),d.onFinished(()=>{var u;t===this.generation&&((u=r.onEnd)==null||u.call(r))});let c=`${Mf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,g=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:e.text,voice:(o=e.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!g.ok||!g.body)throw new Error(await kf(g));let f=g.body.getReader();for(;;){let{done:u,value:m}=await f.read();if(t!==this.generation){await f.cancel().catch(()=>{});return}if(u)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var oi,_u=zs(()=>{"use strict";oi=class{constructor(t,e,r={}){this.primary=t;this.fallback=e;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,e){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=e.onStart)==null||o.call(e)},onEnd:()=>{var o;return(o=e.onEnd)==null?void 0:o.call(e)},onError:o=>{var s,a,i;if(r){(s=e.onError)==null||s.call(e,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,e)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,e,r,o;(e=(t=this.primary).destroy)==null||e.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Ou={};Ni(Ou,{FallbackSpeechEngine:()=>oi,RuntypeSpeechEngine:()=>ri});var $u=zs(()=>{"use strict";Fu();_u()});var Hb={};Ni(Hb,{createThemePreview:()=>ug});module.exports=Sg(Hb);var Zp=null,js=null,is=null;var eu=()=>js?Promise.resolve(js):is||(Zp?(is=Zp().then(n=>(js=n,n)),is):(is=Promise.resolve().then(()=>(Yp(),Jp)).then(n=>(js=n,n)),is)),ls=()=>js;var Tg=n=>{if(n)return n},Fi=n=>{let t=null;return e=>{var o,s;let r=ls();if(!r)return ho(e);if(!t){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Tg(n==null?void 0:n.renderer);d&&t.use({renderer:d})}return t.parse(e)}},Oa=n=>n?Fi({markedOptions:n.options,renderer:n.renderer}):Fi(),$b=Fi();var ho=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Eg={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Mg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,kg=()=>{let n=null;return t=>{let e=ls();if(!e)return ho(t);if(!n){let{DOMPurify:r}=e;n=r(typeof window!="undefined"?window:void 0),n.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Mg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(t,Eg)}},$a=n=>n===!1?null:typeof n=="function"?n:kg();var No="webmcp:",_i=new Map,tu=n=>{var t;_i.clear();for(let e of n){let r=(t=e.title)==null?void 0:t.trim();r&&_i.set(e.name,r)}},Oi=n=>_i.get(su(n)),qa={warn(n,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...t)}},nu=null;function ou(n){if(n.length===0)return"0:empty";let t=n.map(e=>{var r,o;return[e.name,(r=e.description)!=null?r:"",e.parametersSchema?JSON.stringify(e.parametersSchema):"",(o=e.origin)!=null?o:"",e.annotations?JSON.stringify(e.annotations):""].join("")}).sort();return`${n.length}:${Lg(t.join(""))}`}function ru(n,t){let e=3735928559^t,r=1103547991^t;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);e=Math.imul(e^s,2654435761),r=Math.imul(r^s,1597334677)}return e=Math.imul(e^e>>>16,2246822507),e^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(e^e>>>13,3266489909),4294967296*(2097151&r)+(e>>>0)}function Lg(n){let t=ru(n,0).toString(36),e=ru(n,2654435761).toString(36);return`${t}.${e}`}var Ua=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var e;this.confirmHandler=(e=t.onConfirm)!=null?e:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let e;try{e=await t.getTools()}catch(o){return qa.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}tu(e);let r=typeof location!="undefined"?location.origin:"";return e.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Pg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,e,r){if(await this.ensureReady(),this.config.enabled!==!0)return yr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return yr(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=su(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return yr(`Failed to read WebMCP registry: ${x}`)}tu(a);let i=a.find(v=>v.name===s);if(!i)return yr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return yr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return yr("Aborted by cancel()");let d=Oi(s),c={toolName:s,args:e,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return yr("User declined the tool call.");if(r!=null&&r.aborted)return yr("Aborted by cancel()");let g=new AbortController,f=!1,u=setTimeout(()=>{f=!0,g.abort()},this.timeoutMs),m=()=>g.abort();r&&(r.aborted?g.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,Hg(e),{signal:g.signal});return Wg(v)}catch(v){if(f)return yr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return yr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return yr(x)}finally{clearTimeout(u),r&&r.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(nu?await nu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){qa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let e=t;return typeof e.getTools!="function"||typeof e.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,qa.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let e=(r=this.confirmHandler)!=null?r:Rg;try{return await e(t)}catch(o){return qa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let e=this.config.allowlist;return!e||e.length===0?!0:e.some(r=>Ig(t,r))}},su=n=>n.startsWith(No)?n.slice(No.length):n,Vs=n=>n.startsWith(No),Ig=(n,t)=>{if(t==="*")return!0;let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+e.replace(/\*/g,".*")+"$").test(n)},Pg=n=>{if(!(n===void 0||n===""))try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Wg=n=>{if(n==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Dg(t)}]}},yr=n=>({isError:!0,content:[{type:"text",text:n}]}),Rg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Bg(n.args),e=`Allow the AI to call ${n.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
- ${e}`:"")+(n.description?`
4
+ ${t}`:"")+(n.description?`
5
5
 
6
- ${n.description}`:"");return window.confirm(t)},Ig=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},Wg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Rg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var yo=require("partial-json");var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Nr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Lt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Gs=(...n)=>n.filter(Boolean).join(" ");var Oi="ask_user_question",Qs=8,ds="data-persona-ask-sheet-for",Hg="Other",Bg="Other\u2026",au="Type your own answer here",iu="Send",Dg="Next",Ng="Back",Fg="Submit all",Og="Skip",_g=3,_i="data-ask-current-index",$i="data-ask-question-count",lu="data-ask-answers",qi="data-ask-grouped",cu="data-ask-layout",$g=n=>n.layout==="pills"?"pills":"rows",qg=n=>n.getAttribute(cu)==="pills"?"pills":"rows",su=!1,du=n=>n.replace(/["\\]/g,"\\$&"),Fo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Oi,Ui=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},ps=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=(0,yo.parse)(o,yo.STR|yo.OBJ|yo.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Xs=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>Qs&&!su&&(su=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Qs}.`)),e.slice(0,Qs)},Ug=n=>{var e;return(e=Xs(n)[0])!=null?e:null},zg=(n,e)=>{var t;return(t=Xs(n)[e])!=null?t:null},jg=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},pu=(n,e,t)=>{if(n!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},Vg=(n,e,t,r)=>{let s=b("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=b("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=pu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Kg=n=>{let t=b("span",n==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},Gg=(n,e,t,r)=>{var g,f,u;let s=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<_g;m++)s.appendChild(Kg(r));return s}if(d.forEach((m,v)=>{s.appendChild(Vg(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Hg:Bg;if(r==="rows"){let v=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(g=e.freeTextPlaceholder)!=null?g:au,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),x.appendChild(E),v.appendChild(x);let k=pu(r,a,d.length);k&&v.appendChild(k),s.appendChild(v)}else{let v=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(u=e.freeTextLabel)!=null?u:m,s.appendChild(v)}}return s},uu=(n,e)=>{var s,a;let r=b("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:au,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:iu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Qg=n=>{var r;let e=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=b("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:iu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Xg=(n,e,t)=>{var c,g,f,u;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Ng,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(g=t.skipLabel)!=null?g:Og,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(f=t.submitAllLabel)!=null?f:Fg:(u=t.nextLabel)!=null?u:Dg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Oo=n=>{let e=n.getAttribute(lu);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},mu=(n,e)=>{n.setAttribute(lu,JSON.stringify(e))},pr=n=>{var t;let e=Number((t=n.getAttribute(_i))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Jg=(n,e)=>{n.setAttribute(_i,String(Math.max(0,Math.floor(e))))},us=n=>{var t;let e=Number((t=n.getAttribute($i))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},bo=n=>n.getAttribute(qi)==="true",Yg=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Zg=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},Ua=(n,e)=>{let{payload:t}=ps(e),r=Xs(t),o=Oo(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},gu=n=>{let e=Oo(n),t=pr(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",g=o.has(c);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},fu=n=>{if(!bo(n))return;let e=Oo(n),t=pr(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},zi=(n,e,t)=>{let r=Ui(t),o=qg(n),{payload:s,complete:a}=ps(e),i=bo(n),d=pr(n),c=us(n),g=i?zg(s,d):Ug(s),f=!!(g!=null&&g.multiSelect),u=n.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let L=typeof(g==null?void 0:g.question)=="string"?g.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let L=Gg(g,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=n.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(uu(r,o))}let E=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!E?n.appendChild(Qg(r)):(!f||i)&&E&&E.remove(),n.setAttribute("data-multi-select",f?"true":"false");let k=n.querySelector('[data-ask-nav-row="true"]');if(i){let L=Xg(d,c,r);k?k.replaceWith(L):n.appendChild(L)}else k&&k.remove();gu(n),fu(n)},ef=(n,e,t)=>{let r=Ui(e),o=$g(r),s=n.toolCall.id,a=Xs(t),i=Math.max(1,a.length),d=i>1,c=Yg(n,a),g=d?Zg(n,i):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(ds,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute($i,String(i)),f.setAttribute(_i,String(g)),f.setAttribute(qi,d?"true":"false"),f.setAttribute(cu,o),mu(f,c),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),jg(f,r);let u=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",u.appendChild(v),f.appendChild(u);let E=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),f.appendChild(E),o!=="rows"&&f.appendChild(uu(r,o)),zi(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},tf=(n,e,t)=>{let{payload:r}=ps(e),o=Math.max(1,Xs(r).length);o>us(n)&&(n.setAttribute($i,String(o)),o>1&&!bo(n)&&n.setAttribute(qi,"true")),zi(n,e,t)};var za=(n,e,t)=>{if(!t||!Fo(n)||Ui(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${ds}]`).forEach(c=>{c.getAttribute(ds)!==o&&c.remove()});let a=t.querySelector(`[${ds}="${du(o)}"]`);if(a){tf(a,n,e);return}let{payload:i}=ps(n),d=ef(n,e,i);t.appendChild(d)},ms=(n,e)=>{if(!n)return;let t=e?`[${ds}="${du(e)}"]`:`[${ds}]`;n.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},ji=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),vo=(n,e)=>{let t=Oo(n),r=pr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,mu(n,t),gu(n),fu(n)},ja=(n,e,t,r)=>{let o=us(n),s=Math.max(0,Math.min(o-1,r));Jg(n,s),zi(n,e,t)};var Gr="suggest_replies";var nf={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},hu={name:Gr,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:nf,origin:"sdk",annotations:{readOnlyHint:!0}},Vi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ki=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===Gr},rf=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},yu=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Ki(r))continue;let o=rf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},bu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var of={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Qs,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},sf={name:Oi,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:of,origin:"sdk",annotations:{readOnlyHint:!0}},Gi=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(sf),bu(n)&&e.push(hu),e};var gs=require("partial-json"),vu=n=>n.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},af=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},xu=n=>n.status==="complete"?af(n):n.status==="pending"?"Waiting":"",lf=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var wu=n=>n.status==="complete"?lf(n):"Using tool...",Va=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Ys=n=>{var t,r,o;let e=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Va(e)},Ka=n=>{var t,r,o;let e=n.durationMs!==void 0?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Va(e)},Qi=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Ys(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Ga=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Js(r,t.slice(s,a.index),[]),a[1]!==void 0?Js(r,a[1],["bold"]):a[2]!==void 0?Js(r,a[2],["italic"]):a[3]!==void 0&&Js(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Js(r,t.slice(s),[]),r},Js=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},cf=()=>{let n=null,e=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
6
+ ${n.description}`:"");return window.confirm(e)},Bg=n=>{if(n==null)return"";try{let t=JSON.stringify(n,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(n)}},Hg=n=>{if(n===void 0)return"{}";try{let t=JSON.stringify(n);return t===void 0?"{}":t}catch{return"{}"}},Dg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var bo=require("partial-json");var y=(n,t)=>{let e=document.createElement(n);return t&&(e.className=t),e},Dr=(n,t,e)=>{let r=n.createElement(t);return e&&(r.className=e),r};var It=(n,t={},...e)=>{let r=document.createElement(n);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=e.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Ks=(...n)=>n.filter(Boolean).join(" ");var $i="ask_user_question",Gs=8,cs="data-persona-ask-sheet-for",Ng="Other",Fg="Other\u2026",iu="Type your own answer here",lu="Send",_g="Next",Og="Back",$g="Submit all",qg="Skip",Ug=3,qi="data-ask-current-index",Ui="data-ask-question-count",cu="data-ask-answers",zi="data-ask-grouped",du="data-ask-layout",zg=n=>n.layout==="pills"?"pills":"rows",jg=n=>n.getAttribute(du)==="pills"?"pills":"rows",au=!1,pu=n=>n.replace(/["\\]/g,"\\$&"),Fo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===$i,ji=n=>{var t,e;return(e=(t=n==null?void 0:n.features)==null?void 0:t.askUserQuestion)!=null?e:{}},ds=n=>{let t=n.toolCall;if(!t)return{payload:null,complete:!1};let e=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:e};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:e};try{let o=r.join(""),s=(0,bo.parse)(o,bo.STR|bo.OBJ|bo.ARR);if(s&&typeof s=="object")return{payload:s,complete:e}}catch{}return{payload:null,complete:e}},Qs=n=>{let t=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return t.length>Gs&&!au&&(au=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Gs}.`)),t.slice(0,Gs)},Vg=n=>{var t;return(t=Qs(n)[0])!=null?t:null},Kg=(n,t)=>{var e;return(e=Qs(n)[t])!=null?e:null},Gg=(n,t)=>{let e=t.styles;e&&(e.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",e.sheetBackground),e.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",e.sheetBorder),e.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",e.sheetShadow),e.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",e.pillBackground),e.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",e.pillBackgroundSelected),e.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",e.pillTextColor),e.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",e.pillTextColorSelected),e.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",e.pillBorderRadius),e.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",e.customInputBackground))},uu=(n,t,e)=>{if(n!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(e+1),r.appendChild(o)}return r},Qg=(n,t,e,r)=>{let s=y("button",e==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",n.label),e==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=y("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=uu(e,r,t);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Xg=n=>{let e=y("span",n==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return e.setAttribute("aria-hidden","true"),e},Jg=(n,t,e,r)=>{var g,f,u;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!e){for(let m=0;m<Ug;m++)s.appendChild(Xg(r));return s}if(d.forEach((m,v)=>{s.appendChild(Qg(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Ng:Fg;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(g=t.freeTextPlaceholder)!=null?g:iu,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:m),x.appendChild(E),v.appendChild(x);let M=uu(r,a,d.length);M&&v.appendChild(M),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(u=t.freeTextLabel)!=null?u:m,s.appendChild(v)}}return s},mu=(n,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:iu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:lu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Yg=n=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let e=y("button","persona-ask-multi-submit persona-pointer-events-auto");return e.type="button",e.textContent=(r=n.submitLabel)!=null?r:lu,e.setAttribute("data-ask-user-action","submit-multi"),e.disabled=!0,t.appendChild(e),t},Zg=(n,t,e)=>{var c,g,f,u;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=e.backLabel)!=null?c:Og,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(g=e.skipLabel)!=null?g:qg,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===t-1;return i.textContent=d?(f=e.submitAllLabel)!=null?f:$g:(u=e.nextLabel)!=null?u:_g,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},_o=n=>{let t=n.getAttribute(cu);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}},gu=(n,t)=>{n.setAttribute(cu,JSON.stringify(t))},dr=n=>{var e;let t=Number((e=n.getAttribute(qi))!=null?e:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ef=(n,t)=>{n.setAttribute(qi,String(Math.max(0,Math.floor(t))))},ps=n=>{var e;let t=Number((e=n.getAttribute(Ui))!=null?e:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=n=>n.getAttribute(zi)==="true",tf=(n,t)=>{var o;let e=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!e||typeof e!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(e,i)){let d=e[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},nf=(n,t)=>{var r;let e=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(t-1,Math.floor(e)))},za=(n,t)=>{let{payload:e}=ds(t),r=Qs(e),o=_o(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},fu=n=>{let t=_o(n),e=dr(n),r=t[e],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",g=o.has(c);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},hu=n=>{if(!yo(n))return;let t=_o(n),e=dr(n),r=t[e],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Vi=(n,t,e)=>{let r=ji(e),o=jg(n),{payload:s,complete:a}=ds(t),i=yo(n),d=dr(n),c=ps(n),g=i?Kg(s,d):Vg(s),f=!!(g!=null&&g.multiSelect),u=n.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let S=typeof(g==null?void 0:g.question)=="string"?g.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let S=Jg(g,r,a,o);x.replaceWith(S)}if(o!=="rows"){let S=n.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(mu(r,o))}let E=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!E?n.appendChild(Yg(r)):(!f||i)&&E&&E.remove(),n.setAttribute("data-multi-select",f?"true":"false");let M=n.querySelector('[data-ask-nav-row="true"]');if(i){let S=Zg(d,c,r);M?M.replaceWith(S):n.appendChild(S)}else M&&M.remove();fu(n),hu(n)},rf=(n,t,e)=>{let r=ji(t),o=zg(r),s=n.toolCall.id,a=Qs(e),i=Math.max(1,a.length),d=i>1,c=tf(n,a),g=d?nf(n,i):0,f=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(cs,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(Ui,String(i)),f.setAttribute(qi,String(g)),f.setAttribute(zi,d?"true":"false"),f.setAttribute(du,o),gu(f,c),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Gg(f,r);let u=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=y("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",u.appendChild(v),f.appendChild(u);let E=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),f.appendChild(E),o!=="rows"&&f.appendChild(mu(r,o)),Vi(f,n,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},of=(n,t,e)=>{let{payload:r}=ds(t),o=Math.max(1,Qs(r).length);o>ps(n)&&(n.setAttribute(Ui,String(o)),o>1&&!yo(n)&&n.setAttribute(zi,"true")),Vi(n,t,e)};var ja=(n,t,e)=>{if(!e||!Fo(n)||ji(t).enabled===!1)return;let o=n.toolCall.id;e.querySelectorAll(`[${cs}]`).forEach(c=>{c.getAttribute(cs)!==o&&c.remove()});let a=e.querySelector(`[${cs}="${pu(o)}"]`);if(a){of(a,n,t);return}let{payload:i}=ds(n),d=rf(n,t,i);e.appendChild(d)},us=(n,t)=>{if(!n)return;let e=t?`[${cs}="${pu(t)}"]`:`[${cs}]`;n.querySelectorAll(e).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Ki=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),vo=(n,t)=>{let e=_o(n),r=dr(n);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete e[r]:e[r]=t,gu(n,e),fu(n),hu(n)},Va=(n,t,e,r)=>{let o=ps(n),s=Math.max(0,Math.min(o-1,r));ef(n,s),Vi(n,t,e)};var Gr="suggest_replies";var sf={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},bu={name:Gr,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:sf,origin:"sdk",annotations:{readOnlyHint:!0}},Gi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Qi=n=>{var t;return n.variant==="tool"&&((t=n.toolCall)==null?void 0:t.name)===Gr},af=n=>{let t=n;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let e=t==null?void 0:t.suggestions;if(!Array.isArray(e))return[];let r=e.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},yu=n=>{var t;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.role==="user")return null;if(!Qi(r))continue;let o=af((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},vu=n=>{var e;let t=(e=n==null?void 0:n.features)==null?void 0:e.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var lf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Gs,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},cf={name:$i,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:lf,origin:"sdk",annotations:{readOnlyHint:!0}},Xi=n=>{var r;let t=[],e=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1&&t.push(cf),vu(n)&&t.push(bu),t};var ms=require("partial-json"),xu=n=>n.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),gs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},df=n=>{var a,i;let t=(a=n.completedAt)!=null?a:Date.now(),e=(i=n.startedAt)!=null?i:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-e))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},wu=n=>n.status==="complete"?df(n):n.status==="pending"?"Waiting":"",pf=n=>{var o,s,a;let e=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return e<.1?"Used tool for <0.1 seconds":`Used tool for ${e>=10?Math.round(e).toString():e.toFixed(1).replace(/\.0$/,"")} seconds`};var Cu=n=>n.status==="complete"?pf(n):"Using tool...",Ka=n=>{let t=n/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=n=>{var e,r,o;let t=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((e=n.completedAt)!=null?e:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ka(t)},Ga=n=>{var e,r,o;let t=n.durationMs!==void 0?n.durationMs:Math.max(0,((e=n.completedAt)!=null?e:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ka(t)},Ji=(n,t,e)=>{var s;if(!t)return e;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Js(n);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Qa=(n,t)=>{let e=n.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(e))!==null;)a.index>s&&Xs(r,e.slice(s,a.index),[]),a[1]!==void 0?Xs(r,a[1],["bold"]):a[2]!==void 0?Xs(r,a[2],["italic"]):a[3]!==void 0&&Xs(r,a[3],["dim"]),s=a.index+a[0].length;return s<e.length&&Xs(r,e.slice(s),[]),r},Xs=(n,t,e)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:e}),o<r.length-1&&n.push({text:"{duration}",styles:e,isDuration:!0})},uf=()=>{let n=null,t=0,e=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},_o=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Cu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Au=()=>{var e;let n=cf();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Su=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=(0,gs.parse)(t,gs.STR|gs.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?vu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=vu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Tu=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Qa=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var s,a,i;let r=(i=(s=t==null?void 0:t.seq)!=null?s:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(e,t);return}let o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(r,{payloadType:e,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let e=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of e)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Mu="3.36.0";var Zs=Mu;var pf="https://api.runtype.com/v1/dispatch",Xa="https://api.runtype.com";function uf(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Xi=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function mf(n){switch(n){case"json":return Su;case"regex-json":return Au;case"xml":return Tu;default:return Cu}}var Eu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function gf(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Eu(t);if(!Eu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=_o(n);return _o(e)!==null&&a===null?e:n}var ea=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;this.apiUrl=(t=e.apiUrl)!=null?t:pf,this.headers={"Content-Type":"application/json","X-Persona-Version":Zs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:mf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new qa(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zs},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zs},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let I=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:I}),I}let c=await this.buildPayload(e.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Xi).map(I=>{var R,A,W;return{id:I.id,role:I.role,content:(W=(A=(R=I.contentParts)!=null?R:I.llmContent)!=null?A:I.rawContent)!=null?W:I.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},u=c.clientTools,m=!!(u&&u.length>0),v=m?ru(u):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&x&&this.lastSentClientToolsFingerprint===v,k=!1,L=null,F;for(let I=0;;I++){let A={...f,...m&&(k||!E)&&u?{clientTools:u}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),F=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zs},body:JSON.stringify(A),signal:r.signal}),F.status===409&&I===0&&m){let W=await F.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){k=!0,this.lastSentClientToolsFingerprint=null;continue}L=W!=null?W:{error:"Chat request failed"}}break}if(!F.ok){let I=L!=null?L:await F.json().catch(()=>({error:"Chat request failed"}));if(F.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(F.status===429){let A=new Error(I.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let R=new Error(I.error||"Failed to send message");throw t({type:"error",error:R}),R}if(!F.body){let I=new Error("No response body received");throw t({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(F.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Xa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,g;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Xa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(g=r==null?void 0:r.streamResponse)!=null?g:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(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(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Gi(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(e){var s,a;let r={messages:e.slice().filter(Xi).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Gi(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=g=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...g!==void 0&&{partId:g}};return r.current=f,o(f),f},c=g=>r.current?r.current:d(g);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let g=c(i.partId);i.partId!==void 0&&!g.partId&&(g.partId=i.partId),g.content+=i.text,o(g)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r){var vn,Rt,pn,Cr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=q=>{let G=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,ye=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,Qe=q.tools?q.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...q,reasoning:G,toolCall:ye,tools:Qe}},f=q=>{if(q.role!=="assistant"||q.variant)return!0;let G=Array.isArray(q.contentParts)&&q.contentParts.length>0,ye=typeof q.rawContent=="string"&&q.rawContent.trim()!=="";return typeof q.content=="string"&&q.content.trim()!==""||G||ye||!!q.stopReason},u=q=>{f(q)&&t({type:"message",message:g(q)})},m=null,v=null,x={current:null},E={current:null},k=!1,L=new Map,F=new Map,I=new Map,R=new Map,A={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},D=(q,G,ye="")=>`${q}::${G}::${ye}`,N=(q,G)=>`${q}::${G}::`,M=(q,G,ye,Qe)=>{let et=D(q,G,ye),qe=I.get(et);if(qe)return qe;let _e=ye?`-${ye}`:"",Pt={id:`nested-${q}-${G}${_e}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ye?{partId:ye}:{},agentMetadata:{executionId:Qe,parentToolId:q,parentStepId:G}};return I.set(et,Pt),u(Pt),Pt},z=q=>{if(q==null)return null;try{return String(q)}catch{return null}},j=q=>{var G,ye,Qe,et,qe;return z((qe=(et=(Qe=(ye=(G=q.stepId)!=null?G:q.step_id)!=null?ye:q.step)!=null?Qe:q.parentId)!=null?et:q.flowStepId)!=null?qe:q.flow_step_id)},oe=q=>{var G,ye,Qe,et,qe,_e,Pt;return z((Pt=(_e=(qe=(et=(Qe=(ye=(G=q.callId)!=null?G:q.call_id)!=null?ye:q.requestId)!=null?Qe:q.request_id)!=null?et:q.toolCallId)!=null?qe:q.tool_call_id)!=null?_e:q.stepId)!=null?Pt:q.step_id)},Le=r,Ve=!1,ve=()=>{if(m)return m;let q;return!Ve&&Le?(q=Le,Ve=!0):Le&&E.current?q=`${Le}_${E.current}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:q,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(m),m},Be=(q,G)=>{A.lastId=G,q&&A.byStep.set(q,G)},Oe=(q,G)=>{var qe;let ye=(qe=q.reasoningId)!=null?qe:q.id,Qe=j(q);if(ye){let _e=String(ye);return Be(Qe,_e),_e}if(Qe){let _e=A.byStep.get(Qe);if(_e)return A.lastId=_e,_e}if(A.lastId&&!G)return A.lastId;if(!G)return null;let et=`reason-${c()}`;return Be(Qe,et),et},Te=q=>{let G=L.get(q);if(G)return G;let ye={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:q,status:"streaming",chunks:[]}};return L.set(q,ye),u(ye),ye},we=(q,G)=>{W.lastId=G,q&&W.byCall.set(q,G)},se=new Set,Q=new Map,ae=new Set,fe=new Map,ue=q=>{if(!q)return!1;let G=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return G==="emit_artifact_markdown"||G==="emit_artifact_component"},K=(q,G)=>{var qe;let ye=(qe=q.toolId)!=null?qe:q.id,Qe=oe(q);if(ye){let _e=String(ye);return we(Qe,_e),_e}if(Qe){let _e=W.byCall.get(Qe);if(_e)return W.lastId=_e,_e}if(W.lastId&&!G)return W.lastId;if(!G)return null;let et=`tool-${c()}`;return we(Qe,et),et},ie=q=>{let G=F.get(q);if(G)return G;let ye={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:q,status:"pending"}};return F.set(q,ye),u(ye),ye},We=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let G=Number(q);if(!Number.isNaN(G)&&Number.isFinite(G))return G;let ye=Date.parse(q);if(!Number.isNaN(ye))return ye}return Date.now()},te=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},ee=new Map,re=new Map,it=new Map,lt=new Map,st=null,Ee=(q,G,ye)=>{var Pt;let Qe=it.get(q);Qe||(Qe=[],it.set(q,Qe));let et=0,qe=Qe.length;for(;et<qe;){let Kt=et+qe>>>1;Qe[Kt].seq<G?et=Kt+1:qe=Kt}((Pt=Qe[et])==null?void 0:Pt.seq)===G?Qe[et]={seq:G,text:ye}:Qe.splice(et,0,{seq:G,text:ye});let _e="";for(let Kt=0;Kt<Qe.length;Kt++)_e+=Qe[Kt].text;return _e},he=(q,G)=>{let ye=te(G),Qe=re.get(q.id),et=gf(Qe,ye);q.rawContent=et;let qe=ee.get(q.id),_e=V=>{var ce;let Ht=(ce=q.content)!=null?ce:"";V.trim()!==""&&(Ht.trim().length===0||V.startsWith(Ht)||V.trimStart().startsWith(Ht.trim()))&&(q.content=V)},Pt=()=>{var V;if(qe){let Ht=(V=qe.close)==null?void 0:V.call(qe);Ht instanceof Promise&&Ht.catch(()=>{})}ee.delete(q.id),re.delete(q.id),q.streaming=!1,u(q)};if(!qe){_e(ye),Pt();return}let Kt=_o(et);if(Kt!==null&&Kt.trim()!==""){_e(Kt),Pt();return}let Jt=V=>{var Ce;let Ht=typeof V=="string"?V:(Ce=V==null?void 0:V.text)!=null?Ce:null;if(Ht!==null&&Ht.trim()!=="")return Ht;let ce=qe.getExtractedText();return ce!==null&&ce.trim()!==""?ce:ye},Ln;try{Ln=qe.processChunk(et)}catch{_e(ye),Pt();return}if(Ln instanceof Promise){Ln.then(V=>{_e(Jt(V)),Pt()}).catch(()=>{_e(ye),Pt()});return}_e(Jt(Ln)),Pt()},Je=[],Y=!1,me,ke=()=>{Y||(Y=!0,queueMicrotask(()=>{Y=!1,me()}))},Ye=new Qa((q,G)=>{Je.push({payloadType:q,payload:G}),ke()}),Ge=null,Ie=new Map,Ke=(vn=this.config.iterationDisplay)!=null?vn:"separate";for(me=()=>{var q,G,ye,Qe,et,qe,_e,Pt,Kt,Jt,Ln,V,Ht,ce,Ce,Fe,Tt,on,sn,xn,Nt,rt,Dt,pt,Yt,nr,Pn,an,On,Ar,xt,zn,Sr,Fr,mr,bt,Co,Tr,Ao,_n,Ko,Yr,Or,Zr,eo,So,To,to,Ct,jn,Vn,In,Mt,rr,or,Kn,no,_r,ro,Gn,Ft,Wn,sr,oo,$r,so,Mr,Qn,be,ut,tn,un,Er,Es,qr,Mo,kr,_,Go,Lr,Pr,Ur,Ir,gr,Qo,wa,Xn,Jn,fr,hr,Eo,zr,An,Wr,Xo,ko,Jo,Ca,Yo,Aa,Zo,yt,ks,ar,$n,Sa,Ta,es,jr,Ls,ao,Ps,Is,Ws,Rs,qn,ts,Rr,Hr,Hs,Ma,Bs,Ds,Lo,Ea,ka,La,Pa,Ia,io,lo,Wa,Ns,co,Ra,Fs,po,Os;for(let ns=0;ns<Je.length;ns++){let Ue=Je[ns].payloadType,C=Je[ns].payload;if(Ue==="reason_start"){let $=(q=Oe(C,!0))!=null?q:`reason-${c()}`,T=Te($);T.reasoning=(G=T.reasoning)!=null?G:{id:$,status:"streaming",chunks:[]},T.reasoning.startedAt=(Qe=T.reasoning.startedAt)!=null?Qe:We((ye=C.startedAt)!=null?ye:C.timestamp),T.reasoning.completedAt=void 0,T.reasoning.durationMs=void 0,T.streaming=!0,T.reasoning.status="streaming",u(T)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let $=(qe=(et=Oe(C,!1))!=null?et:Oe(C,!0))!=null?qe:`reason-${c()}`,T=Te($);T.reasoning=(_e=T.reasoning)!=null?_e:{id:$,status:"streaming",chunks:[]},T.reasoning.startedAt=(Kt=T.reasoning.startedAt)!=null?Kt:We((Pt=C.startedAt)!=null?Pt:C.timestamp);let J=(V=(Ln=(Jt=C.reasoningText)!=null?Jt:C.text)!=null?Ln:C.delta)!=null?V:"";if(J&&C.hidden!==!0){let le=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(le!==void 0){let X=Ee($,le,String(J));T.reasoning.chunks=[X]}else T.reasoning.chunks.push(String(J))}if(T.reasoning.status=C.done?"complete":"streaming",C.done){T.reasoning.completedAt=We((Ht=C.completedAt)!=null?Ht:C.timestamp);let le=(ce=T.reasoning.startedAt)!=null?ce:Date.now();T.reasoning.durationMs=Math.max(0,((Ce=T.reasoning.completedAt)!=null?Ce:Date.now())-le)}T.streaming=T.reasoning.status!=="complete",u(T)}else if(Ue==="reason_complete"){let $=(Tt=(Fe=Oe(C,!1))!=null?Fe:Oe(C,!0))!=null?Tt:`reason-${c()}`,T=L.get($);if(T!=null&&T.reasoning){T.reasoning.status="complete",T.reasoning.completedAt=We((on=C.completedAt)!=null?on:C.timestamp);let le=(sn=T.reasoning.startedAt)!=null?sn:Date.now();T.reasoning.durationMs=Math.max(0,((xn=T.reasoning.completedAt)!=null?xn:Date.now())-le),T.streaming=!1,u(T)}let J=j(C);J&&A.byStep.delete(J)}else if(Ue==="tool_start"){let $=(Nt=K(C,!0))!=null?Nt:`tool-${c()}`,T=(rt=C.toolName)!=null?rt:C.name;if(ue(T)){se.add($);continue}let J=ie($),le=(Dt=J.toolCall)!=null?Dt:{id:$,status:"pending"};le.name=T!=null?T:le.name,le.status="running",C.args!==void 0?le.args=C.args:C.parameters!==void 0&&(le.args=C.parameters),le.startedAt=(Yt=le.startedAt)!=null?Yt:We((pt=C.startedAt)!=null?pt:C.timestamp),le.completedAt=void 0,le.durationMs=void 0,J.toolCall=le,J.streaming=!0;let X=C.agentContext;(X||C.executionId)&&(J.agentMetadata={executionId:(nr=X==null?void 0:X.executionId)!=null?nr:C.executionId,iteration:(Pn=X==null?void 0:X.iteration)!=null?Pn:C.iteration}),u(J)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let $=(On=(an=K(C,!1))!=null?an:K(C,!0))!=null?On:`tool-${c()}`;if(se.has($))continue;let T=ie($),J=(Ar=T.toolCall)!=null?Ar:{id:$,status:"running"};J.startedAt=(zn=J.startedAt)!=null?zn:We((xt=C.startedAt)!=null?xt:C.timestamp);let le=(mr=(Fr=(Sr=C.text)!=null?Sr:C.delta)!=null?Fr:C.message)!=null?mr:"";le&&(J.chunks=(bt=J.chunks)!=null?bt:[],J.chunks.push(String(le))),J.status="running",T.toolCall=J,T.streaming=!0;let X=C.agentContext;(X||C.executionId)&&(T.agentMetadata=(Ao=T.agentMetadata)!=null?Ao:{executionId:(Co=X==null?void 0:X.executionId)!=null?Co:C.executionId,iteration:(Tr=X==null?void 0:X.iteration)!=null?Tr:C.iteration}),u(T)}else if(Ue==="tool_complete"){let $=(Ko=(_n=K(C,!1))!=null?_n:K(C,!0))!=null?Ko:`tool-${c()}`;if(se.has($)){se.delete($);continue}let T=ie($),J=(Yr=T.toolCall)!=null?Yr:{id:$,status:"running"};J.status="complete",C.result!==void 0&&(J.result=C.result),typeof C.duration=="number"&&(J.duration=C.duration),J.completedAt=We((Or=C.completedAt)!=null?Or:C.timestamp);let le=(Zr=C.duration)!=null?Zr:C.executionTime;if(typeof le=="number")J.durationMs=le;else{let $e=(eo=J.startedAt)!=null?eo:Date.now();J.durationMs=Math.max(0,((So=J.completedAt)!=null?So:Date.now())-$e)}T.toolCall=J,T.streaming=!1;let X=C.agentContext;(X||C.executionId)&&(T.agentMetadata=(Ct=T.agentMetadata)!=null?Ct:{executionId:(To=X==null?void 0:X.executionId)!=null?To:C.executionId,iteration:(to=X==null?void 0:X.iteration)!=null?to:C.iteration}),u(T);let Me=oe(C);Me&&W.byCall.delete(Me)}else if(Ue==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,T=(jn=$!=null?$:C.toolId)!=null?jn:`local-${c()}`,J=ie(T),le=C.toolName,X=Ks(le),Me=(Vn=J.toolCall)!=null?Vn:{id:T,status:"pending"};Me.name=le,Me.args=C.parameters,Me.status=X?"running":"complete",Me.chunks=(In=Me.chunks)!=null?In:[],Me.startedAt=(rr=Me.startedAt)!=null?rr:We((Mt=C.startedAt)!=null?Mt:C.timestamp),X?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(or=Me.completedAt)!=null?or:Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(no=C.executionId)!=null?no:(Kn=J.agentMetadata)==null?void 0:Kn.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(J)}else if(Ue==="text_start"){if((_r=C.toolContext)!=null&&_r.toolId)continue;let $=C.partId;if($!==void 0&&E.current!==null&&$!==E.current){let T=m;T&&(T.streaming=!1,u(T),st=T,m=null,k=!0)}$!==void 0&&(E.current=$)}else if(Ue==="text_end"){if((ro=C.toolContext)!=null&&ro.toolId)continue;let $=m;$&&($.streaming=!1,u($),st=$,m=null,k=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let $=C.stepType,T=C.executionType;if($==="tool"||T==="context")continue;let J=C.toolContext;if(J!=null&&J.toolId){let $e=String((Ft=(Gn=C.id)!=null?Gn:J.stepId)!=null?Ft:`step-${c()}`),at=C.partId!==void 0&&C.partId!==null?String(C.partId):"",tt=`${J.toolId}::${$e}`,Bt=R.get(tt);if(at!==""&&Bt!==void 0&&Bt!==""&&Bt!==at){let At=I.get(D(J.toolId,$e,Bt));At&&At.streaming!==!1&&(At.streaming=!1,u(At))}at!==""&&R.set(tt,at);let zt=M(J.toolId,$e,at,J.executionId),ln=($r=(oo=(sr=(Wn=C.text)!=null?Wn:C.delta)!=null?sr:C.content)!=null?oo:C.chunk)!=null?$r:"";ln&&(zt.content+=String(ln),zt.streaming=!0,u(zt)),C.isComplete&&(zt.streaming=!1,u(zt));continue}let le=C.partId;if(le!==void 0&&E.current!==null&&le!==E.current){let $e=m;$e&&($e.streaming=!1,u($e),st=$e,m=null,k=!0)}le!==void 0&&(E.current=le);let X=le!==void 0&&(so=lt.get(le))!=null?so:ve();le!==void 0&&(X.partId||(X.partId=le),lt.set(le,X));let Me=(ut=(be=(Qn=(Mr=C.text)!=null?Mr:C.delta)!=null?Qn:C.content)!=null?be:C.chunk)!=null?ut:"";if(Me){let $e=typeof C.seq=="number"?C.seq:void 0,at=le!=null?le:X.id,tt=$e!==void 0?Ee(at,$e,String(Me)):((tn=re.get(X.id))!=null?tn:"")+Me;X.rawContent=tt,ee.has(X.id)||ee.set(X.id,this.createStreamParser());let Bt=ee.get(X.id),zt=tt.trim().startsWith("{")||tt.trim().startsWith("[");if(zt&&re.set(X.id,tt),Bt.__isPlainTextParser===!0){X.content=$e!==void 0?tt:X.content+Me,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,u(X);continue}let At=Bt.processChunk(tt);if(At instanceof Promise)At.then(Et=>{var Rn;let yn=typeof Et=="string"?Et:(Rn=Et==null?void 0:Et.text)!=null?Rn:null;if(yn!==null&&yn.trim()!=="")X.content=yn,u(X);else if(!zt&&!tt.trim().startsWith("<")){let wn=m,Zt=wn&&wn.id===X.id?wn:X;Zt.id===X.id&&(Zt.content=$e!==void 0?tt:Zt.content+Me,re.delete(Zt.id),ee.delete(Zt.id),Zt.rawContent=void 0,u(Zt))}}).catch(()=>{X.content=$e!==void 0?tt:X.content+Me,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,u(X)});else{let Et=typeof At=="string"?At:(un=At==null?void 0:At.text)!=null?un:null;Et!==null&&Et.trim()!==""?(X.content=Et,u(X)):!zt&&!tt.trim().startsWith("<")&&(X.content=$e!==void 0?tt:X.content+Me,re.delete(X.id),ee.delete(X.id),X.rawContent=void 0,u(X))}}if(C.isComplete){let $e=(Es=(Er=C.result)==null?void 0:Er.response)!=null?Es:X.content;if($e){let at=re.get(X.id),tt=at!=null?at:te($e);X.rawContent=tt;let Bt=ee.get(X.id),zt=null,ln=!1;if(Bt&&(zt=Bt.getExtractedText(),zt===null&&(zt=_o(tt)),zt===null)){let At=Bt.processChunk(tt);At instanceof Promise?(ln=!0,At.then(Et=>{var Rn;let yn=typeof Et=="string"?Et:(Rn=Et==null?void 0:Et.text)!=null?Rn:null;if(yn!==null){let wn=m;wn&&wn.id===X.id&&(wn.content=yn,wn.streaming=!1,ee.delete(wn.id),re.delete(wn.id),u(wn))}})):zt=typeof At=="string"?At:(qr=At==null?void 0:At.text)!=null?qr:null}if(!ln){zt!==null&&zt.trim()!==""?X.content=zt:re.has(X.id)||(X.content=te($e));let At=ee.get(X.id);if(At){let Et=(Mo=At.close)==null?void 0:Mo.call(At);Et instanceof Promise&&Et.catch(()=>{}),ee.delete(X.id)}re.delete(X.id),X.streaming=!1,u(X)}}}}else if(Ue==="step_complete"){let $=C.stepType,T=C.executionType;if($==="tool"||T==="context")continue;let J=C.toolContext;if(J!=null&&J.toolId){let $e=String((_=(kr=C.id)!=null?kr:J.stepId)!=null?_:"");if($e){let at=N(J.toolId,$e);for(let[tt,Bt]of I)tt.startsWith(at)&&Bt.streaming!==!1&&(Bt.streaming=!1,u(Bt));R.delete(`${J.toolId}::${$e}`)}continue}let le=C.stopReason;if(k){if(m!==null){let tt=m;le&&(tt.stopReason=le),ee.delete(tt.id),re.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,u(tt))}let $e=(Go=C.result)==null?void 0:Go.response,at=st;at&&(le&&(at.stopReason=le),$e!=null?he(at,$e):(ee.delete(at.id),re.delete(at.id))),st=null;continue}let X=(Lr=C.result)==null?void 0:Lr.response,Me=ve();if(le&&(Me.stopReason=le),X!=null){let $e=ee.get(Me.id),at=!1,tt=!1;if($e){let Bt=$e.getExtractedText(),zt=re.get(Me.id),ln=zt!=null?zt:te(X);if(Me.rawContent=ln,Bt!==null&&Bt.trim()!=="")Me.content=Bt,at=!0;else{let At=_o(ln);if(At!==null)Me.content=At,at=!0;else{let Et=$e.processChunk(ln);if(Et instanceof Promise)tt=!0,Et.then(yn=>{var wn;let Rn=typeof yn=="string"?yn:(wn=yn==null?void 0:yn.text)!=null?wn:null;if(Rn!==null&&Rn.trim()!==""){let Zt=m;Zt&&Zt.id===Me.id&&(Zt.content=Rn,Zt.streaming=!1,ee.delete(Zt.id),re.delete(Zt.id),u(Zt))}else{let Zt=$e.getExtractedText(),ir=m;ir&&ir.id===Me.id&&(Zt!==null&&Zt.trim()!==""?ir.content=Zt:re.has(ir.id)||(ir.content=te(X)),ir.streaming=!1,ee.delete(ir.id),re.delete(ir.id),u(ir))}});else{let yn=typeof Et=="string"?Et:(Pr=Et==null?void 0:Et.text)!=null?Pr:null;if(yn!==null&&yn.trim()!=="")Me.content=yn,at=!0;else{let Rn=$e.getExtractedText();Rn!==null&&Rn.trim()!==""&&(Me.content=Rn,at=!0)}}}}}if(!tt){if(!Me.rawContent){let Bt=re.get(Me.id);Me.rawContent=Bt!=null?Bt:te(X)}if(!at&&!re.has(Me.id)&&(Me.content=te(X)),$e){let Bt=(Ur=$e.close)==null?void 0:Ur.call($e);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Me.id),re.delete(Me.id),Me.streaming=!1,u(Me)}}else ee.delete(Me.id),re.delete(Me.id),Me.streaming=!1,u(Me)}else if(Ue==="flow_complete"){let $=(Ir=C.result)==null?void 0:Ir.response;if(k){if(m!==null){let T=m;ee.delete(T.id),re.delete(T.id),T.streaming!==!1&&(T.streaming=!1,u(T))}}else if($!=null){let T=ve(),J=re.get(T.id),le=J!=null?J:te($);T.rawContent=le;let X=te($),Me=ee.get(T.id);if(Me){let tt=_o(le);if(tt!==null)X=tt;else{let Bt=Me.processChunk(le);Bt instanceof Promise&&Bt.then(ln=>{var Et;let At=typeof ln=="string"?ln:(Et=ln==null?void 0:ln.text)!=null?Et:null;At!==null&&(T.content=At,T.streaming=!1,u(T))});let zt=Me.getExtractedText();zt!==null&&(X=zt)}}ee.delete(T.id),re.delete(T.id);let $e=X!==T.content,at=T.streaming!==!1;$e&&(T.content=X),T.streaming=!1,($e||at)&&u(T)}else if(m!==null){let T=m;ee.delete(T.id),re.delete(T.id),T.streaming!==!1&&(T.streaming=!1,u(T))}t({type:"status",status:"idle"})}else if(Ue==="agent_start")Ge={executionId:C.executionId,agentId:(gr=C.agentId)!=null?gr:"virtual",agentName:(Qo=C.agentName)!=null?Qo:"",status:"running",currentIteration:0,maxTurns:(wa=C.maxTurns)!=null?wa:1,startedAt:We(C.startedAt)};else if(Ue==="agent_iteration_start"){if(Ge&&(Ge.currentIteration=C.iteration),Ke==="separate"&&C.iteration>1){let $=m;$&&($.streaming=!1,u($),Ie.set(C.iteration-1,$),m=null)}}else if(Ue==="agent_turn_start")v=null;else if(Ue==="agent_turn_delta"){if(C.contentType==="text"){let $=ve();$.content+=(Xn=C.delta)!=null?Xn:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:Ge==null?void 0:Ge.agentName},v=$,u($)}else if(C.contentType==="thinking"){let $=(Jn=C.turnId)!=null?Jn:`agent-think-${C.iteration}`,T=Te($);T.reasoning=(fr=T.reasoning)!=null?fr:{id:$,status:"streaming",chunks:[]},T.reasoning.chunks.push((hr=C.delta)!=null?hr:""),T.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},u(T)}else if(C.contentType==="tool_input"){let $=(Eo=C.toolCallId)!=null?Eo:W.lastId;if($){let T=F.get($);T!=null&&T.toolCall&&(T.toolCall.chunks=(zr=T.toolCall.chunks)!=null?zr:[],T.toolCall.chunks.push((An=C.delta)!=null?An:""),u(T))}}}else if(Ue==="agent_turn_complete"){let $=C.turnId;if($){let le=L.get($);if(le!=null&&le.reasoning){le.reasoning.status="complete",le.reasoning.completedAt=We(C.completedAt);let X=(Wr=le.reasoning.startedAt)!=null?Wr:Date.now();le.reasoning.durationMs=Math.max(0,((Xo=le.reasoning.completedAt)!=null?Xo:Date.now())-X),le.streaming=!1,u(le)}}let T=C.stopReason,J=m!=null?m:v;if(T&&J!==null){let le=C.turnId;(!le||((ko=J.agentMetadata)==null?void 0:ko.turnId)===le)&&(J.stopReason=T,u(J))}}else if(Ue==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let $=(Jo=C.toolCallId)!=null?Jo:`agent-tool-${c()}`;we(oe(C),$);let T=ie($),J=(Ca=T.toolCall)!=null?Ca:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};J.name=(Aa=(Yo=C.toolName)!=null?Yo:C.name)!=null?Aa:J.name,J.status="running",C.parameters!==void 0&&(J.args=C.parameters),J.startedAt=We((Zo=C.startedAt)!=null?Zo:C.timestamp),T.toolCall=J,T.streaming=!0,T.agentMetadata={executionId:C.executionId,iteration:C.iteration},u(T)}else if(Ue==="agent_tool_delta"){let $=(yt=C.toolCallId)!=null?yt:W.lastId;if($){let T=(ks=F.get($))!=null?ks:ie($);T.toolCall&&(T.toolCall.chunks=(ar=T.toolCall.chunks)!=null?ar:[],T.toolCall.chunks.push(($n=C.delta)!=null?$n:""),T.toolCall.status="running",T.streaming=!0,u(T))}}else if(Ue==="agent_tool_complete"){let $=(Sa=C.toolCallId)!=null?Sa:W.lastId;if($){let T=(Ta=F.get($))!=null?Ta:ie($);if(T.toolCall){T.toolCall.status="complete",C.result!==void 0&&(T.toolCall.result=C.result),typeof C.executionTime=="number"&&(T.toolCall.durationMs=C.executionTime),T.toolCall.completedAt=We((es=C.completedAt)!=null?es:C.timestamp),T.streaming=!1,u(T);let J=oe(C);J&&W.byCall.delete(J)}}}else if(Ue==="agent_media"){let $=Array.isArray(C.media)?C.media:[],T=[];for(let J of $){if(!J||typeof J!="object")continue;let le=J,X=typeof le.type=="string"?le.type:void 0,Me=typeof le.mediaType=="string"?le.mediaType.toLowerCase():"",$e=null,at="";if(X==="media"){let tt=typeof le.data=="string"?le.data:void 0;if(!tt)continue;at=Me.length>0?Me:"application/octet-stream",$e=`data:${at};base64,${tt}`}else if(X==="image-url"){let tt=typeof le.url=="string"?le.url:void 0;if(!tt)continue;at=Me,$e=tt}else if(X==="file-url"){let tt=typeof le.url=="string"?le.url:void 0;if(!tt)continue;at=Me,$e=tt}else continue;if($e)if(X==="image-url"||at.startsWith("image/"))T.push({type:"image",image:$e,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))T.push({type:"audio",audio:$e,mimeType:at});else if(at.startsWith("video/"))T.push({type:"video",video:$e,mimeType:at});else{let tt=at||"application/octet-stream";T.push({type:"file",data:$e,mimeType:tt,filename:uf(tt)})}}if(T.length>0){let J=c(),le=C.toolCallId,Me={id:`agent-media-${typeof le=="string"&&le.length>0?`${le}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:T,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};u(Me);let $e=m;$e&&($e.streaming=!1,u($e)),m=null,x.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,T={id:$,role:"assistant",content:(jr=C.reflection)!=null?jr:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Ls=C.reflection)!=null?Ls:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};u(T)}else if(Ue==="agent_complete"){Ge&&(Ge.status=C.success?"complete":"error",Ge.completedAt=We(C.completedAt),Ge.stopReason=C.stopReason);let $=m;$&&($.streaming=!1,u($)),t({type:"status",status:"idle"})}else if(Ue==="agent_error"){let $=typeof C.error=="string"?C.error:(Ps=(ao=C.error)==null?void 0:ao.message)!=null?Ps:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):t({type:"error",error:new Error($)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let $=(Is=C.approvalId)!=null?Is:`approval-${c()}`,T={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Ws=Ge==null?void 0:Ge.agentId)!=null?Ws:"virtual",executionId:(qn=(Rs=C.executionId)!=null?Rs:Ge==null?void 0:Ge.executionId)!=null?qn:"",toolName:(ts=C.toolName)!=null?ts:"",toolType:C.toolType,description:(Hr=C.description)!=null?Hr:`Execute ${(Rr=C.toolName)!=null?Rr:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};u(T)}else if(Ue==="step_await"&&C.awaitReason==="approval_required"){let $=(Hs=C.approvalId)!=null?Hs:`approval-${c()}`,T={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Ma=Ge==null?void 0:Ge.agentId)!=null?Ma:"virtual",executionId:(Ds=(Bs=C.executionId)!=null?Bs:Ge==null?void 0:Ge.executionId)!=null?Ds:"",toolName:(Lo=C.toolName)!=null?Lo:"",toolType:C.toolType,description:(ka=C.description)!=null?ka:`Execute ${(Ea=C.toolName)!=null?Ea:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};u(T)}else if(Ue==="agent_approval_complete"){let $=C.approvalId;if($){let J={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(La=C.decision)!=null?La:"approved",agentId:(Pa=Ge==null?void 0:Ge.agentId)!=null?Pa:"virtual",executionId:(io=(Ia=C.executionId)!=null?Ia:Ge==null?void 0:Ge.executionId)!=null?io:"",toolName:(lo=C.toolName)!=null?lo:"",description:(Wa=C.description)!=null?Wa:"",resolvedAt:Date.now()}};u(J)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let $=C.artifactType,T=String(C.id),J=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:T,artifactType:$,title:J,component:typeof C.component=="string"?C.component:void 0}),fe.set(T,{markdown:"",title:J}),!ae.has(T)){ae.add(T);let le={id:`artifact-ref-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:T,title:J,artifactType:$,status:"streaming"}})};Q.set(T,le),u(le)}}else if(Ue==="artifact_delta"){let $=String(C.id),T=typeof C.delta=="string"?C.delta:String((Ns=C.delta)!=null?Ns:"");t({type:"artifact_delta",id:$,artDelta:T});let J=fe.get($);J&&(J.markdown+=T)}else if(Ue==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ue==="artifact_complete"){let $=String(C.id);t({type:"artifact_complete",id:$});let T=Q.get($);if(T){T.streaming=!1;try{let J=JSON.parse((co=T.rawContent)!=null?co:"{}");if(J.props){J.props.status="complete";let le=fe.get($);le!=null&&le.markdown&&(J.props.markdown=le.markdown)}T.rawContent=JSON.stringify(J)}catch{}fe.delete($),u(T),Q.delete($)}}}else if(Ue==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let T=String((Ra=$.id)!=null?Ra:`msg-${c()}`),J=$.role,X={id:T,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(u(X),X.rawContent)try{let Me=JSON.parse(X.rawContent),$e=(Fs=Me==null?void 0:Me.props)==null?void 0:Fs.artifactId;typeof $e=="string"&&ae.add($e)}catch{}m=null,x.current=null,ee.delete(T),re.delete(T)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(Ue==="dispatch_error"){let T=(po=C.message)!=null?po:C.error;T!=null&&T!==""&&($=new Error(String(T)))}else if(Ue==="step_error"||Ue==="flow_error"){let T=C.error;typeof T=="string"&&T!==""?$=new Error(T):T!=null&&typeof T=="object"&&"message"in T&&($=new Error(String((Os=T.message)!=null?Os:T)))}else Ue==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){t({type:"error",error:$});let T=m;T&&T.streaming&&(T.streaming=!1,u(T)),t({type:"status",status:"idle"})}}}}}Je.length=0};;){let{done:q,value:G}=await o.read();if(q)break;a+=s.decode(G,{stream:!0});let ye=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=t)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=e(r);return s!==null&&(n=s),t=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Oo=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Au=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Su=()=>{var t;let n=uf();return{processChunk:async e=>{let r=e.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(e)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},Tu=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:e=>{let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(e.length<=t)return n!==null||n===""?{text:n||"",raw:e}:null;try{let o=(0,ms.parse)(e,ms.STR|ms.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?xu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=xu(o.text)))}catch{}return t=e.length,n!==null?{text:n,raw:e}:null},close:()=>{}}};var Eu=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var Xa=class{constructor(t,e=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=e}push(t,e){var s,a,i;let r=(i=(s=e==null?void 0:e.seq)!=null?s:e==null?void 0:e.sequenceIndex)!=null?i:(a=e==null?void 0:e.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,e);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,e),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,e);return}let o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(r,{payloadType:t,payload:e,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((e,r)=>e[0]-r[0]);for(let[e,r]of t)this.buffer.delete(e),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Mu="webmcp:";function ku(n){return n==="execution_start"}var Ja=class{constructor(t){this.kind="agent";this.iteration=1;this.openTurnId=null;this.openStepId=null;this.openTextBlockId=null;this.openReasoningId=null;this.mediaBuffers=new Map;var e;this.executionId=(e=t==null?void 0:t.executionId)!=null?e:""}push(t,e){var r,o,s,a,i,d,c,g,f,u,m,v,x,E,M;switch(typeof e.executionId=="string"&&e.executionId&&(this.executionId=e.executionId),typeof e.iteration=="number"&&(this.iteration=e.iteration),t){case"execution_start":return this.kind=e.kind==="flow"?"flow":"agent",this.kind!=="agent"?[]:[this.out("agent_start",{executionId:this.executionId,agentId:e.agentId,agentName:e.agentName,maxTurns:e.maxTurns,startedAt:e.startedAt})];case"turn_start":return this.openTurnId=typeof e.id=="string"?e.id:null,this.kind!=="agent"?[]:[this.out("agent_turn_start",{turnId:e.id,iteration:e.iteration})];case"turn_complete":{let S=this.kind==="agent"?[this.out("agent_turn_complete",{turnId:e.id,iteration:e.iteration,stopReason:e.stopReason,completedAt:e.completedAt})]:[];return this.openTurnId===e.id&&(this.openTurnId=null),S}case"execution_complete":return((r=e.kind)!=null?r:this.kind)==="agent"?[this.out("agent_complete",{executionId:this.executionId,success:e.success,completedAt:e.completedAt,stopReason:e.stopReason})]:[this.out("flow_complete",{success:e.success,completedAt:e.completedAt,duration:e.durationMs,finalOutput:e.finalOutput,totalSteps:e.totalSteps,successfulSteps:e.successfulSteps,failedSteps:e.failedSteps})];case"execution_error":return((o=e.kind)!=null?o:this.kind)==="agent"?[this.out("agent_error",{recoverable:!1,error:e.error})]:[this.out("flow_error",{error:e.error,code:e.code,upgradeUrl:e.upgradeUrl})];case"error":return[this.out("agent_error",{recoverable:!0,error:e.error})];case"ping":return[this.out("agent_ping",{timestamp:e.timestamp})];case"text_start":return this.openTextBlockId=typeof e.id=="string"?e.id:null,[];case"text_delta":{let S=String((s=e.delta)!=null?s:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"text",delta:S,turnId:(a=this.openTurnId)!=null?a:e.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("step_delta",{id:(i=this.openStepId)!=null?i:e.id,text:S,stepType:"prompt"})]}case"text_complete":return this.openTextBlockId===e.id&&(this.openTextBlockId=null),[];case"reasoning_start":return this.openReasoningId=typeof e.id=="string"?e.id:null,this.kind==="flow"?[this.out("reason_start",{id:e.id})]:[];case"reasoning_delta":{let S=String((d=e.delta)!=null?d:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"thinking",delta:S,turnId:(c=this.openTurnId)!=null?c:e.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("reason_delta",{id:e.id,delta:S})]}case"reasoning_complete":{let S=typeof e.text=="string"&&e.text.length>0;if(this.kind==="agent")return e.scope==="loop"||S?[this.out("agent_reflection",{reflection:(g=e.text)!=null?g:"",executionId:this.executionId,iteration:this.iteration})]:[];let B=[];return S&&B.push(this.out("reason_delta",{id:e.id,delta:e.text})),B.push(this.out("reason_complete",{id:e.id})),B}case"tool_start":return this.kind==="agent"?[this.out("agent_tool_start",{toolCallId:e.toolCallId,toolName:e.toolName,parameters:e.parameters,executionId:this.executionId,iteration:(f=e.iteration)!=null?f:this.iteration,startedAt:e.startedAt})]:[this.out("tool_start",{toolId:e.toolCallId,toolName:e.toolName,parameters:e.parameters,executionId:this.executionId,iteration:(u=e.iteration)!=null?u:this.iteration,startedAt:e.startedAt})];case"tool_input_delta":return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"tool_input",delta:String((m=e.delta)!=null?m:""),toolCallId:e.toolCallId})]:[];case"tool_input_complete":return[];case"tool_output_delta":{let S=String((v=e.delta)!=null?v:"");return this.kind==="agent"?[this.out("agent_tool_delta",{toolCallId:e.toolCallId,delta:S})]:[this.out("tool_delta",{toolId:e.toolCallId,delta:S})]}case"tool_complete":return this.kind==="agent"?[this.out("agent_tool_complete",{toolCallId:e.toolCallId,result:e.result,executionTime:e.executionTime,completedAt:e.completedAt})]:[this.out("tool_complete",{toolId:e.toolCallId,result:e.result,duration:e.executionTime,completedAt:e.completedAt})];case"media_start":{let S=String(e.id);return this.mediaBuffers.set(S,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,role:typeof e.role=="string"?e.role:void 0,toolCallId:e.toolCallId,parts:[]}),[]}case"media_delta":{let S=this.mediaBuffers.get(String(e.id));return S&&typeof e.delta=="string"&&S.parts.push(e.delta),[]}case"media_complete":{let S=String(e.id),B=this.mediaBuffers.get(S);this.mediaBuffers.delete(S);let I=(E=(x=typeof e.mediaType=="string"?e.mediaType:void 0)!=null?x:B==null?void 0:B.mediaType)!=null?E:"application/octet-stream",R=typeof e.data=="string"?e.data:void 0,A=typeof e.url=="string"?e.url:B&&B.parts.length>0?B.parts.join(""):void 0,L=null;return R?L={type:"media",data:R,mediaType:I}:A&&(L={type:I.startsWith("image/")?"image-url":"file-url",url:A,mediaType:I}),L?[this.out("agent_media",{media:[L],executionId:this.executionId,iteration:this.iteration,toolCallId:(M=e.toolCallId)!=null?M:B==null?void 0:B.toolCallId})]:[]}case"approval_start":return[this.out("agent_approval_start",{approvalId:e.approvalId,toolName:e.toolName,toolType:e.toolType,description:e.description,reason:e.reason,parameters:e.parameters,executionId:this.executionId})];case"approval_complete":return[this.out("agent_approval_complete",{approvalId:e.approvalId,decision:e.decision,executionId:this.executionId,toolName:e.toolName,description:e.description})];case"await":{let S=typeof e.toolName=="string"?e.toolName:"",B=e.origin==="webmcp"&&!S.startsWith(Mu)?`${Mu}${S}`:S;return[this.out("step_await",{awaitReason:"local_tool_required",toolName:B,parameters:e.parameters,toolCallId:e.toolCallId,toolId:e.toolId,executionId:this.executionId,awaitedAt:e.awaitedAt})]}case"step_start":return this.openStepId=typeof e.id=="string"?e.id:null,[this.out("step_start",{id:e.id,name:e.name,stepType:e.stepType,index:e.index,totalSteps:e.totalSteps,startedAt:e.startedAt,outputVariable:e.outputVariable})];case"step_complete":{let S=this.out("step_complete",{id:e.id,name:e.name,stepType:e.stepType,success:e.success,duration:e.durationMs,result:e.result,stopReason:e.stopReason,completedAt:e.completedAt,unresolvedVariables:e.unresolvedVariables});return this.openStepId===e.id&&(this.openStepId=null),[S]}case"step_skip":return[];case"artifact_start":return[this.out("artifact_start",{id:e.id,artifactType:e.artifactType,title:e.title,component:e.component})];case"artifact_delta":return[this.out("artifact_delta",{id:e.id,delta:e.delta})];case"artifact_update":return[this.out("artifact_update",{id:e.id,component:e.component,props:e.props})];case"artifact_complete":return[this.out("artifact_complete",{id:e.id})];case"source":case"custom":return[];default:return[]}}out(t,e){let r={};for(let[o,s]of Object.entries(e))s!==void 0&&(r[o]=s);return{payloadType:t,payload:r}}};var Lu="3.37.0";var Ys=Lu;var gf="https://api.runtype.com/v1/dispatch",Ya="https://api.runtype.com";function ff(n){var s,a;let t=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Yi=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function hf(n){switch(n){case"json":return Tu;case"regex-json":return Su;case"xml":return Eu;default:return Au}}var Iu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function bf(n,t){if(!n)return t;let e=n.trim(),r=t.trim();if(e.length===0)return t;if(r.length===0)return n;let o=Iu(e);if(!Iu(r))return n;if(!o||r===e||r.startsWith(e))return t;let a=Oo(n);return Oo(t)!==null&&a===null?t:n}var Zs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var e,r,o,s;this.apiUrl=(e=t.apiUrl)!=null?e:gf,this.headers={"Content-Type":"application/json","X-Persona-Version":Ys,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:hf(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 Ua(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var e;(e=this.webMcpBridge)==null||e.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,e,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,e,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}withEventsParam(t){return this.config.events!=="unified"?t:t+(t.includes("?")?"&":"?")+"events=unified"}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ya}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,e;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(e=(t=this.config).onSessionInit)==null||e.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,e={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ys},body:JSON.stringify(e)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var e;return`${((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ya}/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":Ys},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,e){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:e})}async submitCSATFeedback(t,e){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:e})}async submitNPSFeedback(t,e){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:e})}async dispatch(t,e){return this.isAgentMode()?this.dispatchAgent(t,e):this.isClientTokenMode()?this.dispatchClientToken(t,e):this.dispatchProxy(t,e)}async dispatchClientToken(t,e){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let I=new Error("Session expired. Please refresh to continue.");throw e({type:"error",error:I}),I}let c=await this.buildPayload(t.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,f={sessionId:d.sessionId,messages:t.messages.filter(Yi).map(I=>{var R,A,L;return{id:I.id,role:I.role,content:(L=(A=(R=I.contentParts)!=null?R:I.llmContent)!=null?A:I.rawContent)!=null?L:I.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},u=c.clientTools,m=!!(u&&u.length>0),v=m?ou(u):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&x&&this.lastSentClientToolsFingerprint===v,M=!1,S=null,B;for(let I=0;;I++){let A={...f,...m&&(M||!E)&&u?{clientTools:u}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),B=await fetch(this.withEventsParam(this.getClientApiUrl("chat")),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ys},body:JSON.stringify(A),signal:r.signal}),B.status===409&&I===0&&m){let L=await B.json().catch(()=>null);if((L==null?void 0:L.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}S=L!=null?L:{error:"Chat request failed"}}break}if(!B.ok){let I=S!=null?S:await B.json().catch(()=>({error:"Chat request failed"}));if(B.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw e({type:"error",error:A}),A}if(B.status===429){let A=new Error(I.hint||"Message limit reached for this session.");throw e({type:"error",error:A}),A}let R=new Error(I.error||"Failed to send message");throw e({type:"error",error:R}),R}if(!B.body){let I=new Error("No response body received");throw e({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,e({type:"status",status:"connected"});try{await this.streamResponse(B.body,e,t.assistantMessageId)}finally{e({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&e({type:"error",error:c}),c}}async dispatchProxy(t,e){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.withEventsParam(this.apiUrl),{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw e({type:"error",error:d}),d}else a=await fetch(this.withEventsParam(this.apiUrl),{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw e({type:"error",error:i}),i}e({type:"status",status:"connected"});try{await this.streamResponse(a.body,e)}finally{e({type:"status",status:"idle"})}}async dispatchAgent(t,e){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.withEventsParam(this.apiUrl),{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw e({type:"error",error:d}),d}else a=await fetch(this.withEventsParam(this.apiUrl),{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw e({type:"error",error:i}),i}e({type:"status",status:"connected"});try{await this.streamResponse(a.body,e,t.assistantMessageId)}finally{e({type:"status",status:"idle"})}}async processStream(t,e,r){e({type:"status",status:"connected"});try{await this.streamResponse(t,e,r)}finally{e({type:"status",status:"idle"})}}async resolveApproval(t,e){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ya}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:e,streamResponse:!0})})}async resumeFlow(t,e,r){var c,g;let o=this.isClientTokenMode(),s=this.withEventsParam(o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ya}/resume`),a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:e,streamResponse:(g=r==null?void 0:r.streamResponse)!=null?g:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let e=t.slice().filter(Yi).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:e,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Xi(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var s,a;let r={messages:t.slice().filter(Yi).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Xi(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,e,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=g=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...g!==void 0&&{partId:g}};return r.current=f,o(f),f},c=g=>r.current?r.current:d(g);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let g=c(i.partId);i.partId!==void 0&&!g.partId&&(g.partId=i.partId),g.content+=i.text,o(g)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,e({type:"status",status:"idle"})),i.error&&(a.current=null,e({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,e,r){var wr,Sn,Ke,Ft;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=q=>{let ke=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,Ce=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,_e=q.tools?q.tools.map(it=>({...it,chunks:it.chunks?[...it.chunks]:void 0})):void 0;return{...q,reasoning:ke,toolCall:Ce,tools:_e}},f=q=>{if(q.role!=="assistant"||q.variant)return!0;let ke=Array.isArray(q.contentParts)&&q.contentParts.length>0,Ce=typeof q.rawContent=="string"&&q.rawContent.trim()!=="";return typeof q.content=="string"&&q.content.trim()!==""||ke||Ce||!!q.stopReason},u=q=>{f(q)&&e({type:"message",message:g(q)})},m=null,v=null,x={current:null},E={current:null},M=!1,S=new Map,B=new Map,I=new Map,R=new Map,A={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},N=(q,ke,Ce="")=>`${q}::${ke}::${Ce}`,F=(q,ke)=>`${q}::${ke}::`,k=(q,ke,Ce,_e)=>{let it=N(q,ke,Ce),pt=I.get(it);if(pt)return pt;let ot=Ce?`-${Ce}`:"",Mt={id:`nested-${q}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Ce?{partId:Ce}:{},agentMetadata:{executionId:_e,parentToolId:q,parentStepId:ke}};return I.set(it,Mt),u(Mt),Mt},z=q=>{if(q==null)return null;try{return String(q)}catch{return null}},j=q=>{var ke,Ce,_e,it,pt;return z((pt=(it=(_e=(Ce=(ke=q.stepId)!=null?ke:q.step_id)!=null?Ce:q.step)!=null?_e:q.parentId)!=null?it:q.flowStepId)!=null?pt:q.flow_step_id)},re=q=>{var ke,Ce,_e,it,pt,ot,Mt;return z((Mt=(ot=(pt=(it=(_e=(Ce=(ke=q.callId)!=null?ke:q.call_id)!=null?Ce:q.requestId)!=null?_e:q.request_id)!=null?it:q.toolCallId)!=null?pt:q.tool_call_id)!=null?ot:q.stepId)!=null?Mt:q.step_id)},Ie=r,Ve=!1,ve=()=>{if(m)return m;let q;return!Ve&&Ie?(q=Ie,Ve=!0):Ie&&E.current?q=`${Ie}_${E.current}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:q,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(m),m},Ne=(q,ke)=>{A.lastId=ke,q&&A.byStep.set(q,ke)},qe=(q,ke)=>{var pt;let Ce=(pt=q.reasoningId)!=null?pt:q.id,_e=j(q);if(Ce){let ot=String(Ce);return Ne(_e,ot),ot}if(_e){let ot=A.byStep.get(_e);if(ot)return A.lastId=ot,ot}if(A.lastId&&!ke)return A.lastId;if(!ke)return null;let it=`reason-${c()}`;return Ne(_e,it),it},Te=q=>{let ke=S.get(q);if(ke)return ke;let Ce={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:q,status:"streaming",chunks:[]}};return S.set(q,Ce),u(Ce),Ce},we=(q,ke)=>{L.lastId=ke,q&&L.byCall.set(q,ke)},oe=new Set,X=new Map,se=new Set,fe=new Map,pe=q=>{if(!q)return!1;let ke=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},K=(q,ke)=>{var pt;let Ce=(pt=q.toolId)!=null?pt:q.id,_e=re(q);if(Ce){let ot=String(Ce);return we(_e,ot),ot}if(_e){let ot=L.byCall.get(_e);if(ot)return L.lastId=ot,ot}if(L.lastId&&!ke)return L.lastId;if(!ke)return null;let it=`tool-${c()}`;return we(_e,it),it},ae=q=>{let ke=B.get(q);if(ke)return ke;let Ce={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:q,status:"pending"}};return B.set(q,Ce),u(Ce),Ce},Be=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let ke=Number(q);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let Ce=Date.parse(q);if(!Number.isNaN(Ce))return Ce}return Date.now()},ee=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},Z=new Map,ne=new Map,st=new Map,at=new Map,nt=null,Me=(q,ke,Ce)=>{var Mt;let _e=st.get(q);_e||(_e=[],st.set(q,_e));let it=0,pt=_e.length;for(;it<pt;){let V=it+pt>>>1;_e[V].seq<ke?it=V+1:pt=V}((Mt=_e[it])==null?void 0:Mt.seq)===ke?_e[it]={seq:ke,text:Ce}:_e.splice(it,0,{seq:ke,text:Ce});let ot="";for(let V=0;V<_e.length;V++)ot+=_e[V].text;return ot},he=(q,ke)=>{let Ce=ee(ke),_e=ne.get(q.id),it=bf(_e,Ce);q.rawContent=it;let pt=Z.get(q.id),ot=me=>{var ut;let Ee=(ut=q.content)!=null?ut:"";me.trim()!==""&&(Ee.trim().length===0||me.startsWith(Ee)||me.trimStart().startsWith(Ee.trim()))&&(q.content=me)},Mt=()=>{var me;if(pt){let Ee=(me=pt.close)==null?void 0:me.call(pt);Ee instanceof Promise&&Ee.catch(()=>{})}Z.delete(q.id),ne.delete(q.id),q.streaming=!1,u(q)};if(!pt){ot(Ce),Mt();return}let V=Oo(it);if(V!==null&&V.trim()!==""){ot(V),Mt();return}let St=me=>{var en;let Ee=typeof me=="string"?me:(en=me==null?void 0:me.text)!=null?en:null;if(Ee!==null&&Ee.trim()!=="")return Ee;let ut=pt.getExtractedText();return ut!==null&&ut.trim()!==""?ut:Ce},de;try{de=pt.processChunk(it)}catch{ot(Ce),Mt();return}if(de instanceof Promise){de.then(me=>{ot(St(me)),Mt()}).catch(()=>{ot(Ce),Mt()});return}ot(St(de)),Mt()},Ge=[],J=!1,ue,Le=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,ue()}))},Xe=new Xa((q,ke)=>{Ge.push({payloadType:q,payload:ke}),Le()}),Gt=new Ja,Pe=this.config.events==="unified",Ue=!1,rt=null,Nt=new Map,yn=(wr=this.config.iterationDisplay)!=null?wr:"separate";for(ue=()=>{var q,ke,Ce,_e,it,pt,ot,Mt,V,St,de,me,Ee,ut,en,an,wn,Ot,et,_t,mt,tn,rr,Wn,ln,On,Cr,Ct,jn,Ar,Nr,ur,xt,Co,Sr,Ao,$n,Ko,Yr,Fr,Zr,eo,So,To,to,Tt,Vn,Kn,Rn,kt,or,sr,Gn,no,_r,ro,Qn,$t,Bn,ar,oo,Or,so,Tr,Xn,ye,gt,rn,un,Er,Es,$r,Eo,Mr,O,Go,kr,Lr,qr,Ir,mr,Qo,xa,Jn,Yn,gr,fr,Mo,Ur,Tn,Pr,Xo,ko,Jo,wa,Yo,Ca,Zo,vt,Ms,ir,qn,Aa,Sa,es,zr,ks,ao,Ls,Is,Ps,Ws,Un,ts,Wr,Rr,Rs,Ta,Bs,Hs,Lo,Ea,Ma,ka,La,Ia,io,lo,Pa,Ds,co,Wa,Ns,po,Fs,Ra,jr,Ba;for(let Br=0;Br<Ge.length;Br++){let be=Ge[Br].payloadType,w=Ge[Br].payload;if(be==="reason_start"){let $=(q=qe(w,!0))!=null?q:`reason-${c()}`,P=Te($);P.reasoning=(ke=P.reasoning)!=null?ke:{id:$,status:"streaming",chunks:[]},P.reasoning.startedAt=(_e=P.reasoning.startedAt)!=null?_e:Be((Ce=w.startedAt)!=null?Ce:w.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",u(P)}else if(be==="reason_delta"||be==="reason_chunk"){let $=(pt=(it=qe(w,!1))!=null?it:qe(w,!0))!=null?pt:`reason-${c()}`,P=Te($);P.reasoning=(ot=P.reasoning)!=null?ot:{id:$,status:"streaming",chunks:[]},P.reasoning.startedAt=(V=P.reasoning.startedAt)!=null?V:Be((Mt=w.startedAt)!=null?Mt:w.timestamp);let G=(me=(de=(St=w.reasoningText)!=null?St:w.text)!=null?de:w.delta)!=null?me:"";if(G&&w.hidden!==!0){let ie=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(ie!==void 0){let Q=Me($,ie,String(G));P.reasoning.chunks=[Q]}else P.reasoning.chunks.push(String(G))}if(P.reasoning.status=w.done?"complete":"streaming",w.done){P.reasoning.completedAt=Be((Ee=w.completedAt)!=null?Ee:w.timestamp);let ie=(ut=P.reasoning.startedAt)!=null?ut:Date.now();P.reasoning.durationMs=Math.max(0,((en=P.reasoning.completedAt)!=null?en:Date.now())-ie)}P.streaming=P.reasoning.status!=="complete",u(P)}else if(be==="reason_complete"){let $=(wn=(an=qe(w,!1))!=null?an:qe(w,!0))!=null?wn:`reason-${c()}`,P=S.get($);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=Be((Ot=w.completedAt)!=null?Ot:w.timestamp);let ie=(et=P.reasoning.startedAt)!=null?et:Date.now();P.reasoning.durationMs=Math.max(0,((_t=P.reasoning.completedAt)!=null?_t:Date.now())-ie),P.streaming=!1,u(P)}let G=j(w);G&&A.byStep.delete(G)}else if(be==="tool_start"){let $=(mt=K(w,!0))!=null?mt:`tool-${c()}`,P=(tn=w.toolName)!=null?tn:w.name;if(pe(P)){oe.add($);continue}let G=ae($),ie=(rr=G.toolCall)!=null?rr:{id:$,status:"pending"};ie.name=P!=null?P:ie.name,ie.status="running",w.args!==void 0?ie.args=w.args:w.parameters!==void 0&&(ie.args=w.parameters),ie.startedAt=(ln=ie.startedAt)!=null?ln:Be((Wn=w.startedAt)!=null?Wn:w.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,G.toolCall=ie,G.streaming=!0;let Q=w.agentContext;(Q||w.executionId)&&(G.agentMetadata={executionId:(On=Q==null?void 0:Q.executionId)!=null?On:w.executionId,iteration:(Cr=Q==null?void 0:Q.iteration)!=null?Cr:w.iteration}),u(G)}else if(be==="tool_chunk"||be==="tool_delta"){let $=(jn=(Ct=K(w,!1))!=null?Ct:K(w,!0))!=null?jn:`tool-${c()}`;if(oe.has($))continue;let P=ae($),G=(Ar=P.toolCall)!=null?Ar:{id:$,status:"running"};G.startedAt=(ur=G.startedAt)!=null?ur:Be((Nr=w.startedAt)!=null?Nr:w.timestamp);let ie=(Sr=(Co=(xt=w.text)!=null?xt:w.delta)!=null?Co:w.message)!=null?Sr:"";ie&&(G.chunks=(Ao=G.chunks)!=null?Ao:[],G.chunks.push(String(ie))),G.status="running",P.toolCall=G,P.streaming=!0;let Q=w.agentContext;(Q||w.executionId)&&(P.agentMetadata=(Yr=P.agentMetadata)!=null?Yr:{executionId:($n=Q==null?void 0:Q.executionId)!=null?$n:w.executionId,iteration:(Ko=Q==null?void 0:Q.iteration)!=null?Ko:w.iteration}),u(P)}else if(be==="tool_complete"){let $=(Zr=(Fr=K(w,!1))!=null?Fr:K(w,!0))!=null?Zr:`tool-${c()}`;if(oe.has($)){oe.delete($);continue}let P=ae($),G=(eo=P.toolCall)!=null?eo:{id:$,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Be((So=w.completedAt)!=null?So:w.timestamp);let ie=(To=w.duration)!=null?To:w.executionTime;if(typeof ie=="number")G.durationMs=ie;else{let $e=(to=G.startedAt)!=null?to:Date.now();G.durationMs=Math.max(0,((Tt=G.completedAt)!=null?Tt:Date.now())-$e)}P.toolCall=G,P.streaming=!1;let Q=w.agentContext;(Q||w.executionId)&&(P.agentMetadata=(Rn=P.agentMetadata)!=null?Rn:{executionId:(Vn=Q==null?void 0:Q.executionId)!=null?Vn:w.executionId,iteration:(Kn=Q==null?void 0:Q.iteration)!=null?Kn:w.iteration}),u(P);let Re=re(w);Re&&L.byCall.delete(Re)}else if(be==="step_await"&&w.awaitReason==="local_tool_required"&&w.toolName){let $=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,P=(kt=$!=null?$:w.toolId)!=null?kt:`local-${c()}`,G=ae(P),ie=w.toolName,Q=Vs(ie),Re=(or=G.toolCall)!=null?or:{id:P,status:"pending"};Re.name=ie,Re.args=w.parameters,Re.status=Q?"running":"complete",Re.chunks=(sr=Re.chunks)!=null?sr:[],Re.startedAt=(no=Re.startedAt)!=null?no:Be((Gn=w.startedAt)!=null?Gn:w.timestamp),Q?(Re.completedAt=void 0,Re.duration=void 0,Re.durationMs=void 0):Re.completedAt=(_r=Re.completedAt)!=null?_r:Re.startedAt,G.toolCall=Re,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Qn=w.executionId)!=null?Qn:(ro=G.agentMetadata)==null?void 0:ro.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(G)}else if(be==="text_start"){if(($t=w.toolContext)!=null&&$t.toolId)continue;let $=w.partId;if($!==void 0&&E.current!==null&&$!==E.current){let P=m;P&&(P.streaming=!1,u(P),nt=P,m=null,M=!0)}$!==void 0&&(E.current=$)}else if(be==="text_end"){if((Bn=w.toolContext)!=null&&Bn.toolId)continue;let $=m;$&&($.streaming=!1,u($),nt=$,m=null,M=!0)}else if(be==="step_chunk"||be==="step_delta"){let $=w.stepType,P=w.executionType;if($==="tool"||P==="context")continue;let G=w.toolContext;if(G!=null&&G.toolId){let $e=String((oo=(ar=w.id)!=null?ar:G.stepId)!=null?oo:`step-${c()}`),lt=w.partId!==void 0&&w.partId!==null?String(w.partId):"",Ye=`${G.toolId}::${$e}`,Pt=R.get(Ye);if(lt!==""&&Pt!==void 0&&Pt!==""&&Pt!==lt){let Wt=I.get(N(G.toolId,$e,Pt));Wt&&Wt.streaming!==!1&&(Wt.streaming=!1,u(Wt))}lt!==""&&R.set(Ye,lt);let qt=k(G.toolId,$e,lt,G.executionId),vn=(Xn=(Tr=(so=(Or=w.text)!=null?Or:w.delta)!=null?so:w.content)!=null?Tr:w.chunk)!=null?Xn:"";vn&&(qt.content+=String(vn),qt.streaming=!0,u(qt)),w.isComplete&&(qt.streaming=!1,u(qt));continue}let ie=w.partId;if(ie!==void 0&&E.current!==null&&ie!==E.current){let $e=m;$e&&($e.streaming=!1,u($e),nt=$e,m=null,M=!0)}ie!==void 0&&(E.current=ie);let Q=ie!==void 0&&(ye=at.get(ie))!=null?ye:ve();ie!==void 0&&(Q.partId||(Q.partId=ie),at.set(ie,Q));let Re=(Er=(un=(rn=(gt=w.text)!=null?gt:w.delta)!=null?rn:w.content)!=null?un:w.chunk)!=null?Er:"";if(Re){let $e=typeof w.seq=="number"?w.seq:void 0,lt=ie!=null?ie:Q.id,Ye=$e!==void 0?Me(lt,$e,String(Re)):((Es=ne.get(Q.id))!=null?Es:"")+Re;Q.rawContent=Ye,Z.has(Q.id)||Z.set(Q.id,this.createStreamParser());let Pt=Z.get(Q.id),qt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(qt&&ne.set(Q.id,Ye),Pt.__isPlainTextParser===!0){Q.content=$e!==void 0?Ye:Q.content+Re,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q);continue}let Wt=Pt.processChunk(Ye);if(Wt instanceof Promise)Wt.then(Ht=>{var En;let mn=typeof Ht=="string"?Ht:(En=Ht==null?void 0:Ht.text)!=null?En:null;if(mn!==null&&mn.trim()!=="")Q.content=mn,u(Q);else if(!qt&&!Ye.trim().startsWith("<")){let Cn=m,Dt=Cn&&Cn.id===Q.id?Cn:Q;Dt.id===Q.id&&(Dt.content=$e!==void 0?Ye:Dt.content+Re,ne.delete(Dt.id),Z.delete(Dt.id),Dt.rawContent=void 0,u(Dt))}}).catch(()=>{Q.content=$e!==void 0?Ye:Q.content+Re,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q)});else{let Ht=typeof Wt=="string"?Wt:($r=Wt==null?void 0:Wt.text)!=null?$r:null;Ht!==null&&Ht.trim()!==""?(Q.content=Ht,u(Q)):!qt&&!Ye.trim().startsWith("<")&&(Q.content=$e!==void 0?Ye:Q.content+Re,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q))}}if(w.isComplete){let $e=(Mr=(Eo=w.result)==null?void 0:Eo.response)!=null?Mr:Q.content;if($e){let lt=ne.get(Q.id),Ye=lt!=null?lt:ee($e);Q.rawContent=Ye;let Pt=Z.get(Q.id),qt=null,vn=!1;if(Pt&&(qt=Pt.getExtractedText(),qt===null&&(qt=Oo(Ye)),qt===null)){let Wt=Pt.processChunk(Ye);Wt instanceof Promise?(vn=!0,Wt.then(Ht=>{var En;let mn=typeof Ht=="string"?Ht:(En=Ht==null?void 0:Ht.text)!=null?En:null;if(mn!==null){let Cn=m;Cn&&Cn.id===Q.id&&(Cn.content=mn,Cn.streaming=!1,Z.delete(Cn.id),ne.delete(Cn.id),u(Cn))}})):qt=typeof Wt=="string"?Wt:(O=Wt==null?void 0:Wt.text)!=null?O:null}if(!vn){qt!==null&&qt.trim()!==""?Q.content=qt:ne.has(Q.id)||(Q.content=ee($e));let Wt=Z.get(Q.id);if(Wt){let Ht=(Go=Wt.close)==null?void 0:Go.call(Wt);Ht instanceof Promise&&Ht.catch(()=>{}),Z.delete(Q.id)}ne.delete(Q.id),Q.streaming=!1,u(Q)}}}}else if(be==="step_complete"){let $=w.stepType,P=w.executionType;if($==="tool"||P==="context")continue;let G=w.toolContext;if(G!=null&&G.toolId){let $e=String((Lr=(kr=w.id)!=null?kr:G.stepId)!=null?Lr:"");if($e){let lt=F(G.toolId,$e);for(let[Ye,Pt]of I)Ye.startsWith(lt)&&Pt.streaming!==!1&&(Pt.streaming=!1,u(Pt));R.delete(`${G.toolId}::${$e}`)}continue}let ie=w.stopReason;if(M){if(m!==null){let Ye=m;ie&&(Ye.stopReason=ie),Z.delete(Ye.id),ne.delete(Ye.id),Ye.streaming!==!1&&(Ye.streaming=!1,u(Ye))}let $e=(qr=w.result)==null?void 0:qr.response,lt=nt;lt&&(ie&&(lt.stopReason=ie),$e!=null?he(lt,$e):(Z.delete(lt.id),ne.delete(lt.id))),nt=null;continue}let Q=(Ir=w.result)==null?void 0:Ir.response,Re=ve();if(ie&&(Re.stopReason=ie),Q!=null){let $e=Z.get(Re.id),lt=!1,Ye=!1;if($e){let Pt=$e.getExtractedText(),qt=ne.get(Re.id),vn=qt!=null?qt:ee(Q);if(Re.rawContent=vn,Pt!==null&&Pt.trim()!=="")Re.content=Pt,lt=!0;else{let Wt=Oo(vn);if(Wt!==null)Re.content=Wt,lt=!0;else{let Ht=$e.processChunk(vn);if(Ht instanceof Promise)Ye=!0,Ht.then(mn=>{var Cn;let En=typeof mn=="string"?mn:(Cn=mn==null?void 0:mn.text)!=null?Cn:null;if(En!==null&&En.trim()!==""){let Dt=m;Dt&&Dt.id===Re.id&&(Dt.content=En,Dt.streaming=!1,Z.delete(Dt.id),ne.delete(Dt.id),u(Dt))}else{let Dt=$e.getExtractedText(),cn=m;cn&&cn.id===Re.id&&(Dt!==null&&Dt.trim()!==""?cn.content=Dt:ne.has(cn.id)||(cn.content=ee(Q)),cn.streaming=!1,Z.delete(cn.id),ne.delete(cn.id),u(cn))}});else{let mn=typeof Ht=="string"?Ht:(mr=Ht==null?void 0:Ht.text)!=null?mr:null;if(mn!==null&&mn.trim()!=="")Re.content=mn,lt=!0;else{let En=$e.getExtractedText();En!==null&&En.trim()!==""&&(Re.content=En,lt=!0)}}}}}if(!Ye){if(!Re.rawContent){let Pt=ne.get(Re.id);Re.rawContent=Pt!=null?Pt:ee(Q)}if(!lt&&!ne.has(Re.id)&&(Re.content=ee(Q)),$e){let Pt=(Qo=$e.close)==null?void 0:Qo.call($e);Pt instanceof Promise&&Pt.catch(()=>{})}Z.delete(Re.id),ne.delete(Re.id),Re.streaming=!1,u(Re)}}else Z.delete(Re.id),ne.delete(Re.id),Re.streaming=!1,u(Re)}else if(be==="flow_complete"){let $=(xa=w.result)==null?void 0:xa.response;if(M){if(m!==null){let P=m;Z.delete(P.id),ne.delete(P.id),P.streaming!==!1&&(P.streaming=!1,u(P))}}else if($!=null){let P=ve(),G=ne.get(P.id),ie=G!=null?G:ee($);P.rawContent=ie;let Q=ee($),Re=Z.get(P.id);if(Re){let Ye=Oo(ie);if(Ye!==null)Q=Ye;else{let Pt=Re.processChunk(ie);Pt instanceof Promise&&Pt.then(vn=>{var Ht;let Wt=typeof vn=="string"?vn:(Ht=vn==null?void 0:vn.text)!=null?Ht:null;Wt!==null&&(P.content=Wt,P.streaming=!1,u(P))});let qt=Re.getExtractedText();qt!==null&&(Q=qt)}}Z.delete(P.id),ne.delete(P.id);let $e=Q!==P.content,lt=P.streaming!==!1;$e&&(P.content=Q),P.streaming=!1,($e||lt)&&u(P)}else if(m!==null){let P=m;Z.delete(P.id),ne.delete(P.id),P.streaming!==!1&&(P.streaming=!1,u(P))}e({type:"status",status:"idle"})}else if(be==="agent_start")rt={executionId:w.executionId,agentId:(Jn=w.agentId)!=null?Jn:"virtual",agentName:(Yn=w.agentName)!=null?Yn:"",status:"running",currentIteration:0,maxTurns:(gr=w.maxTurns)!=null?gr:1,startedAt:Be(w.startedAt)};else if(be==="agent_iteration_start"){if(rt&&(rt.currentIteration=w.iteration),yn==="separate"&&w.iteration>1){let $=m;$&&($.streaming=!1,u($),Nt.set(w.iteration-1,$),m=null)}}else if(be==="agent_turn_start")v=null;else if(be==="agent_turn_delta"){if(w.contentType==="text"){let $=ve();$.content+=(fr=w.delta)!=null?fr:"",$.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId,agentName:rt==null?void 0:rt.agentName},v=$,u($)}else if(w.contentType==="thinking"){let $=(Mo=w.turnId)!=null?Mo:`agent-think-${w.iteration}`,P=Te($);P.reasoning=(Ur=P.reasoning)!=null?Ur:{id:$,status:"streaming",chunks:[]},P.reasoning.chunks.push((Tn=w.delta)!=null?Tn:""),P.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId},u(P)}else if(w.contentType==="tool_input"){let $=(Pr=w.toolCallId)!=null?Pr:L.lastId;if($){let P=B.get($);P!=null&&P.toolCall&&(P.toolCall.chunks=(Xo=P.toolCall.chunks)!=null?Xo:[],P.toolCall.chunks.push((ko=w.delta)!=null?ko:""),u(P))}}}else if(be==="agent_turn_complete"){let $=w.turnId;if($){let ie=S.get($);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Be(w.completedAt);let Q=(Jo=ie.reasoning.startedAt)!=null?Jo:Date.now();ie.reasoning.durationMs=Math.max(0,((wa=ie.reasoning.completedAt)!=null?wa:Date.now())-Q),ie.streaming=!1,u(ie)}}let P=w.stopReason,G=m!=null?m:v;if(P&&G!==null){let ie=w.turnId;(!ie||((Yo=G.agentMetadata)==null?void 0:Yo.turnId)===ie)&&(G.stopReason=P,u(G))}}else if(be==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let $=(Ca=w.toolCallId)!=null?Ca:`agent-tool-${c()}`;we(re(w),$);let P=ae($),G=(Zo=P.toolCall)!=null?Zo:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};G.name=(Ms=(vt=w.toolName)!=null?vt:w.name)!=null?Ms:G.name,G.status="running",w.parameters!==void 0&&(G.args=w.parameters),G.startedAt=Be((ir=w.startedAt)!=null?ir:w.timestamp),P.toolCall=G,P.streaming=!0,P.agentMetadata={executionId:w.executionId,iteration:w.iteration},u(P)}else if(be==="agent_tool_delta"){let $=(qn=w.toolCallId)!=null?qn:L.lastId;if($){let P=(Aa=B.get($))!=null?Aa:ae($);P.toolCall&&(P.toolCall.chunks=(Sa=P.toolCall.chunks)!=null?Sa:[],P.toolCall.chunks.push((es=w.delta)!=null?es:""),P.toolCall.status="running",P.streaming=!0,u(P))}}else if(be==="agent_tool_complete"){let $=(zr=w.toolCallId)!=null?zr:L.lastId;if($){let P=(ks=B.get($))!=null?ks:ae($);if(P.toolCall){P.toolCall.status="complete",w.result!==void 0&&(P.toolCall.result=w.result),typeof w.executionTime=="number"&&(P.toolCall.durationMs=w.executionTime),P.toolCall.completedAt=Be((ao=w.completedAt)!=null?ao:w.timestamp),P.streaming=!1,u(P);let G=re(w);G&&L.byCall.delete(G)}}}else if(be==="agent_media"){let $=Array.isArray(w.media)?w.media:[],P=[];for(let G of $){if(!G||typeof G!="object")continue;let ie=G,Q=typeof ie.type=="string"?ie.type:void 0,Re=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",$e=null,lt="";if(Q==="media"){let Ye=typeof ie.data=="string"?ie.data:void 0;if(!Ye)continue;lt=Re.length>0?Re:"application/octet-stream",$e=`data:${lt};base64,${Ye}`}else if(Q==="image-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;lt=Re,$e=Ye}else if(Q==="file-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;lt=Re,$e=Ye}else continue;if($e)if(Q==="image-url"||lt.startsWith("image/"))P.push({type:"image",image:$e,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))P.push({type:"audio",audio:$e,mimeType:lt});else if(lt.startsWith("video/"))P.push({type:"video",video:$e,mimeType:lt});else{let Ye=lt||"application/octet-stream";P.push({type:"file",data:$e,mimeType:Ye,filename:ff(Ye)})}}if(P.length>0){let G=c(),ie=w.toolCallId,Re={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${G}`:String(G)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:G,agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(Re);let $e=m;$e&&($e.streaming=!1,u($e)),m=null,x.current=null}}else if(be!=="agent_iteration_complete"){if(be==="agent_reflection"||be==="agent_reflect"){let $=`agent-reflection-${w.executionId}-${w.iteration}`,P={id:$,role:"assistant",content:(Ls=w.reflection)!=null?Ls:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Is=w.reflection)!=null?Is:""]},agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(P)}else if(be==="agent_complete"){rt&&(rt.status=w.success?"complete":"error",rt.completedAt=Be(w.completedAt),rt.stopReason=w.stopReason);let $=m;$&&($.streaming=!1,u($)),e({type:"status",status:"idle"})}else if(be==="agent_error"){let $=typeof w.error=="string"?w.error:(Ws=(Ps=w.error)==null?void 0:Ps.message)!=null?Ws:"Agent execution error";w.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):e({type:"error",error:new Error($)})}else if(be!=="agent_ping"){if(be==="agent_approval_start"){let $=(Un=w.approvalId)!=null?Un:`approval-${c()}`,P={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(ts=rt==null?void 0:rt.agentId)!=null?ts:"virtual",executionId:(Rr=(Wr=w.executionId)!=null?Wr:rt==null?void 0:rt.executionId)!=null?Rr:"",toolName:(Rs=w.toolName)!=null?Rs:"",toolType:w.toolType,description:(Bs=w.description)!=null?Bs:`Execute ${(Ta=w.toolName)!=null?Ta:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(P)}else if(be==="step_await"&&w.awaitReason==="approval_required"){let $=(Hs=w.approvalId)!=null?Hs:`approval-${c()}`,P={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Lo=rt==null?void 0:rt.agentId)!=null?Lo:"virtual",executionId:(Ma=(Ea=w.executionId)!=null?Ea:rt==null?void 0:rt.executionId)!=null?Ma:"",toolName:(ka=w.toolName)!=null?ka:"",toolType:w.toolType,description:(Ia=w.description)!=null?Ia:`Execute ${(La=w.toolName)!=null?La:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(P)}else if(be==="agent_approval_complete"){let $=w.approvalId;if($){let G={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(io=w.decision)!=null?io:"approved",agentId:(lo=rt==null?void 0:rt.agentId)!=null?lo:"virtual",executionId:(Ds=(Pa=w.executionId)!=null?Pa:rt==null?void 0:rt.executionId)!=null?Ds:"",toolName:(co=w.toolName)!=null?co:"",description:(Wa=w.description)!=null?Wa:"",resolvedAt:Date.now()}};u(G)}}else if(be==="artifact_start"||be==="artifact_delta"||be==="artifact_update"||be==="artifact_complete"){if(be==="artifact_start"){let $=w.artifactType,P=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(e({type:"artifact_start",id:P,artifactType:$,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(P,{markdown:"",title:G}),!se.has(P)){se.add(P);let ie={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:G,artifactType:$,status:"streaming"}})};X.set(P,ie),u(ie)}}else if(be==="artifact_delta"){let $=String(w.id),P=typeof w.delta=="string"?w.delta:String((Ns=w.delta)!=null?Ns:"");e({type:"artifact_delta",id:$,artDelta:P});let G=fe.get($);G&&(G.markdown+=P)}else if(be==="artifact_update"){let $=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};e({type:"artifact_update",id:String(w.id),props:$,component:typeof w.component=="string"?w.component:void 0})}else if(be==="artifact_complete"){let $=String(w.id);e({type:"artifact_complete",id:$});let P=X.get($);if(P){P.streaming=!1;try{let G=JSON.parse((po=P.rawContent)!=null?po:"{}");if(G.props){G.props.status="complete";let ie=fe.get($);ie!=null&&ie.markdown&&(G.props.markdown=ie.markdown)}P.rawContent=JSON.stringify(G)}catch{}fe.delete($),u(P),X.delete($)}}}else if(be==="transcript_insert"){let $=w.message;if(!$||typeof $!="object")continue;let P=String((Fs=$.id)!=null?Fs:`msg-${c()}`),G=$.role,Q={id:P,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(u(Q),Q.rawContent)try{let Re=JSON.parse(Q.rawContent),$e=(Ra=Re==null?void 0:Re.props)==null?void 0:Ra.artifactId;typeof $e=="string"&&se.add($e)}catch{}m=null,x.current=null,Z.delete(P),ne.delete(P)}else if(be==="error"||be==="step_error"||be==="dispatch_error"||be==="flow_error"){let $=null;if(w.error instanceof Error)$=w.error;else if(be==="dispatch_error"){let P=(jr=w.message)!=null?jr:w.error;P!=null&&P!==""&&($=new Error(String(P)))}else if(be==="step_error"||be==="flow_error"){let P=w.error;typeof P=="string"&&P!==""?$=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&($=new Error(String((Ba=P.message)!=null?Ba:P)))}else be==="error"&&w.error!=null&&w.error!==""&&($=new Error(String(w.error)));if($){e({type:"error",error:$});let P=m;P&&P.streaming&&(P.streaming=!1,u(P)),e({type:"status",status:"idle"})}}}}}Ge.length=0};;){let{done:q,value:ke}=await o.read();if(q)break;a+=s.decode(ke,{stream:!0});let Ce=a.split(`
10
10
 
11
- `);a=(Rt=ye.pop())!=null?Rt:"";for(let Qe of ye){let et=Qe.split(`
12
- `),qe="message",_e="";for(let Jt of et)Jt.startsWith("event:")?qe=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(_e+=Jt.replace("data:","").trim());if(!_e)continue;let Pt;try{Pt=JSON.parse(_e)}catch(Jt){t({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let Kt=qe!=="message"?qe:(pn=Pt.type)!=null?pn:"message";if((Cr=this.onSSEEvent)==null||Cr.call(this,Kt,Pt),this.parseSSEEvent){x.current=m;let Jt=await this.handleCustomSSEEvent(Pt,t,x,u,c,E);if(x.current&&x.current!==m&&(m=x.current),Jt)continue}Ye.push(Kt,Pt),me()}}Ye.flushPending(),me(),Ye.destroy()}};function Ja(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function ta(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ya="[Image]";function Ji(n){return{type:"text",text:n}}var ku=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ff=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qr=[...ku,...ff];function hf(n){return ku.includes(n)||n.startsWith("image/")}function Za(n){return hf(n.type)}async function Lu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Za(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function Pu(n,e=Qr,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function yf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function Iu(n,e){let t=yf(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||t||"FILE"}Yi();var Wu=16e3,bf=24e3,vf=4096,xf=1380533830;function wf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===xf?new Uint8Array(n,44):new Uint8Array(n)}function Cf(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var na=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Wu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let g=window.AudioContext||window.webkitAudioContext,f=new g({sampleRate:Wu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new hs(bf);if(o!==this.callGeneration){u.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Cf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(m,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let E=x.code?` (code ${x.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(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(vf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let g=0;g<d.length;g++){let f=Math.max(-1,Math.min(1,d[g]));c[g]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=wf(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var $o=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ys(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new na(n.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function Ru(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ys({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ys({type:"runtype",runtype:n.runtype});if($o.isSupported())return ys({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Zi(n){try{return Ru(n),!0}catch{return!1}}function ei(n){var t;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var bs=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ei(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,g;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(g=t.onError)==null||g.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var ra=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(t,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function el(n){if(!n)return"";let e=Af(n);return Hu(e!==null?e:n)}function Af(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Hu(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
13
- `),e=e.replace(/\n{2,}/g,`
14
- `),e.trim()}var Ou=null;var tl=()=>Ou?Ou():Promise.resolve().then(()=>(Fu(),Nu));var Mf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Ef(n,e){return Mf.some(t=>n[t]!==e[t])}function _u(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${r}
11
+ `);a=(Sn=Ce.pop())!=null?Sn:"";for(let _e of Ce){let it=_e.split(`
12
+ `),pt="message",ot="";for(let St of it)St.startsWith("event:")?pt=St.replace("event:","").trim():St.startsWith("data:")&&(ot+=St.replace("data:","").trim());if(!ot)continue;let Mt;try{Mt=JSON.parse(ot)}catch(St){e({type:"error",error:St instanceof Error?St:new Error("Failed to parse chat stream payload")});continue}let V=pt!=="message"?pt:(Ke=Mt.type)!=null?Ke:"message";if((Ft=this.onSSEEvent)==null||Ft.call(this,V,Mt),this.parseSSEEvent){x.current=m;let St=await this.handleCustomSSEEvent(Mt,e,x,u,c,E);if(x.current&&x.current!==m&&(m=x.current),St)continue}if(Ue||(ku(V)?(Pe=!0,Ue=!0):(V==="agent_start"||V==="flow_start"||V==="step_start")&&(Pe=!1,Ue=!0)),Pe){for(let St of Gt.push(V,Mt))Ge.push(St);ue();continue}Xe.push(V,Mt),ue()}}Xe.flushPending(),ue(),Xe.destroy()}};function Za(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function ea(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var ei="[Image]";function Zi(n){return{type:"text",text:n}}var Pu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yf=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qr=[...Pu,...yf];function vf(n){return Pu.includes(n)||n.startsWith("image/")}function ti(n){return vf(n.type)}async function Wu(n){return new Promise((t,e)=>{let r=new FileReader;r.onload=()=>{let o=r.result;ti(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>e(new Error("Failed to read file")),r.readAsDataURL(n)})}function Ru(n,t=Qr,e=10*1024*1024){return t.includes(n.type)?n.size>e?{valid:!1,error:`File too large. Maximum size: ${Math.round(e/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function xf(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function Bu(n,t){let e=xf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||e||"FILE"}el();var Hu=16e3,wf=24e3,Cf=4096,Af=1380533830;function Sf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===Af?new Uint8Array(n,44):new Uint8Array(n)}function Tf(n){var r;let t=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ta=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,e=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!e)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Hu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let g=window.AudioContext||window.webkitAudioContext,f=new g({sampleRate:Hu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new fs(wf);if(o!==this.callGeneration){u.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Tf(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(m,["runtype.bearer",e]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let E=x.code?` (code ${x.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,e,r,o){let s=t.createMediaStreamSource(e);this.sourceNode=s;let a=t.createScriptProcessor(Cf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let g=0;g<d.length;g++){let f=Math.max(-1,Math.min(1,d[g]));c[g]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,e){var o,s;if(e!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,e);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,e){if(e!==this.callGeneration||!this.playback)return;let r=Sf(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(e=>e(t))}emitError(t){this.errorCallbacks.forEach(e=>e(t))}emitTranscript(t,e,r){this.transcriptCallbacks.forEach(o=>o(t,e,r))}emitMetrics(t){this.metricsCallbacks.forEach(e=>e(t))}};var $o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,e;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((e=this.config)==null?void 0:e.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function hs(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new ta(n.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(n.browser||{});case"custom":{let t=n.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let e=typeof t=="function"?t():t;if(!e||typeof e.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return e}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function Du(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return hs({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return hs({type:"runtype",runtype:n.runtype});if($o.isSupported())return hs({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function tl(n){try{return Du(n),!0}catch{return!1}}function ni(n){var e;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=n.find(s=>s.name===r);if(o)return o}return(e=n.find(r=>r.lang.startsWith("en")))!=null?e:n[0]}var bs=class n{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,e){var a;if(!n.isSupported()){(a=e.onError)==null||a.call(e,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ni(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=e.onEnd)==null?void 0:i.call(e)},o.onerror=i=>{var c,g;let d=i.error;d==="canceled"||d==="interrupted"?(c=e.onEnd)==null||c.call(e):(g=e.onError)==null||g.call(e,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=e.onStart)==null||i.call(e)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var na=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,e;return(e=(t=this.engine)==null?void 0:t.supportsPause)!=null?e:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,e){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,e)}async play(t,e){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(e,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,e;this.stop(),(e=(t=this.engine)==null?void 0:t.destroy)==null||e.call(t),this.engine=null,this.listeners.clear()}set(t,e){this.activeId=e==="idle"?null:t,this.state=e;for(let r of this.listeners)r(this.activeId,this.state)}};function nl(n){if(!n)return"";let t=Ef(n);return Nu(t!==null?t:n)}function Ef(n){let t=n.trim(),e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(e&&(t=e[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Nu(n){if(!n)return"";let t=n;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
+ `),t=t.replace(/\n{2,}/g,`
14
+ `),t.trim()}var qu=null;var rl=()=>qu?qu():Promise.resolve().then(()=>($u(),Ou));var Lf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function If(n,t){return Lf.some(e=>n[e]!==t[e])}function Uu(n,t){let e=n instanceof Error?n:new Error(String(n));if(typeof t=="string")return t;if(typeof t=="function")return t(e);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return e.message?`${r}
15
15
 
16
- _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]}),$u=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,qu=n=>Ks(n)||n===Gr,ri=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ra(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,g,f;if(e.type==="message"){this.upsertMessage(e.message);let u=e.message.toolCall,m=!!(u!=null&&u.name)&&(Ks(u.name)||u.name===Gr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(g=this.callbacks).onError)==null||f.call(g,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ea(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!t||!r||!this.config.clientToken||tl().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Zi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=bs.isSupported()?new bs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,g=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&g)return tl().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:m})=>{let v=new u({host:d,agentId:c,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&t?new m(v,t,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ys(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let g=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=g.id}if(c){this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let g=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=g.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,g,f;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=e.browser)==null?void 0:g.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Ef(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new ea(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g,rawContent:f}=e,m={id:a!=null?a:t==="user"?Ja():t==="assistant"?ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:f=!1,voiceProcessing:u,rawContent:m}=r,x={id:d!=null?d:o==="user"?Ja():o==="assistant"?ta():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,g,f,u,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Ja(),s=ta(),a={id:o,role:"user",content:r||Ya,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=_u(v,this.config.errorMessage);if(E){let k={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(k)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(g=this.callbacks).onError)==null||f.call(g,v):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=ta();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let f=_u(c,this.config.errorMessage);if(f){let u={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var g,f,u,m,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(g=a==null?void 0:a.createdAt)!=null?g:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(c?x=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),x){let E=null;if(x instanceof Response){if(!x.ok){let k=await x.json().catch(()=>null);throw new Error((u=k==null?void 0:k.error)!=null?u:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var g,f,u,m,v,x,E,k,L,F,I,R;let r=this.messages.find(A=>A.id===e.id);if(((g=r==null?void 0:r.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(u=e.toolCall)==null?void 0:u.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let A=(x=e.toolCall)==null?void 0:x.args,W=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(W.length===1){let D=typeof((E=W[0])==null?void 0:E.question)=="string"?W[0].question:"";D&&(a={[D]:t})}}this.markAskUserQuestionResolved(e,a),(k=this.abortController)==null||k.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(L=e.toolCall)==null?void 0:L.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof t=="string"?t:Object.entries(t).map(([W,D])=>`${W}: ${Array.isArray(D)?D.join(", "):D}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((W,D)=>{let N=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!N)return;let M=A[N],z=Array.isArray(M)?M.join(", "):typeof M=="string"?M:"";this.appendMessage({id:`ask-user-q-${i}-${D}`,role:"assistant",content:N,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${D}`,role:"user",content:z||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:t});if(!A.ok){let W=await A.json().catch(()=>null);throw new Error((F=W==null?void 0:W.error)!=null?F:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let W=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(R=(I=this.callbacks).onError)==null||R.call(I,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==Gr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,g,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async u=>{var R,A,W,D,N,M,z;let m=(R=u.toolCall)==null?void 0:R.name,v=(A=u.toolCall)==null?void 0:A.id;if(!m||!v)return null;let x=`${e}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(u),k=(D=(W=u.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?D:m;if(m===Gr)return{dedupeKey:x,resumeKey:k,output:Vi(),toolMessage:u,startedAt:E,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let F=this.client.executeWebMcpToolCall(m,(N=u.toolCall)==null?void 0:N.args,L.signal),I;if(!F)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await F}catch(j){let oe=j instanceof Error&&(j.name==="AbortError"||j.message.includes("aborted")||j.message.includes("abort"));return oe||(z=(M=this.callbacks).onError)==null||z.call(M,j instanceof Error?j:new Error(String(j))),this.markWebMcpToolComplete(u,oa(oe?"Aborted by cancel()":$u(j)),E),this.webMcpInflightKeys.delete(x),null}return L.signal.aborted?(this.markWebMcpToolComplete(u,oa("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:k,output:I,toolMessage:u,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let u={};for(let v of i)u[v.resumeKey]=v.output;let m=await this.client.resumeFlow(e,u,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===Gr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(g=this.callbacks).onError)==null||f.call(g,u instanceof Error?u:new Error(String(u)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,oa("Aborted by cancel()"),v.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,x,E,k,L,F,I,R,A,W,D,N;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(x=e.toolCall)==null?void 0:x.name,o=(E=e.toolCall)==null?void 0:E.id;if(!t){(L=(k=this.callbacks).onError)==null||L.call(k,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let M=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(M)||this.webMcpResolvedKeys.has(M))return;this.webMcpInflightKeys.add(M);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(M)}catch(z){(I=(F=this.callbacks).onError)==null||I.call(F,z instanceof Error?z:new Error(String(z)))}finally{this.webMcpInflightKeys.delete(M)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Gr,g=(R=e.toolCall)==null?void 0:R.args,f=c?null:this.client.executeWebMcpToolCall(r,g,d),u="execute",m=a;try{let M;if(c?M=Vi():f?M=await f:M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,oa("Aborted by cancel()"),a);return}let z=(W=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?W:r;u="resume",await this.resumeWithToolOutput(t,z,M,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,M,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(M){let z=M instanceof Error&&(M.name==="AbortError"||M.message.includes("aborted")||M.message.includes("abort"));(u==="execute"||z||d.aborted)&&this.markWebMcpToolComplete(e,oa(z||d.aborted?"Aborted by cancel()":$u(M)),a),z||(N=(D=this.callbacks).onError)==null||N.call(D,M instanceof Error?M:new Error(String(M)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=el(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ei(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=el(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var g,f,u,m,v,x,E,k,L,F,I,R,A,W,D;if(s!==r)return o;let a={...o,...t};if(((g=o.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(u=a.agentMetadata)!=null?u:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let N=o.approval,M=t.approval;a.approval={...N,...M,executionId:M.executionId||N.executionId,toolName:M.toolName||N.toolName,description:M.description||N.description,toolType:(m=M.toolType)!=null?m:N.toolType,reason:(v=M.reason)!=null?v:N.reason,parameters:(x=M.parameters)!=null?x:N.parameters}}let i=(E=t.toolCall)==null?void 0:E.name,d=(k=t.agentMetadata)==null?void 0:k.executionId,c=(L=t.toolCall)==null?void 0:L.id;if(i&&qu(i)&&d&&c&&((F=t.agentMetadata)==null?void 0:F.awaitingLocalTool)===!0){let N=`${d}:${c}`,M=this.webMcpInflightKeys.has(N),z=this.webMcpResolvedKeys.has(N),j=(I=o.toolCall)==null?void 0:I.name,oe=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&j!==void 0&&qu(j)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(M||z||oe)&&(a.agentMetadata={...(D=a.agentMetadata)!=null?D:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var w=require("lucide"),kf={activity:w.Activity,"arrow-down":w.ArrowDown,"arrow-up":w.ArrowUp,"arrow-up-right":w.ArrowUpRight,bot:w.Bot,"chevron-down":w.ChevronDown,"chevron-up":w.ChevronUp,"chevron-right":w.ChevronRight,"chevron-left":w.ChevronLeft,check:w.Check,clipboard:w.Clipboard,"clipboard-copy":w.ClipboardCopy,copy:w.Copy,file:w.File,"file-code":w.FileCode,"file-spreadsheet":w.FileSpreadsheet,"file-text":w.FileText,"image-plus":w.ImagePlus,loader:w.Loader,"loader-circle":w.LoaderCircle,mic:w.Mic,paperclip:w.Paperclip,"refresh-cw":w.RefreshCw,search:w.Search,send:w.Send,"shield-alert":w.ShieldAlert,"shield-check":w.ShieldCheck,"shield-x":w.ShieldX,square:w.Square,"thumbs-down":w.ThumbsDown,"thumbs-up":w.ThumbsUp,upload:w.Upload,"volume-2":w.Volume2,x:w.X,user:w.User,mail:w.Mail,phone:w.Phone,calendar:w.Calendar,clock:w.Clock,building:w.Building,"map-pin":w.MapPin,lock:w.Lock,key:w.Key,"credit-card":w.CreditCard,"at-sign":w.AtSign,hash:w.Hash,globe:w.Globe,link:w.Link,"circle-check":w.CircleCheck,"circle-x":w.CircleX,"triangle-alert":w.TriangleAlert,info:w.Info,ban:w.Ban,shield:w.Shield,"arrow-left":w.ArrowLeft,"arrow-right":w.ArrowRight,"external-link":w.ExternalLink,ellipsis:w.Ellipsis,"ellipsis-vertical":w.EllipsisVertical,menu:w.Menu,house:w.House,plus:w.Plus,minus:w.Minus,pencil:w.Pencil,trash:w.Trash,"trash-2":w.Trash2,save:w.Save,download:w.Download,share:w.Share,funnel:w.Funnel,settings:w.Settings,"rotate-cw":w.RotateCw,maximize:w.Maximize,minimize:w.Minimize,"shopping-cart":w.ShoppingCart,"shopping-bag":w.ShoppingBag,package:w.Package,truck:w.Truck,tag:w.Tag,gift:w.Gift,receipt:w.Receipt,wallet:w.Wallet,store:w.Store,"dollar-sign":w.DollarSign,percent:w.Percent,play:w.Play,pause:w.Pause,"volume-x":w.VolumeX,camera:w.Camera,image:w.Image,film:w.Film,headphones:w.Headphones,"message-circle":w.MessageCircle,"message-square":w.MessageSquare,bell:w.Bell,heart:w.Heart,star:w.Star,eye:w.Eye,"eye-off":w.EyeOff,bookmark:w.Bookmark,"calendar-days":w.CalendarDays,history:w.History,timer:w.Timer,folder:w.Folder,"folder-open":w.FolderOpen,files:w.Files,sparkles:w.Sparkles,zap:w.Zap,sun:w.Sun,moon:w.Moon,flag:w.Flag,monitor:w.Monitor,smartphone:w.Smartphone},Se=(n,e=24,t="currentColor",r=2)=>{let o=kf[n];return o?Lf(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Lf(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}),o}var oi={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function Pf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function If(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var sa=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:oi.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:oi.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:oi.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:oi.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let g=Pu(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let f=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await Lu(c),u=Za(c)?URL.createObjectURL(c):null,m={id:Pf(),file:c,previewUrl:u,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Za(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=If(e.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Iu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Se("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Uu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function aa(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];Uu(s)&&Uu(o)?t[r]=aa(s,o):t[r]=o}return t}var Xr="min(440px, calc(100vw - 24px))",ju="440px",Wf={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:Xr,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:Wf,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 zu(n,e){if(!(!n&&!e))return n?e?aa(n,e):n:e}function Vu(n){var e,t,r,o,s,a,i,d,c,g,f,u,m,v,x,E,k,L,F,I,R;return n?{..._t,...n,theme:zu(_t.theme,n.theme),darkTheme:zu(_t.darkTheme,n.darkTheme),launcher:{..._t.launcher,...n.launcher,dock:{...(e=_t.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=_t.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{..._t.copy,...n.copy},sendButton:{..._t.sendButton,...n.sendButton},statusIndicator:{..._t.statusIndicator,...n.statusIndicator},voiceRecognition:{..._t.voiceRecognition,...n.voiceRecognition},features:(()=>{var se,Q,ae,fe,ue,K,ie,We,te,ee;let A=(se=_t.features)==null?void 0:se.artifacts,W=(Q=n.features)==null?void 0:Q.artifacts,D=(ae=_t.features)==null?void 0:ae.scrollToBottom,N=(fe=n.features)==null?void 0:fe.scrollToBottom,M=(ue=_t.features)==null?void 0:ue.scrollBehavior,z=(K=n.features)==null?void 0:K.scrollBehavior,j=(ie=_t.features)==null?void 0:ie.streamAnimation,oe=(We=n.features)==null?void 0:We.streamAnimation,Le=(te=_t.features)==null?void 0:te.askUserQuestion,Ve=(ee=n.features)==null?void 0:ee.askUserQuestion,ve=A===void 0&&W===void 0?void 0:{...A,...W,layout:{...A==null?void 0:A.layout,...W==null?void 0:W.layout}},Be=D===void 0&&N===void 0?void 0:{...D,...N},Oe=M===void 0&&z===void 0?void 0:{...M,...z},Te=j===void 0&&oe===void 0?void 0:{...j,...oe},we=Le===void 0&&Ve===void 0?void 0:{...Le,...Ve,styles:{...Le==null?void 0:Le.styles,...Ve==null?void 0:Ve.styles}};return{..._t.features,...n.features,...Be!==void 0?{scrollToBottom:Be}:{},...Oe!==void 0?{scrollBehavior:Oe}:{},...ve!==void 0?{artifacts:ve}:{},...Te!==void 0?{streamAnimation:Te}:{},...we!==void 0?{askUserQuestion:we}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:_t.suggestionChips,suggestionChipsConfig:{..._t.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{..._t.layout,...n.layout,header:{...(a=_t.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=_t.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(g=_t.layout)==null?void 0:g.messages)==null?void 0:f.avatar,...(m=(u=n.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=_t.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(k=(E=n.layout)==null?void 0:E.messages)==null?void 0:k.timestamp}},slots:{...(L=_t.layout)==null?void 0:L.slots,...(F=n.layout)==null?void 0:F.slots}},markdown:{..._t.markdown,...n.markdown,options:{...(I=_t.markdown)==null?void 0:I.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{..._t.messageActions,...n.messageActions}}:_t}var Rf={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"}},Hf={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"}},Bf={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:Xr,maxWidth:ju,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 vs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?vs(n,r):r}function Ku(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=vs(n,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Df(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function Gu(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Gu(s,o):t[r]=o}return t}function Nf(n,e){return e?Gu(n,e):n}function qo(n,e={}){var o,s,a,i,d,c,g,f,u,m,v,x,E;let t={palette:Rf,semantic:Hf,components:Bf},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(g=n==null?void 0:n.semantic)==null?void 0:g.colors,interactive:{...t.semantic.colors.interactive,...(u=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(E=n==null?void 0:n.semantic)==null?void 0:E.typography}},components:Nf(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let k=Df(r);if(!k.valid)throw new Error(`Theme validation failed: ${k.errors.map(L=>L.message).join(", ")}`)}if(e.plugins)for(let k of e.plugins)r=k.transform(r);return r}function Qu(n){var x,E,k,L,F,I,R,A,W,D,N,M,z,j,oe,Le,Ve,ve,Be,Oe,Te,we,se,Q,ae,fe,ue,K,ie,We,te,ee,re,it,lt,st,Ee,he,Je,Y,me,ke,Ye,Ge,Ie,Ke,vn,Rt,pn,Cr,q,G,ye,Qe,et,qe,_e,Pt,Kt,Jt,Ln,V,Ht,ce,Ce,Fe,Tt,on,sn,xn,Nt,rt,Dt,pt,Yt,nr,Pn,an,On,Ar,xt,zn,Sr,Fr,mr,bt,Co,Tr,Ao,_n,Ko,Yr,Or,Zr,eo,So,To,to,Ct,jn,Vn,In,Mt,rr,or,Kn,no,_r,ro,Gn,Ft,Wn,sr,oo,$r,so,Mr,Qn;let e=Ku(n),t={};for(let[be,ut]of Object.entries(e)){let tn=be.replace(/\./g,"-");t[`--persona-${tn}`]=ut.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(k=t["--persona-semantic-colors-accent"])!=null?k:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(L=t["--persona-semantic-colors-surface"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(F=t["--persona-semantic-colors-background"])!=null?F:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(I=t["--persona-semantic-colors-container"])!=null?I:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(R=t["--persona-semantic-colors-text"])!=null?R:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(A=t["--persona-semantic-colors-text-muted"])!=null?A:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(D=t["--persona-semantic-colors-border"])!=null?D:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(N=t["--persona-semantic-colors-divider"])!=null?N:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(M=t["--persona-components-voice-recording-indicator"])!=null?M:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(z=t["--persona-components-voice-recording-background"])!=null?z:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(j=t["--persona-components-voice-processing-icon"])!=null?j:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Le=t["--persona-components-approval-requested-background"])!=null?Le:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Ve=t["--persona-components-approval-requested-border"])!=null?Ve:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ve=t["--persona-components-approval-requested-text"])!=null?ve:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Be=t["--persona-components-approval-requested-shadow"])!=null?Be:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(Oe=t["--persona-components-approval-approve-background"])!=null?Oe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Te=t["--persona-components-approval-deny-background"])!=null?Te:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(we=t["--persona-components-attachment-image-background"])!=null?we:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(se=t["--persona-components-attachment-image-border"])!=null?se:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Q=t["--persona-semantic-typography-fontFamily"])!=null?Q:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ae=t["--persona-semantic-typography-fontSize"])!=null?ae:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(fe=t["--persona-semantic-typography-fontWeight"])!=null?fe:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ue=t["--persona-semantic-typography-lineHeight"])!=null?ue:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(K=t["--persona-palette-radius-sm"])!=null?K:"0.125rem",t["--persona-radius-md"]=(ie=t["--persona-palette-radius-md"])!=null?ie:"0.375rem",t["--persona-radius-lg"]=(We=t["--persona-palette-radius-lg"])!=null?We:"0.5rem",t["--persona-radius-xl"]=(te=t["--persona-palette-radius-xl"])!=null?te:"0.75rem",t["--persona-radius-full"]=(ee=t["--persona-palette-radius-full"])!=null?ee:"9999px",t["--persona-launcher-radius"]=(it=(re=t["--persona-components-launcher-borderRadius"])!=null?re:t["--persona-palette-radius-full"])!=null?it:"9999px",t["--persona-launcher-bg"]=(lt=t["--persona-components-launcher-background"])!=null?lt:t["--persona-primary"],t["--persona-launcher-fg"]=(st=t["--persona-components-launcher-foreground"])!=null?st:t["--persona-text-inverse"],t["--persona-launcher-border"]=(Ee=t["--persona-components-launcher-border"])!=null?Ee:t["--persona-border"],t["--persona-button-primary-bg"]=(he=t["--persona-components-button-primary-background"])!=null?he:t["--persona-primary"],t["--persona-button-primary-fg"]=(Je=t["--persona-components-button-primary-foreground"])!=null?Je:t["--persona-text-inverse"],t["--persona-button-radius"]=(me=(Y=t["--persona-components-button-primary-borderRadius"])!=null?Y:t["--persona-palette-radius-full"])!=null?me:"9999px",t["--persona-panel-radius"]=(Ye=(ke=t["--persona-components-panel-borderRadius"])!=null?ke:t["--persona-radius-xl"])!=null?Ye:"0.75rem",t["--persona-panel-border"]=(Ge=t["--persona-components-panel-border"])!=null?Ge:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ke=(Ie=t["--persona-components-panel-shadow"])!=null?Ie:t["--persona-palette-shadows-xl"])!=null?Ke:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(vn=t["--persona-components-launcher-shadow"])!=null?vn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(pn=(Rt=t["--persona-components-input-borderRadius"])!=null?Rt:t["--persona-radius-lg"])!=null?pn:"0.5rem",t["--persona-message-user-radius"]=(q=(Cr=t["--persona-components-message-user-borderRadius"])!=null?Cr:t["--persona-radius-lg"])!=null?q:"0.5rem",t["--persona-message-assistant-radius"]=(ye=(G=t["--persona-components-message-assistant-borderRadius"])!=null?G:t["--persona-radius-lg"])!=null?ye:"0.5rem",t["--persona-header-bg"]=(Qe=t["--persona-components-header-background"])!=null?Qe:t["--persona-surface"],t["--persona-header-border"]=(et=t["--persona-components-header-border"])!=null?et:t["--persona-divider"],t["--persona-header-icon-bg"]=(qe=t["--persona-components-header-iconBackground"])!=null?qe:t["--persona-primary"],t["--persona-header-icon-fg"]=(_e=t["--persona-components-header-iconForeground"])!=null?_e:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Pt=t["--persona-components-header-titleForeground"])!=null?Pt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Kt=t["--persona-components-header-subtitleForeground"])!=null?Kt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Jt=t["--persona-components-header-actionIconForeground"])!=null?Jt:t["--persona-muted"];let r=(Ln=n.components)==null?void 0:Ln.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(V=n.components)==null?void 0:V.introCard;t["--persona-intro-card-bg"]=(Ht=t["--persona-components-introCard-background"])!=null?Ht:t["--persona-surface"],t["--persona-intro-card-radius"]=(ce=t["--persona-components-introCard-borderRadius"])!=null?ce:"1rem",t["--persona-intro-card-padding"]=(Ce=t["--persona-components-introCard-padding"])!=null?Ce:"1.5rem",t["--persona-intro-card-shadow"]=(Tt=(Fe=o==null?void 0:o.shadow)!=null?Fe:t["--persona-components-introCard-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(on=t["--persona-components-input-background"])!=null?on:t["--persona-surface"],t["--persona-input-placeholder"]=(sn=t["--persona-components-input-placeholder"])!=null?sn:t["--persona-text-muted"],t["--persona-message-user-bg"]=(xn=t["--persona-components-message-user-background"])!=null?xn:t["--persona-accent"],t["--persona-message-user-text"]=(Nt=t["--persona-components-message-user-text"])!=null?Nt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(rt=t["--persona-components-message-user-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Dt=t["--persona-components-message-assistant-background"])!=null?Dt:t["--persona-surface"],t["--persona-message-assistant-text"]=(pt=t["--persona-components-message-assistant-text"])!=null?pt:t["--persona-text"],t["--persona-message-assistant-border"]=(Yt=t["--persona-components-message-assistant-border"])!=null?Yt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(nr=t["--persona-components-message-assistant-shadow"])!=null?nr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(an=(Pn=t["--persona-components-scrollToBottom-background"])!=null?Pn:t["--persona-button-primary-bg"])!=null?an:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Ar=(On=t["--persona-components-scrollToBottom-foreground"])!=null?On:t["--persona-button-primary-fg"])!=null?Ar:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(xt=t["--persona-components-scrollToBottom-border"])!=null?xt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(zn=t["--persona-components-scrollToBottom-size"])!=null?zn:"40px",t["--persona-scroll-to-bottom-radius"]=(mr=(Fr=(Sr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Sr:t["--persona-button-radius"])!=null?Fr:t["--persona-radius-full"])!=null?mr:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Co=(bt=t["--persona-components-scrollToBottom-shadow"])!=null?bt:t["--persona-palette-shadows-sm"])!=null?Co:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Tr=t["--persona-components-scrollToBottom-padding"])!=null?Tr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Ao=t["--persona-components-scrollToBottom-gap"])!=null?Ao:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Ko=(_n=t["--persona-components-scrollToBottom-fontSize"])!=null?_n:t["--persona-palette-typography-fontSize-sm"])!=null?Ko:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Yr=t["--persona-components-scrollToBottom-iconSize"])!=null?Yr:"14px",t["--persona-tool-bubble-shadow"]=(Or=t["--persona-components-toolBubble-shadow"])!=null?Or:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Zr=t["--persona-components-reasoningBubble-shadow"])!=null?Zr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(eo=t["--persona-components-composer-shadow"])!=null?eo:"none",t["--persona-md-inline-code-bg"]=(So=t["--persona-components-markdown-inlineCode-background"])!=null?So:t["--persona-container"],t["--persona-md-inline-code-color"]=(To=t["--persona-components-markdown-inlineCode-foreground"])!=null?To:t["--persona-text"],t["--persona-md-link-color"]=(Ct=(to=t["--persona-components-markdown-link-foreground"])!=null?to:t["--persona-accent"])!=null?Ct:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(jn=t["--persona-components-markdown-codeBlock-background"])!=null?jn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Vn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Vn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(In=t["--persona-components-markdown-codeBlock-textColor"])!=null?In:"inherit",t["--persona-md-table-header-bg"]=(Mt=t["--persona-components-markdown-table-headerBackground"])!=null?Mt:t["--persona-container"],t["--persona-md-table-border-color"]=(rr=t["--persona-components-markdown-table-borderColor"])!=null?rr:t["--persona-border"],t["--persona-md-hr-color"]=(or=t["--persona-components-markdown-hr-color"])!=null?or:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Kn=t["--persona-components-markdown-blockquote-borderColor"])!=null?Kn:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(no=t["--persona-components-markdown-blockquote-background"])!=null?no:"transparent",t["--persona-md-blockquote-text-color"]=(_r=t["--persona-components-markdown-blockquote-textColor"])!=null?_r:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(ro=t["--persona-components-collapsibleWidget-container"])!=null?ro:t["--persona-surface"],t["--cw-surface"]=(Gn=t["--persona-components-collapsibleWidget-surface"])!=null?Gn:t["--persona-surface"],t["--cw-border"]=(Ft=t["--persona-components-collapsibleWidget-border"])!=null?Ft:t["--persona-border"],t["--persona-message-border"]=(Wn=t["--persona-components-message-border"])!=null?Wn:t["--persona-border"];let g=n.components,f=g==null?void 0:g.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let u=g==null?void 0:g.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let m=g==null?void 0:g.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=g==null?void 0:g.artifact;if(v!=null&&v.toolbar){let be=v.toolbar;be.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=be.iconHoverColor),be.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=be.iconHoverBackground),be.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=be.iconPadding),be.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=be.iconBorderRadius),be.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=be.iconBorder),be.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=be.toggleGroupGap),be.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=be.toggleBorderRadius),be.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=be.copyBackground),be.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=be.copyBorder),be.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=be.copyColor),be.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=be.copyBorderRadius),be.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=be.copyPadding),be.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=be.copyMenuBackground,t["--persona-dropdown-bg"]=(sr=t["--persona-dropdown-bg"])!=null?sr:be.copyMenuBackground),be.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=be.copyMenuBorder,t["--persona-dropdown-border"]=(oo=t["--persona-dropdown-border"])!=null?oo:be.copyMenuBorder),be.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=be.copyMenuShadow,t["--persona-dropdown-shadow"]=($r=t["--persona-dropdown-shadow"])!=null?$r:be.copyMenuShadow),be.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=be.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(so=t["--persona-dropdown-radius"])!=null?so:be.copyMenuBorderRadius),be.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=be.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Mr=t["--persona-dropdown-item-hover-bg"])!=null?Mr:be.copyMenuItemHoverBackground),be.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=be.iconBackground),be.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=be.toolbarBorder)}if(v!=null&&v.tab){let be=v.tab;be.background&&(t["--persona-artifact-tab-bg"]=be.background),be.activeBackground&&(t["--persona-artifact-tab-active-bg"]=be.activeBackground),be.activeBorder&&(t["--persona-artifact-tab-active-border"]=be.activeBorder),be.borderRadius&&(t["--persona-artifact-tab-radius"]=be.borderRadius),be.textColor&&(t["--persona-artifact-tab-color"]=be.textColor),be.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=be.hoverBackground),be.listBackground&&(t["--persona-artifact-tab-list-bg"]=be.listBackground),be.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=be.listBorderColor),be.listPadding&&(t["--persona-artifact-tab-list-padding"]=be.listPadding)}if(v!=null&&v.pane){let be=v.pane;if(be.toolbarBackground){let ut=(Qn=vs(n,be.toolbarBackground))!=null?Qn:be.toolbarBackground;t["--persona-artifact-toolbar-bg"]=ut}}return t}var Ff={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"}}},Xu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},nl=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Of=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":nl()},_f=n=>Of(n),$f=n=>qo(n),qf=n=>{var t;let e=qo(void 0,{validate:!1});return qo({...n,palette:{...e.palette,colors:{...Ff.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},si=n=>{let e=_f(n),t=Xu(n==null?void 0:n.theme),r=Xu(n==null?void 0:n.darkTheme);return e==="dark"?qf(aa(t!=null?t:{},r!=null?r:{})):$f(t)},Uf=n=>Qu(n),xs=(n,e)=>{let t=si(e),r=Uf(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},Ju=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(nl())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(nl());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};var Yu=require("idiomorph"),ai=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Yu.Idiomorph.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var ii={index:-1,draft:""};function Zu(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ii}}}function em(n,e){var t,r,o,s,a,i,d,c,g,f,u,m,v,x,E,k,L,F,I,R,A,W,D,N,M,z,j,oe,Le,Ve,ve,Be,Oe,Te,we,se,Q,ae;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=n.llmContent)==null?void 0:c.length)!=null?g:0,(u=(f=n.approval)==null?void 0:f.status)!=null?u:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(E=(x=n.toolCall)==null?void 0:x.name)!=null?E:"",(F=(L=(k=n.toolCall)==null?void 0:k.chunks)==null?void 0:L.length)!=null?F:0,(W=(A=(R=(I=n.toolCall)==null?void 0:I.chunks)==null?void 0:R[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?W:"",typeof((D=n.toolCall)==null?void 0:D.args)=="string"?n.toolCall.args.length:(N=n.toolCall)!=null&&N.args?JSON.stringify(n.toolCall.args).length:0,(j=(z=(M=n.reasoning)==null?void 0:M.chunks)==null?void 0:z.length)!=null?j:0,(ve=(Ve=(Le=(oe=n.reasoning)==null?void 0:oe.chunks)==null?void 0:Le[n.reasoning.chunks.length-1])==null?void 0:Ve.length)!=null?ve:0,(we=(Te=(Oe=(Be=n.reasoning)==null?void 0:Be.chunks)==null?void 0:Oe[n.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?we:"",(Q=(se=n.contentParts)==null?void 0:se.length)!=null?Q:0,(ae=n.stopReason)!=null?ae:"",e].join("\0")}function tm(){return new Map}function nm(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function rm(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function om(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function li(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Jr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function Uo(n,e){return Jr(n)-n.scrollTop<=e}function ci(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,g=t-r;return a||Math.abs(g)<s?{action:"none",delta:g,nextLastScrollTop:t}:!e&&o&&(!c||g>0)?{action:"resume",delta:g,nextLastScrollTop:t}:e&&i&&g<0?{action:"pause",delta:g,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:g,nextLastScrollTop:t}:{action:"none",delta:g,nextLastScrollTop:t}}function di(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function sm(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function am(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function im(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var Mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},En=1e5,xo=En+1;var ia={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},zf=["pre","code","a","script","style"],pi=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:ia.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:ia.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:ia.speed,duration:(o=n==null?void 0:n.duration)!=null?o:ia.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:ia.buffer}},jf=[{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"}],cm=new Map;for(let n of jf)cm.set(n.name,n);var la=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=cm.get(n))!=null?r:null},ui=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
17
- `);return s<0?"":n.slice(0,s)}return n},Vf=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},Kf=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},rl=/\s/,Gf=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Qf=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(rl.test(s[i])){let c=i;for(;c<s.length&&rl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let g=i;for(;g<s.length&&!rl.test(s[g]);)c.appendChild(Vf(r,s[g],e,t.value)),t.value+=1,g+=1;a.appendChild(c),i=g}o.replaceChild(a,n)},Xf=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Kf(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},ca=(n,e,t,r)=>{var f,u;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:zf).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Gf(d,s)||i.push(d),d=a.nextNode();let c={value:(u=r==null?void 0:r.startIndex)!=null?u:0},g=e==="char"?Qf:Xf;for(let m of i)g(m,t,c);return o.innerHTML},mi=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},da=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},lm=new WeakMap,Jf=(n,e)=>{var s;if(!n.styles)return;let t=lm.get(e);if(t||(t=new Set,lm.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},ol=new WeakMap,Yf=(n,e)=>{if(!n.onAttach)return;let t=ol.get(e);if(t||(t=new Map,ol.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},dm=n=>{let e=ol.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},sl=(n,e)=>{Jf(n,e),Yf(n,e)};function al(n,e=En){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var pa=0,wo=null;function il(n=document){var t;if(pa++,pa===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;wo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,pa=Math.max(0,pa-1),pa===0&&wo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=wo.originalOverflow,o.style.position=wo.originalPosition,o.style.top=wo.originalTop,o.style.width=wo.originalWidth,s.scrollTo(0,wo.scrollY),wo=null}}}var ua={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Cn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},ma=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},xr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:ua.side,width:(o=e==null?void 0:e.width)!=null?o:ua.width,animate:(s=e==null?void 0:e.animate)!=null?s:ua.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:ua.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:ua.maxHeight}};var wr={"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 Zf="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",gi=(n,e={})=>{var E,k,L,F,I,R;let{showClose:t=!0,wrapperClassName:r=Zf,buttonSize:o,iconSize:s="28px"}=e,a=(E=n==null?void 0:n.launcher)!=null?E:{},i=(k=o!=null?o:a.closeButtonSize)!=null?k:"32px",d=b("div",r),c=(L=a.closeButtonTooltipText)!=null?L:"Close chat",g=(F=a.closeButtonShowTooltip)!=null?F:!0,f=(I=a.closeButtonIconName)!=null?I:"x",u=(R=a.closeButtonIconText)!=null?R:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Lt("button",{className:Gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||Fn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=Se(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=u,d.appendChild(v),g&&c){let A=null,W=()=>{if(A)return;let N=v.ownerDocument,M=N.body;if(!M)return;A=Nr(N,"div","persona-clear-chat-tooltip"),A.textContent=c;let z=Nr(N,"div");z.className="persona-clear-chat-tooltip-arrow",A.appendChild(z);let j=v.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(xo),A.style.left=`${j.left+j.width/2}px`,A.style.top=`${j.top-8}px`,A.style.transform="translate(-50%, -100%)",M.appendChild(A)},D=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",W),d.addEventListener("mouseleave",D),v.addEventListener("focus",W),v.addEventListener("blur",D),d._cleanupTooltip=()=>{D(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",D),v.removeEventListener("focus",W),v.removeEventListener("blur",D)}}return{button:v,wrapper:d}},eh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",fi=(n,e={})=>{var A,W,D,N,M,z,j,oe,Le,Ve,ve,Be,Oe;let{wrapperClassName:t=eh,buttonSize:r,iconSize:o="20px"}=e,a=(W=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?W:{},i=(D=r!=null?r:a.size)!=null?D:"32px",d=(N=a.iconName)!=null?N:"refresh-cw",c=(M=a.iconColor)!=null?M:"",g=(z=a.backgroundColor)!=null?z:"",f=(j=a.borderWidth)!=null?j:"",u=(oe=a.borderColor)!=null?oe:"",m=(Le=a.borderRadius)!=null?Le:"",v=(Ve=a.paddingX)!=null?Ve:"",x=(ve=a.paddingY)!=null?ve:"",E=(Be=a.tooltipText)!=null?Be:"Clear chat",k=(Oe=a.showTooltip)!=null?Oe:!0,L=b("div",t),F=!!(f||u),I=Lt("button",{className:Gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"hover:persona-bg-gray-100",!F&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:c||Fn.actionIconColor,backgroundColor:g||void 0,border:F?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),R=Se(d,o,"currentColor",1);if(R&&(R.style.display="block",I.appendChild(R)),L.appendChild(I),k&&E){let Te=null,we=()=>{if(Te)return;let Q=I.ownerDocument,ae=Q.body;if(!ae)return;Te=Nr(Q,"div","persona-clear-chat-tooltip"),Te.textContent=E;let fe=Nr(Q,"div");fe.className="persona-clear-chat-tooltip-arrow",Te.appendChild(fe);let ue=I.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(xo),Te.style.left=`${ue.left+ue.width/2}px`,Te.style.top=`${ue.top-8}px`,Te.style.transform="translate(-50%, -100%)",ae.appendChild(Te)},se=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};L.addEventListener("mouseenter",we),L.addEventListener("mouseleave",se),I.addEventListener("focus",we),I.addEventListener("blur",se),L._cleanupTooltip=()=>{se(),L.removeEventListener("mouseenter",we),L.removeEventListener("mouseleave",se),I.removeEventListener("focus",we),I.removeEventListener("blur",se)}}return{button:I,wrapper:L}};var Fn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},zo=n=>{var R,A,W,D,N,M,z,j,oe,Le,Ve,ve,Be,Oe,Te,we;let{config:e,showClose:t=!0}=n,r=Lt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(R=e==null?void 0:e.launcher)!=null?R:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(W=o.closeButtonPlacement)!=null?W:"inline",i=(D=o.headerIconHidden)!=null?D:!1,d=o.headerIconName,c=Lt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let se=parseFloat(s)||24,Q=Se(d,se*.6,"currentColor",1);Q?c.replaceChildren(Q):c.textContent=(M=(N=e==null?void 0:e.launcher)==null?void 0:N.agentIconText)!=null?M:"\u{1F4AC}"}else if((z=e==null?void 0:e.launcher)!=null&&z.iconUrl){let se=b("img");se.src=e.launcher.iconUrl,se.alt="",se.className="persona-rounded-xl persona-object-cover",se.style.height=s,se.style.width=s,c.replaceChildren(se)}else c.textContent=(oe=(j=e==null?void 0:e.launcher)==null?void 0:j.agentIconText)!=null?oe:"\u{1F4AC}";let g=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Lt("span",{className:"persona-text-base persona-font-semibold",text:(Ve=(Le=e==null?void 0:e.launcher)==null?void 0:Le.title)!=null?Ve:"Chat Assistant",style:{color:Fn.titleColor}}),u=Lt("span",{className:"persona-text-xs",text:(Be=(ve=e==null?void 0:e.launcher)==null?void 0:ve.subtitle)!=null?Be:"Here to help you get answers fast",style:{color:Fn.subtitleColor}});g.append(f,u),i?r.append(g):r.append(c,g);let m=(Oe=o.clearChat)!=null?Oe:{},v=(Te=m.enabled)!=null?Te:!0,x=(we=m.placement)!=null?we:"inline",E=null,k=null;if(v){let Q=fi(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=Q.button,k=Q.wrapper,x==="top-right"&&(k.style.right="48px"),x==="inline"&&r.appendChild(k)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:F,wrapper:I}=gi(e,{showClose:t,wrapperClassName:L});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:u,closeButton:F,closeButtonWrapper:I,clearChatButton:E,clearChatButtonWrapper:k}},ga=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function ws(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(xo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let E=Se(m.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),g(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&g()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function g(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():g()}function u(){g(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:g,toggle:f,destroy:u}}function kn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=Se(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[g,f]of Object.entries(i))d.setAttribute(g,f);return d}function ll(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let g=b("button",c);if(g.type="button",g.setAttribute("aria-label",t),e){let u=Se(e,s!=null?s:14,"currentColor",2);u&&g.appendChild(u)}let f=b("span");if(f.textContent=t,g.appendChild(f),i&&g.addEventListener("click",i),d)for(let[u,m]of Object.entries(d))g.setAttribute(u,m);return g}function pm(n){var m,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let g=b("span","persona-combo-btn-label");g.textContent=e,c.appendChild(g);let f=Se(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var x,E;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(E=d.border)!=null?E:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let u=ws({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(u.element),c.addEventListener("click",x=>{x.stopPropagation();let E=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),u.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{g.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),u.show()},close:()=>{c.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let x=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),c.remove()}}}var th=n=>{var r;let e=zo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function nh(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Se(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=ws({items:a.menuItems,onSelect:g=>t==null?void 0:t(g),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",g=>{g.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var rh=n=>{var L,F,I,R,A,W,D,N,M;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(L=e==null?void 0:e.launcher)!=null?L:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,g;if(d)c=pm({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Fn.titleColor,g=(I=c.querySelector(".persona-combo-btn-label"))!=null?I:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=b("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=Fn.titleColor,g.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(g),nh(c,o==null?void 0:o.trailingActions,(A=o==null?void 0:o.onAction)!=null?A:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let j=o.onTitleClick;c.addEventListener("click",oe=>{oe.target.closest("button")||j()}),c.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),j())})}let z=o==null?void 0:o.titleRowHover;z&&(c.style.borderRadius=(W=z.borderRadius)!=null?W:"10px",c.style.padding=(D=z.padding)!=null?D:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var j,oe;c.style.backgroundColor=(j=z.background)!=null?j:"",c.style.borderColor=(oe=z.border)!=null?oe:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(N=a.closeButtonSize)!=null?N:"32px",u=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||Fn.actionIconColor;let v=(M=a.closeButtonIconName)!=null?M:"x",x=Se(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),u.appendChild(m),i.appendChild(u);let E=b("div");E.style.display="none";let k=b("span");return k.style.display="none",{header:i,iconHolder:E,headerTitle:g,headerSubtitle:k,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},um={default:th,minimal:rh},oh=n=>{var e;return(e=um[n])!=null?e:um.default},hi=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),g=b("div");g.style.display="none";let f=b("span"),u=b("span"),m=b("button");m.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:g,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=oh(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var yi=n=>{var a,i;let e=b("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},bi=n=>{var R,A,W,D,N,M,z,j,oe,Le,Ve,ve;let e=(R=n==null?void 0:n.sendButton)!=null?R:{},t=(A=e.useIcon)!=null?A:!1,r=(W=e.iconText)!=null?W:"\u2191",o=e.iconName,s=(D=e.stopIconName)!=null?D:"square",a=(N=e.tooltipText)!=null?N:"Send message",i=(M=e.stopTooltipText)!=null?M:"Stop generating",d=(j=(z=n==null?void 0:n.copy)==null?void 0:z.sendButtonLabel)!=null?j:"Send",c=(Le=(oe=n==null?void 0:n.copy)==null?void 0:oe.stopButtonLabel)!=null?Le:"Stop",g=(Ve=e.showTooltip)!=null?Ve:!1,f=(ve=e.size)!=null?ve:"40px",u=e.backgroundColor,m=e.textColor,v=b("div","persona-send-button-wrapper"),x=Lt("button",{className:Gs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!u&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?f:void 0,height:t?f:void 0,minWidth:t?f:void 0,minHeight:t?f:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),E=null,k=null;if(t){let Be=parseFloat(f)||24,Oe=(m==null?void 0:m.trim())||"currentColor";o?(E=Se(o,Be,Oe,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,k=Se(s,Be,Oe,2)}else x.textContent=d;let L=null;g&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let F="send";return{button:x,wrapper:v,setMode:Be=>{if(Be===F)return;F=Be;let Oe=Be==="stop"?i:a;if(x.setAttribute("aria-label",Oe),L&&(L.textContent=Oe),t){if(E&&k){let Te=Be==="stop"?k:E;x.replaceChildren(Te)}}else x.textContent=Be==="stop"?c:d}}},vi=n=>{var L,F,I,R,A,W,D,N,M,z,j,oe;let e=(L=n==null?void 0:n.voiceRecognition)!=null?L:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((F=e.provider)==null?void 0:F.type)==="runtype";if(!(r||o))return null;let a=(R=(I=n==null?void 0:n.sendButton)==null?void 0:I.size)!=null?R:"40px",i=(A=e.iconName)!=null?A:"mic",d=(W=e.iconSize)!=null?W:a,c=parseFloat(d)||24,g=(N=e.backgroundColor)!=null?N:(D=n==null?void 0:n.sendButton)==null?void 0:D.backgroundColor,f=(z=e.iconColor)!=null?z:(M=n==null?void 0:n.sendButton)==null?void 0:M.textColor,u=b("div","persona-send-button-wrapper"),m=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),x=Se(i,c,f||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",u.appendChild(m);let E=(j=e.tooltipText)!=null?j:"Start voice recognition";if(((oe=e.showTooltip)!=null?oe:!1)&&E){let Le=b("div","persona-send-button-tooltip");Le.textContent=E,u.appendChild(Le)}return{button:m,wrapper:u}},xi=n=>{var v,x,E,k,L,F,I,R;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(E=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?E:"40px",r=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((k=e.allowedTypes)!=null?k:Qr).join(","),o.multiple=((L=e.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(F=e.buttonIconName)!=null?F:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),g=Lt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(I=e.buttonTooltipText)!=null?I:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});g.addEventListener("mouseenter",()=>{g.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="transparent"});let f=Se(s,d,"currentColor",1.5);f?g.appendChild(f):g.textContent="\u{1F4CE}",g.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(g);let u=(R=e.buttonTooltipText)!=null?R:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=u,c.appendChild(m),{button:g,wrapper:c,input:o,previewsContainer:r}},wi=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=b("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Ci=()=>Lt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ai=n=>{var v,x,E,k,L,F;let{config:e}=n,t=Lt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Ci(),o=Lt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=yi(e);a();let i=bi(e),d=vi(e),c=xi(e),g=wi(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Lt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&u.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(u,m),o.append(f),o.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,g),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:g,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(k=c==null?void 0:c.wrapper)!=null?k:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var mm=()=>{let n=Lt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=Se("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=Se("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},gm=n=>{var v,x,E,k,L,F;let{config:e}=n,t=Lt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ci();r.style.display="none";let o=wi(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=yi(e);s.style.maxHeight="100px",a();let i=bi(e),d=vi(e),c=xi(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let g=Lt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let u=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),g.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&g.append(c.input),g.append(f,s,u),c&&t.append(c.previewsContainer),t.append(g,r,o);let m=g;return{footer:t,suggestions:r,composerForm:g,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(k=c==null?void 0:c.wrapper)!=null?k:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var fm=n=>{var g,f,u,m,v,x,E,k,L,F,I,R,A,W,D,N,M;let e=(f=(g=n==null?void 0:n.launcher)==null?void 0:g.enabled)!=null?f:!0,t=Cn(n);if(ma(n)){let z=(m=(u=n==null?void 0:n.launcher)==null?void 0:u.composerBar)!=null?m:{},j=b("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(v=z.expandedSize)!=null?v:"anchored",j.style.zIndex=String((E=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?E:En);let oe=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",j.appendChild(oe);let Le=b("div","persona-widget-pill-root");return Le.setAttribute("data-persona-composer-bar",""),Le.dataset.state="collapsed",Le.dataset.expandedSize=(k=z.expandedSize)!=null?k:"anchored",Le.style.zIndex=String((F=(L=n==null?void 0:n.launcher)==null?void 0:L.zIndex)!=null?F:En),{wrapper:j,panel:oe,pillRoot:Le}}if(t){let z=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return z.appendChild(j),{wrapper:z,panel:j}}if(!e){let z=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(R=(I=n==null?void 0:n.launcher)==null?void 0:I.width)!=null?R:"100%";return z.style.width=oe,j.style.width="100%",z.appendChild(j),{wrapper:z,panel:j}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&wr[o.position]?wr[o.position]:wr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((D=(W=n==null?void 0:n.launcher)==null?void 0:W.zIndex)!=null?D:En);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(M=(N=n==null?void 0:n.launcher)==null?void 0:N.width)!=null?M:n==null?void 0:n.launcherWidth,c=d!=null?d:Xr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},sh=(n,e)=>{var I,R,A,W,D,N,M,z,j;let t=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=gi(n,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(A=(R=(I=n==null?void 0:n.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?A:!0,a=null,i=null;if(s){let oe=fi(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Lt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Lt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let g=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(D=(W=n==null?void 0:n.copy)==null?void 0:W.welcomeTitle)!=null?D:"Hello \u{1F44B}"}),f=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(M=(N=n==null?void 0:n.copy)==null?void 0:N.welcomeSubtitle)!=null?M:"Ask anything about your account or products."}),u=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},g,f),m=b("div","persona-flex persona-flex-col persona-gap-3"),v=(z=n==null?void 0:n.layout)==null?void 0:z.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((j=n==null?void 0:n.copy)==null?void 0:j.showWelcomeCard)!==!1||(u.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(u,m);let E=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),k=gm({config:n}),{root:L,textNode:F}=mm();return t.append(d,o,c,E),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:m,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:g,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:L,peekTextNode:F}},hm=(n,e=!0)=>{var E,k,L,F,I,R,A,W,D;if(ma(n))return sh(n,e);let t=Lt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(E=n==null?void 0:n.layout)==null?void 0:E.header,o=((k=n==null?void 0:n.layout)==null?void 0:k.showHeader)!==!1,s=r?hi(n,r,{showClose:e}):zo({config:n,showClose:e}),a=Lt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Lt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),d=Lt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(I=n==null?void 0:n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),c=Lt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:Cn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),g=b("div","persona-flex persona-flex-col persona-gap-3"),f=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;f&&(g.style.maxWidth=f,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((W=n==null?void 0:n.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,g);let m=Ai({config:n}),v=((D=n==null?void 0:n.layout)==null?void 0:D.showFooter)!==!1;o?ga(t,s,n):(s.header.style.display="none",ga(t,s,n)),t.append(a);let x=Lt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(m.footer.style.display="none"),t.append(m.footer),t.append(x),{container:t,body:a,messagesWrapper:g,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var cl=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
16
+ _Details: ${e.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]}),zu=(n,t="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:t,ju=n=>Vs(n)||n===Gr,si=class{constructor(t={},e){this.config=t;this.callbacks=e;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new na(()=>this.createSpeechEngine());this.handleEvent=t=>{var e,r,o,s,a,i,d,c,g,f;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall,m=!!(u!=null&&u.name)&&(Vs(u.name)||u.name===Gr&&((r=(e=this.config.features)==null?void 0:e.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(g=this.callbacks).onError)==null||f.call(g,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Zs(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let e=(o=t.host)!=null?o:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!e||!r||!this.config.clientToken||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 tl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,e,r;return(r=(e=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:e.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let e=bs.isSupported()?new bs({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,g=this.config.clientToken,f=t.browserFallback!==!1;if(d&&c&&g)return rl().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:m})=>{let v=new u({host:d,agentId:c,clientToken:g,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&e?new m(v,e,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&e)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),e}return e}setupVoice(t){var e,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=hs(o);let a=(r=((e=this.config.voiceRecognition)!=null?e:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let g=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=g.id}if(c){this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let g=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=g.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var e,r,o,s,a,i,d,c,g,f;if(!((e=this.config.voiceRecognition)!=null&&e.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=t.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,e;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(e=(t=this.callbacks).onError)==null||e.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let e={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(e)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,e){return this.client.submitMessageFeedback(t,e)}async submitCSATFeedback(t,e){return this.client.submitCSATFeedback(t,e)}async submitNPSFeedback(t,e){return this.client.submitNPSFeedback(t,e)}updateConfig(t){let e={...this.config,...t};if(!If(this.config,e)){this.config=e,this.client.updateConfig(e);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=e,this.client=new Zs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:e,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g,rawContent:f}=t,m={id:a!=null?a:e==="user"?Za():e==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:e,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let e=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:f=!1,voiceProcessing:u,rawContent:m}=r,x={id:d!=null?d:o==="user"?Za():o==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};e.push(x)}return this.messages=this.sortMessages([...this.messages,...e]),this.callbacks.onMessagesChanged([...this.messages]),e}injectComponentDirective(t){let{component:e,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:e,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,e){var c,g,f,u,m;let r=t.trim();if(!r&&(!(e!=null&&e.contentParts)||e.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Za(),s=ea(),a={id:o,role:"user",content:r||ei,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(e==null?void 0:e.viaVoice)||!1,...(e==null?void 0:e.contentParts)&&e.contentParts.length>0&&{contentParts:e.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=Uu(v,this.config.errorMessage);if(E){let M={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(g=this.callbacks).onError)==null||f.call(g,v):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=ea();this.setStreaming(!0);let e=new AbortController;this.abortController=e;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:e.signal,assistantMessageId:t},this.handleEvent)}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let f=Uu(c,this.config.errorMessage);if(f){let u={id:t,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,e){var o,s,a;if(this.streaming&&!(e!=null&&e.allowReentry))return;e!=null&&e.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,e==null?void 0:e.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let e={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${e.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:e}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,e){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:e,resolvedAt:Date.now()}}),r(e==="approved")}async resolveApproval(t,e,r){var g,f,u,m,v;let o=`approval-${t.id}`,s={...t,status:e,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(g=a==null?void 0:a.createdAt)!=null?g:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(c?x=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},e,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},e),x){let E=null;if(x instanceof Response){if(!x.ok){let M=await x.json().catch(()=>null);throw new Error((u=M==null?void 0:M.error)!=null?u:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(e==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,e){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:e.answers,askUserQuestionIndex:e.currentIndex}})}markAskUserQuestionResolved(t,e){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...e?{askUserQuestionAnswers:e}:{}}})}async resolveAskUserQuestion(t,e){var g,f,u,m,v,x,E,M,S,B,I,R;let r=this.messages.find(A=>A.id===t.id);if(((g=r==null?void 0:r.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0)return;let o=(f=t.agentMetadata)==null?void 0:f.executionId,s=(u=t.toolCall)==null?void 0:u.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof e=="string"?void 0:e;if(a===void 0&&typeof e=="string"){let A=(x=t.toolCall)==null?void 0:x.args,L=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(L.length===1){let N=typeof((E=L[0])==null?void 0:E.question)=="string"?L[0].question:"";N&&(a={[N]:e})}}this.markAskUserQuestionResolved(t,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(S=t.toolCall)==null?void 0:S.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof e=="string"?e:Object.entries(e).map(([L,N])=>`${L}: ${Array.isArray(N)?N.join(", "):N}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((L,N)=>{let F=typeof(L==null?void 0:L.question)=="string"?L.question:"";if(!F)return;let k=A[F],z=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${N}`,role:"assistant",content:F,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${N}`,role:"user",content:z||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:e});if(!A.ok){let L=await A.json().catch(()=>null);throw new Error((B=L==null?void 0:L.error)!=null?B:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let L=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(R=(I=this.callbacks).onError)==null||R.call(I,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(t){var s,a;let e=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!e||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(e);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(e,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let e of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(e)})}flushWebMcpAwaitBatch(t){let e=this.webMcpAwaitBatches.get(t);if(!e)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=e;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let e=this.messages.find(a=>a.id===t.id),r=[(o=e==null?void 0:e.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Gr)return!1;let e=this.messages.find(s=>s.id===t.id);return((o=(e!=null?e:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let e=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:e,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),e}markWebMcpToolComplete(t,e,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:e,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,e){var d,c,g,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(e.map(async u=>{var R,A,L,N,F,k,z;let m=(R=u.toolCall)==null?void 0:R.name,v=(A=u.toolCall)==null?void 0:A.id;if(!m||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(u),M=(N=(L=u.agentMetadata)==null?void 0:L.webMcpToolCallId)!=null?N:m;if(m===Gr)return{dedupeKey:x,resumeKey:M,output:Gi(),toolMessage:u,startedAt:E,completedAt:Date.now()};let S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let B=this.client.executeWebMcpToolCall(m,(F=u.toolCall)==null?void 0:F.args,S.signal),I;if(!B)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await B}catch(j){let re=j instanceof Error&&(j.name==="AbortError"||j.message.includes("aborted")||j.message.includes("abort"));return re||(z=(k=this.callbacks).onError)==null||z.call(k,j instanceof Error?j:new Error(String(j))),this.markWebMcpToolComplete(u,ra(re?"Aborted by cancel()":zu(j)),E),this.webMcpInflightKeys.delete(x),null}return S.signal.aborted?(this.markWebMcpToolComplete(u,ra("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:M,output:I,toolMessage:u,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let u={};for(let v of i)u[v.resumeKey]=v.output;let m=await this.client.resumeFlow(t,u,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===Gr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(g=this.callbacks).onError)==null||f.call(g,u instanceof Error?u:new Error(String(u)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ra("Aborted by cancel()"),v.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,E,M,S,B,I,R,A,L,N,F;let e=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(E=t.toolCall)==null?void 0:E.id;if(!e){(S=(M=this.callbacks).onError)==null||S.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let k=`${e}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(e,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(z){(I=(B=this.callbacks).onError)==null||I.call(B,z instanceof Error?z:new Error(String(z)))}finally{this.webMcpInflightKeys.delete(k)}return}let s=`${e}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Gr,g=(R=t.toolCall)==null?void 0:R.args,f=c?null:this.client.executeWebMcpToolCall(r,g,d),u="execute",m=a;try{let k;if(c?k=Gi():f?k=await f:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ra("Aborted by cancel()"),a);return}let z=(L=(A=t.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?L:r;u="resume",await this.resumeWithToolOutput(e,z,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,k,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let z=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(u==="execute"||z||d.aborted)&&this.markWebMcpToolComplete(t,ra(z||d.aborted?"Aborted by cancel()":zu(k)),a),z||(F=(N=this.callbacks).onError)==null||F.call(N,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,e,r,o){var a,i;let s=await this.client.resumeFlow(t,{[e]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let e=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:e,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(e,s),this.selectedArtifactId=e,this.emitArtifactsState(),s}let r={id:e,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(e,r),this.selectedArtifactId=e,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,e;(e=(t=this.callbacks).onArtifactsState)==null||e.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var e,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(e=t.component)!=null?e:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,e=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=e,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let e=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),e&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=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 ni(t)}toggleReadAloud(t){let e=this.messages.find(s=>s.id===t);if(!e||e.role!=="assistant")return;let r=nl(e.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let e=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,e]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let e=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===e.id);if(r===-1){this.appendMessage(e);return}this.messages=this.messages.map((o,s)=>{var g,f,u,m,v,x,E,M,S,B,I,R,A,L,N;if(s!==r)return o;let a={...o,...e};if(((g=o.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0&&e.agentMetadata&&(a.agentMetadata={...e.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&e.agentMetadata&&(a.agentMetadata={...(u=a.agentMetadata)!=null?u:e.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&e.approval&&o.approval.id===e.approval.id){let F=o.approval,k=e.approval;a.approval={...F,...k,executionId:k.executionId||F.executionId,toolName:k.toolName||F.toolName,description:k.description||F.description,toolType:(m=k.toolType)!=null?m:F.toolType,reason:(v=k.reason)!=null?v:F.reason,parameters:(x=k.parameters)!=null?x:F.parameters}}let i=(E=e.toolCall)==null?void 0:E.name,d=(M=e.agentMetadata)==null?void 0:M.executionId,c=(S=e.toolCall)==null?void 0:S.id;if(i&&ju(i)&&d&&c&&((B=e.agentMetadata)==null?void 0:B.awaitingLocalTool)===!0){let F=`${d}:${c}`,k=this.webMcpInflightKeys.has(F),z=this.webMcpResolvedKeys.has(F),j=(I=o.toolCall)==null?void 0:I.name,re=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&j!==void 0&&ju(j)&&((L=o.toolCall)==null?void 0:L.status)==="complete";(k||z||re)&&(a.agentMetadata={...(N=a.agentMetadata)!=null?N:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((e,r)=>{var d,c;let o=new Date(e.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=e.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:e.id.localeCompare(r.id)})}};var C=require("lucide"),Pf={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},Se=(n,t=24,e="currentColor",r=2)=>{let o=Pf[n];return o?Wf(o,t,e,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Wf(n,t,e,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}),o}var ai={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function Rf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Bf(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var oa=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var e,r,o;this.config={allowedTypes:(e=t.allowedTypes)!=null?e:ai.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ai.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ai.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:ai.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var e,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(e=this.config).onFileRejected)==null||r.call(e,c,"count");continue}let g=Ru(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let f=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await Wu(c),u=ti(c)?URL.createObjectURL(c):null,m={id:Rf(),file:c,previewUrl:u,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let e=this.attachments.findIndex(d=>d.id===t);if(e===-1)return;let r=this.attachments[e];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(e,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,e;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(e=(t=this.config).onAttachmentsChange)==null||e.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let e=ti(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",e&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Bf(t.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Bu(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Se("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,e){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:e})}};var Vu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function sa(n,t){if(!n)return t;if(!t)return n;let e={...n};for(let[r,o]of Object.entries(t)){let s=e[r];Vu(s)&&Vu(o)?e[r]=sa(s,o):e[r]=o}return e}var Xr="min(440px, calc(100vw - 24px))",Gu="440px",Hf={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:Xr,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)"},zt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Hf,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Ku(n,t){if(!(!n&&!t))return n?t?sa(n,t):n:t}function Qu(n){var t,e,r,o,s,a,i,d,c,g,f,u,m,v,x,E,M,S,B,I,R;return n?{...zt,...n,theme:Ku(zt.theme,n.theme),darkTheme:Ku(zt.darkTheme,n.darkTheme),launcher:{...zt.launcher,...n.launcher,dock:{...(t=zt.launcher)==null?void 0:t.dock,...(e=n.launcher)==null?void 0:e.dock},clearChat:{...(r=zt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...zt.copy,...n.copy},sendButton:{...zt.sendButton,...n.sendButton},statusIndicator:{...zt.statusIndicator,...n.statusIndicator},voiceRecognition:{...zt.voiceRecognition,...n.voiceRecognition},features:(()=>{var oe,X,se,fe,pe,K,ae,Be,ee,Z;let A=(oe=zt.features)==null?void 0:oe.artifacts,L=(X=n.features)==null?void 0:X.artifacts,N=(se=zt.features)==null?void 0:se.scrollToBottom,F=(fe=n.features)==null?void 0:fe.scrollToBottom,k=(pe=zt.features)==null?void 0:pe.scrollBehavior,z=(K=n.features)==null?void 0:K.scrollBehavior,j=(ae=zt.features)==null?void 0:ae.streamAnimation,re=(Be=n.features)==null?void 0:Be.streamAnimation,Ie=(ee=zt.features)==null?void 0:ee.askUserQuestion,Ve=(Z=n.features)==null?void 0:Z.askUserQuestion,ve=A===void 0&&L===void 0?void 0:{...A,...L,layout:{...A==null?void 0:A.layout,...L==null?void 0:L.layout}},Ne=N===void 0&&F===void 0?void 0:{...N,...F},qe=k===void 0&&z===void 0?void 0:{...k,...z},Te=j===void 0&&re===void 0?void 0:{...j,...re},we=Ie===void 0&&Ve===void 0?void 0:{...Ie,...Ve,styles:{...Ie==null?void 0:Ie.styles,...Ve==null?void 0:Ve.styles}};return{...zt.features,...n.features,...Ne!==void 0?{scrollToBottom:Ne}:{},...qe!==void 0?{scrollBehavior:qe}:{},...ve!==void 0?{artifacts:ve}:{},...Te!==void 0?{streamAnimation:Te}:{},...we!==void 0?{askUserQuestion:we}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:zt.suggestionChips,suggestionChipsConfig:{...zt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...zt.layout,...n.layout,header:{...(a=zt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=zt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(g=zt.layout)==null?void 0:g.messages)==null?void 0:f.avatar,...(m=(u=n.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=zt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(M=(E=n.layout)==null?void 0:E.messages)==null?void 0:M.timestamp}},slots:{...(S=zt.layout)==null?void 0:S.slots,...(B=n.layout)==null?void 0:B.slots}},markdown:{...zt.markdown,...n.markdown,options:{...(I=zt.markdown)==null?void 0:I.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...zt.messageActions,...n.messageActions}}:zt}var Df={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"}},Nf={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"}},Ff={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:Xr,maxWidth:Gu,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 ys(n,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let e=t.split("."),r=n;for(let o of e){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ys(n,r):r}function Xu(n){let t={};function e(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ys(n,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&e(a,i)}}return e(n.palette,"palette"),e(n.semantic,"semantic"),e(n.components,"components"),t}function _f(n){let t=[],e=[];return n.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||e.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||e.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:e}}function Ju(n,t){let e={...n};for(let[r,o]of Object.entries(t)){let s=e[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?e[r]=Ju(s,o):e[r]=o}return e}function Of(n,t){return t?Ju(n,t):n}function qo(n,t={}){var o,s,a,i,d,c,g,f,u,m,v,x,E;let e={palette:Df,semantic:Nf,components:Ff},r={palette:{...e.palette,...n==null?void 0:n.palette,colors:{...e.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...e.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...e.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...e.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...e.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...e.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...e.semantic,...n==null?void 0:n.semantic,colors:{...e.semantic.colors,...(g=n==null?void 0:n.semantic)==null?void 0:g.colors,interactive:{...e.semantic.colors.interactive,...(u=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...e.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...e.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...e.semantic.typography,...(E=n==null?void 0:n.semantic)==null?void 0:E.typography}},components:Of(e.components,n==null?void 0:n.components)};if(t.validate!==!1){let M=_f(r);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(S=>S.message).join(", ")}`)}if(t.plugins)for(let M of t.plugins)r=M.transform(r);return r}function Yu(n){var x,E,M,S,B,I,R,A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we,oe,X,se,fe,pe,K,ae,Be,ee,Z,ne,st,at,nt,Me,he,Ge,J,ue,Le,Xe,Gt,Pe,Ue,rt,Nt,yn,wr,Sn,Ke,Ft,q,ke,Ce,_e,it,pt,ot,Mt,V,St,de,me,Ee,ut,en,an,wn,Ot,et,_t,mt,tn,rr,Wn,ln,On,Cr,Ct,jn,Ar,Nr,ur,xt,Co,Sr,Ao,$n,Ko,Yr,Fr,Zr,eo,So,To,to,Tt,Vn,Kn,Rn,kt,or,sr,Gn,no,_r,ro,Qn,$t,Bn,ar,oo,Or,so,Tr,Xn;let t=Xu(n),e={};for(let[ye,gt]of Object.entries(t)){let rn=ye.replace(/\./g,"-");e[`--persona-${rn}`]=gt.value}e["--persona-primary"]=(x=e["--persona-semantic-colors-primary"])!=null?x:e["--persona-palette-colors-primary-500"],e["--persona-secondary"]=(E=e["--persona-semantic-colors-secondary"])!=null?E:e["--persona-palette-colors-secondary-500"],e["--persona-accent"]=(M=e["--persona-semantic-colors-accent"])!=null?M:e["--persona-palette-colors-accent-500"],e["--persona-surface"]=(S=e["--persona-semantic-colors-surface"])!=null?S:e["--persona-palette-colors-gray-50"],e["--persona-background"]=(B=e["--persona-semantic-colors-background"])!=null?B:e["--persona-palette-colors-gray-50"],e["--persona-container"]=(I=e["--persona-semantic-colors-container"])!=null?I:e["--persona-palette-colors-gray-100"],e["--persona-text"]=(R=e["--persona-semantic-colors-text"])!=null?R:e["--persona-palette-colors-gray-900"],e["--persona-text-muted"]=(A=e["--persona-semantic-colors-text-muted"])!=null?A:e["--persona-palette-colors-gray-500"],e["--persona-text-inverse"]=(L=e["--persona-semantic-colors-text-inverse"])!=null?L:e["--persona-palette-colors-gray-50"],e["--persona-border"]=(N=e["--persona-semantic-colors-border"])!=null?N:e["--persona-palette-colors-gray-200"],e["--persona-divider"]=(F=e["--persona-semantic-colors-divider"])!=null?F:e["--persona-palette-colors-gray-200"],e["--persona-muted"]=e["--persona-text-muted"],e["--persona-voice-recording-indicator"]=(k=e["--persona-components-voice-recording-indicator"])!=null?k:e["--persona-palette-colors-error-500"],e["--persona-voice-recording-bg"]=(z=e["--persona-components-voice-recording-background"])!=null?z:e["--persona-palette-colors-error-50"],e["--persona-voice-processing-icon"]=(j=e["--persona-components-voice-processing-icon"])!=null?j:e["--persona-palette-colors-primary-500"],e["--persona-voice-speaking-icon"]=(re=e["--persona-components-voice-speaking-icon"])!=null?re:e["--persona-palette-colors-success-500"],e["--persona-approval-bg"]=(Ie=e["--persona-components-approval-requested-background"])!=null?Ie:e["--persona-palette-colors-warning-50"],e["--persona-approval-border"]=(Ve=e["--persona-components-approval-requested-border"])!=null?Ve:e["--persona-palette-colors-warning-200"],e["--persona-approval-text"]=(ve=e["--persona-components-approval-requested-text"])!=null?ve:e["--persona-palette-colors-gray-900"],e["--persona-approval-shadow"]=(Ne=e["--persona-components-approval-requested-shadow"])!=null?Ne:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-approval-approve-bg"]=(qe=e["--persona-components-approval-approve-background"])!=null?qe:e["--persona-palette-colors-success-500"],e["--persona-approval-deny-bg"]=(Te=e["--persona-components-approval-deny-background"])!=null?Te:e["--persona-palette-colors-error-500"],e["--persona-attachment-image-bg"]=(we=e["--persona-components-attachment-image-background"])!=null?we:e["--persona-palette-colors-gray-100"],e["--persona-attachment-image-border"]=(oe=e["--persona-components-attachment-image-border"])!=null?oe:e["--persona-palette-colors-gray-200"],e["--persona-font-family"]=(X=e["--persona-semantic-typography-fontFamily"])!=null?X:e["--persona-palette-typography-fontFamily-sans"],e["--persona-font-size"]=(se=e["--persona-semantic-typography-fontSize"])!=null?se:e["--persona-palette-typography-fontSize-base"],e["--persona-font-weight"]=(fe=e["--persona-semantic-typography-fontWeight"])!=null?fe:e["--persona-palette-typography-fontWeight-normal"],e["--persona-line-height"]=(pe=e["--persona-semantic-typography-lineHeight"])!=null?pe:e["--persona-palette-typography-lineHeight-normal"],e["--persona-input-font-family"]=e["--persona-font-family"],e["--persona-input-font-weight"]=e["--persona-font-weight"],e["--persona-radius-sm"]=(K=e["--persona-palette-radius-sm"])!=null?K:"0.125rem",e["--persona-radius-md"]=(ae=e["--persona-palette-radius-md"])!=null?ae:"0.375rem",e["--persona-radius-lg"]=(Be=e["--persona-palette-radius-lg"])!=null?Be:"0.5rem",e["--persona-radius-xl"]=(ee=e["--persona-palette-radius-xl"])!=null?ee:"0.75rem",e["--persona-radius-full"]=(Z=e["--persona-palette-radius-full"])!=null?Z:"9999px",e["--persona-launcher-radius"]=(st=(ne=e["--persona-components-launcher-borderRadius"])!=null?ne:e["--persona-palette-radius-full"])!=null?st:"9999px",e["--persona-launcher-bg"]=(at=e["--persona-components-launcher-background"])!=null?at:e["--persona-primary"],e["--persona-launcher-fg"]=(nt=e["--persona-components-launcher-foreground"])!=null?nt:e["--persona-text-inverse"],e["--persona-launcher-border"]=(Me=e["--persona-components-launcher-border"])!=null?Me:e["--persona-border"],e["--persona-button-primary-bg"]=(he=e["--persona-components-button-primary-background"])!=null?he:e["--persona-primary"],e["--persona-button-primary-fg"]=(Ge=e["--persona-components-button-primary-foreground"])!=null?Ge:e["--persona-text-inverse"],e["--persona-button-radius"]=(ue=(J=e["--persona-components-button-primary-borderRadius"])!=null?J:e["--persona-palette-radius-full"])!=null?ue:"9999px",e["--persona-panel-radius"]=(Xe=(Le=e["--persona-components-panel-borderRadius"])!=null?Le:e["--persona-radius-xl"])!=null?Xe:"0.75rem",e["--persona-panel-border"]=(Gt=e["--persona-components-panel-border"])!=null?Gt:`1px solid ${e["--persona-border"]}`,e["--persona-panel-shadow"]=(Ue=(Pe=e["--persona-components-panel-shadow"])!=null?Pe:e["--persona-palette-shadows-xl"])!=null?Ue:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",e["--persona-launcher-shadow"]=(rt=e["--persona-components-launcher-shadow"])!=null?rt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",e["--persona-input-radius"]=(yn=(Nt=e["--persona-components-input-borderRadius"])!=null?Nt:e["--persona-radius-lg"])!=null?yn:"0.5rem",e["--persona-message-user-radius"]=(Sn=(wr=e["--persona-components-message-user-borderRadius"])!=null?wr:e["--persona-radius-lg"])!=null?Sn:"0.5rem",e["--persona-message-assistant-radius"]=(Ft=(Ke=e["--persona-components-message-assistant-borderRadius"])!=null?Ke:e["--persona-radius-lg"])!=null?Ft:"0.5rem",e["--persona-header-bg"]=(q=e["--persona-components-header-background"])!=null?q:e["--persona-surface"],e["--persona-header-border"]=(ke=e["--persona-components-header-border"])!=null?ke:e["--persona-divider"],e["--persona-header-icon-bg"]=(Ce=e["--persona-components-header-iconBackground"])!=null?Ce:e["--persona-primary"],e["--persona-header-icon-fg"]=(_e=e["--persona-components-header-iconForeground"])!=null?_e:e["--persona-text-inverse"],e["--persona-header-title-fg"]=(it=e["--persona-components-header-titleForeground"])!=null?it:e["--persona-primary"],e["--persona-header-subtitle-fg"]=(pt=e["--persona-components-header-subtitleForeground"])!=null?pt:e["--persona-text-muted"],e["--persona-header-action-icon-fg"]=(ot=e["--persona-components-header-actionIconForeground"])!=null?ot:e["--persona-muted"];let r=(Mt=n.components)==null?void 0:Mt.header;r!=null&&r.shadow&&(e["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(e["--persona-header-border-bottom"]=r.borderBottom);let o=(V=n.components)==null?void 0:V.introCard;e["--persona-intro-card-bg"]=(St=e["--persona-components-introCard-background"])!=null?St:e["--persona-surface"],e["--persona-intro-card-radius"]=(de=e["--persona-components-introCard-borderRadius"])!=null?de:"1rem",e["--persona-intro-card-padding"]=(me=e["--persona-components-introCard-padding"])!=null?me:"1.5rem",e["--persona-intro-card-shadow"]=(ut=(Ee=o==null?void 0:o.shadow)!=null?Ee:e["--persona-components-introCard-shadow"])!=null?ut:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-input-background"]=(en=e["--persona-components-input-background"])!=null?en:e["--persona-surface"],e["--persona-input-placeholder"]=(an=e["--persona-components-input-placeholder"])!=null?an:e["--persona-text-muted"],e["--persona-message-user-bg"]=(wn=e["--persona-components-message-user-background"])!=null?wn:e["--persona-accent"],e["--persona-message-user-text"]=(Ot=e["--persona-components-message-user-text"])!=null?Ot:e["--persona-text-inverse"],e["--persona-message-user-shadow"]=(et=e["--persona-components-message-user-shadow"])!=null?et:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-message-assistant-bg"]=(_t=e["--persona-components-message-assistant-background"])!=null?_t:e["--persona-surface"],e["--persona-message-assistant-text"]=(mt=e["--persona-components-message-assistant-text"])!=null?mt:e["--persona-text"],e["--persona-message-assistant-border"]=(tn=e["--persona-components-message-assistant-border"])!=null?tn:e["--persona-border"],e["--persona-message-assistant-shadow"]=(rr=e["--persona-components-message-assistant-shadow"])!=null?rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",e["--persona-scroll-to-bottom-bg"]=(ln=(Wn=e["--persona-components-scrollToBottom-background"])!=null?Wn:e["--persona-button-primary-bg"])!=null?ln:e["--persona-accent"],e["--persona-scroll-to-bottom-fg"]=(Cr=(On=e["--persona-components-scrollToBottom-foreground"])!=null?On:e["--persona-button-primary-fg"])!=null?Cr:e["--persona-text-inverse"],e["--persona-scroll-to-bottom-border"]=(Ct=e["--persona-components-scrollToBottom-border"])!=null?Ct:e["--persona-primary"],e["--persona-scroll-to-bottom-size"]=(jn=e["--persona-components-scrollToBottom-size"])!=null?jn:"40px",e["--persona-scroll-to-bottom-radius"]=(ur=(Nr=(Ar=e["--persona-components-scrollToBottom-borderRadius"])!=null?Ar:e["--persona-button-radius"])!=null?Nr:e["--persona-radius-full"])!=null?ur:"9999px",e["--persona-scroll-to-bottom-shadow"]=(Co=(xt=e["--persona-components-scrollToBottom-shadow"])!=null?xt:e["--persona-palette-shadows-sm"])!=null?Co:"0 1px 2px 0 rgb(0 0 0 / 0.05)",e["--persona-scroll-to-bottom-padding"]=(Sr=e["--persona-components-scrollToBottom-padding"])!=null?Sr:"0.5rem 0.875rem",e["--persona-scroll-to-bottom-gap"]=(Ao=e["--persona-components-scrollToBottom-gap"])!=null?Ao:"0.5rem",e["--persona-scroll-to-bottom-font-size"]=(Ko=($n=e["--persona-components-scrollToBottom-fontSize"])!=null?$n:e["--persona-palette-typography-fontSize-sm"])!=null?Ko:"0.875rem",e["--persona-scroll-to-bottom-icon-size"]=(Yr=e["--persona-components-scrollToBottom-iconSize"])!=null?Yr:"14px",e["--persona-tool-bubble-shadow"]=(Fr=e["--persona-components-toolBubble-shadow"])!=null?Fr:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-reasoning-bubble-shadow"]=(Zr=e["--persona-components-reasoningBubble-shadow"])!=null?Zr:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-composer-shadow"]=(eo=e["--persona-components-composer-shadow"])!=null?eo:"none",e["--persona-md-inline-code-bg"]=(So=e["--persona-components-markdown-inlineCode-background"])!=null?So:e["--persona-container"],e["--persona-md-inline-code-color"]=(To=e["--persona-components-markdown-inlineCode-foreground"])!=null?To:e["--persona-text"],e["--persona-md-link-color"]=(Tt=(to=e["--persona-components-markdown-link-foreground"])!=null?to:e["--persona-accent"])!=null?Tt:"#0f0f0f";let s=e["--persona-components-markdown-heading-h1-fontSize"];s&&(e["--persona-md-h1-size"]=s);let a=e["--persona-components-markdown-heading-h1-fontWeight"];a&&(e["--persona-md-h1-weight"]=a);let i=e["--persona-components-markdown-heading-h2-fontSize"];i&&(e["--persona-md-h2-size"]=i);let d=e["--persona-components-markdown-heading-h2-fontWeight"];d&&(e["--persona-md-h2-weight"]=d);let c=e["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(e["--persona-md-prose-font-family"]=c),e["--persona-md-code-block-bg"]=(Vn=e["--persona-components-markdown-codeBlock-background"])!=null?Vn:e["--persona-container"],e["--persona-md-code-block-border-color"]=(Kn=e["--persona-components-markdown-codeBlock-borderColor"])!=null?Kn:e["--persona-border"],e["--persona-md-code-block-text-color"]=(Rn=e["--persona-components-markdown-codeBlock-textColor"])!=null?Rn:"inherit",e["--persona-md-table-header-bg"]=(kt=e["--persona-components-markdown-table-headerBackground"])!=null?kt:e["--persona-container"],e["--persona-md-table-border-color"]=(or=e["--persona-components-markdown-table-borderColor"])!=null?or:e["--persona-border"],e["--persona-md-hr-color"]=(sr=e["--persona-components-markdown-hr-color"])!=null?sr:e["--persona-divider"],e["--persona-md-blockquote-border-color"]=(Gn=e["--persona-components-markdown-blockquote-borderColor"])!=null?Gn:e["--persona-palette-colors-gray-900"],e["--persona-md-blockquote-bg"]=(no=e["--persona-components-markdown-blockquote-background"])!=null?no:"transparent",e["--persona-md-blockquote-text-color"]=(_r=e["--persona-components-markdown-blockquote-textColor"])!=null?_r:e["--persona-palette-colors-gray-500"],e["--cw-container"]=(ro=e["--persona-components-collapsibleWidget-container"])!=null?ro:e["--persona-surface"],e["--cw-surface"]=(Qn=e["--persona-components-collapsibleWidget-surface"])!=null?Qn:e["--persona-surface"],e["--cw-border"]=($t=e["--persona-components-collapsibleWidget-border"])!=null?$t:e["--persona-border"],e["--persona-message-border"]=(Bn=e["--persona-components-message-border"])!=null?Bn:e["--persona-border"];let g=n.components,f=g==null?void 0:g.iconButton;f&&(f.background&&(e["--persona-icon-btn-bg"]=f.background),f.border&&(e["--persona-icon-btn-border"]=f.border),f.color&&(e["--persona-icon-btn-color"]=f.color),f.padding&&(e["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(e["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(e["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(e["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(e["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(e["--persona-icon-btn-active-border"]=f.activeBorder));let u=g==null?void 0:g.labelButton;u&&(u.background&&(e["--persona-label-btn-bg"]=u.background),u.border&&(e["--persona-label-btn-border"]=u.border),u.color&&(e["--persona-label-btn-color"]=u.color),u.padding&&(e["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(e["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(e["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(e["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(e["--persona-label-btn-gap"]=u.gap));let m=g==null?void 0:g.toggleGroup;m&&(m.gap&&(e["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(e["--persona-toggle-group-radius"]=m.borderRadius));let v=g==null?void 0:g.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(e["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(e["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(e["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(e["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(e["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(e["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(e["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(e["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(e["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(e["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(e["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(e["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(e["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,e["--persona-dropdown-bg"]=(ar=e["--persona-dropdown-bg"])!=null?ar:ye.copyMenuBackground),ye.copyMenuBorder&&(e["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,e["--persona-dropdown-border"]=(oo=e["--persona-dropdown-border"])!=null?oo:ye.copyMenuBorder),ye.copyMenuShadow&&(e["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,e["--persona-dropdown-shadow"]=(Or=e["--persona-dropdown-shadow"])!=null?Or:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(e["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,e["--persona-dropdown-radius"]=(so=e["--persona-dropdown-radius"])!=null?so:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(e["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,e["--persona-dropdown-item-hover-bg"]=(Tr=e["--persona-dropdown-item-hover-bg"])!=null?Tr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(e["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(e["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(e["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(e["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(e["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(e["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(e["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(e["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(e["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(e["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(e["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let gt=(Xn=ys(n,ye.toolbarBackground))!=null?Xn:ye.toolbarBackground;e["--persona-artifact-toolbar-bg"]=gt}}return e}var $f={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Zu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},ol=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},qf=n=>{var e;let t=(e=n==null?void 0:n.colorScheme)!=null?e:"light";return t==="light"?"light":t==="dark"?"dark":ol()},Uf=n=>qf(n),zf=n=>qo(n),jf=n=>{var e;let t=qo(void 0,{validate:!1});return qo({...n,palette:{...t.palette,colors:{...$f.colors,...(e=n==null?void 0:n.palette)==null?void 0:e.colors}}},{validate:!1})},ii=n=>{let t=Uf(n),e=Zu(n==null?void 0:n.theme),r=Zu(n==null?void 0:n.darkTheme);return t==="dark"?jf(sa(e!=null?e:{},r!=null?r:{})):zf(e)},Vf=n=>Yu(n),vs=(n,t)=>{let e=ii(t),r=Vf(e);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},em=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let e=new MutationObserver(()=>{n(ol())});e.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>e.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let e=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(ol());e.addEventListener?(e.addEventListener("change",r),t.push(()=>e.removeEventListener("change",r))):e.addListener&&(e.addListener(r),t.push(()=>e.removeListener(r)))}return()=>{t.forEach(e=>e())}};var tm=require("idiomorph"),li=(n,t,e={})=>{let{preserveTypingAnimation:r=!0}=e;tm.Idiomorph.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var ci={index:-1,draft:""};function nm(n){let{direction:t,history:e,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(e.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=e.length-1;return{handled:!0,value:e[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:e[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<e.length-1){let i=s.index+1;return{handled:!0,value:e[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ci}}}function rm(n,t){var e,r,o,s,a,i,d,c,g,f,u,m,v,x,E,M,S,B,I,R,A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we,oe,X,se;return[n.id,n.role,(r=(e=n.content)==null?void 0:e.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=n.llmContent)==null?void 0:c.length)!=null?g:0,(u=(f=n.approval)==null?void 0:f.status)!=null?u:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(E=(x=n.toolCall)==null?void 0:x.name)!=null?E:"",(B=(S=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:S.length)!=null?B:0,(L=(A=(R=(I=n.toolCall)==null?void 0:I.chunks)==null?void 0:R[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?L:"",typeof((N=n.toolCall)==null?void 0:N.args)=="string"?n.toolCall.args.length:(F=n.toolCall)!=null&&F.args?JSON.stringify(n.toolCall.args).length:0,(j=(z=(k=n.reasoning)==null?void 0:k.chunks)==null?void 0:z.length)!=null?j:0,(ve=(Ve=(Ie=(re=n.reasoning)==null?void 0:re.chunks)==null?void 0:Ie[n.reasoning.chunks.length-1])==null?void 0:Ve.length)!=null?ve:0,(we=(Te=(qe=(Ne=n.reasoning)==null?void 0:Ne.chunks)==null?void 0:qe[n.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?we:"",(X=(oe=n.contentParts)==null?void 0:oe.length)!=null?X:0,(se=n.stopReason)!=null?se:"",t].join("\0")}function om(){return new Map}function sm(n,t,e){let r=n.get(t);return r&&r.fingerprint===e?r.wrapper:null}function am(n,t,e,r){n.set(t,{fingerprint:e,wrapper:r})}function im(n,t){for(let e of n.keys())t.has(e)||n.delete(e)}function di(n=!0){let t=n;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Jr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function Uo(n,t){return Jr(n)-n.scrollTop<=t}function pi(n){let{following:t,currentScrollTop:e,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,g=e-r;return a||Math.abs(g)<s?{action:"none",delta:g,nextLastScrollTop:e}:!t&&o&&(!c||g>0)?{action:"resume",delta:g,nextLastScrollTop:e}:t&&i&&g<0?{action:"pause",delta:g,nextLastScrollTop:e}:t&&d&&!o?{action:"pause",delta:g,nextLastScrollTop:e}:{action:"none",delta:g,nextLastScrollTop:e}}function ui(n){let{following:t,deltaY:e,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return t&&e<0?"pause":!t&&o&&e>0&&r?"resume":"none"}function lm(n,t){return!n||n.isCollapsed?!1:t.contains(n.anchorNode)||t.contains(n.focusNode)}function cm(n){let t=Math.max(0,n.anchorOffsetTop-n.topOffset),e=Math.max(0,t+n.viewportHeight-n.contentHeight);return{targetScrollTop:t,spacerHeight:e}}function dm(n){let t=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-t)}var Ln={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},In=1e5,xo=In+1;var aa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Kf=["pre","code","a","script","style"],mi=n=>{var t,e,r,o,s;return{type:(t=n==null?void 0:n.type)!=null?t:aa.type,placeholder:(e=n==null?void 0:n.placeholder)!=null?e:aa.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:aa.speed,duration:(o=n==null?void 0:n.duration)!=null?o:aa.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:aa.buffer}},Gf=[{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"}],um=new Map;for(let n of Gf)um.set(n.name,n);var ia=(n,t)=>{var e,r;return n==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,n)?(e=t[n])!=null?e:null:(r=um.get(n))!=null?r:null},gi=(n,t,e,r,o)=>{if(!o)return n;if(e!=null&&e.bufferContent)return e.bufferContent(n,r);if(!n)return n;if(t==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(t==="line"){let s=n.lastIndexOf(`
17
+ `);return s<0?"":n.slice(0,s)}return n},Qf=(n,t,e,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${e}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Xf=(n,t,e,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${e}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},sl=/\s/,Jf=(n,t)=>{let e=n.parentNode;for(;e;){if(e.nodeType===1){let r=e;if(t.has(r.tagName.toLowerCase()))return!0}e=e.parentNode}return!1},Yf=(n,t,e)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(sl.test(s[i])){let c=i;for(;c<s.length&&sl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let g=i;for(;g<s.length&&!sl.test(s[g]);)c.appendChild(Qf(r,s[g],t,e.value)),e.value+=1,g+=1;a.appendChild(c),i=g}o.replaceChild(a,n)},Zf=(n,t,e)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Xf(r,c,t,e.value)),e.value+=1));o.replaceChild(a,n)},la=(n,t,e,r)=>{var f,u;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:Kf).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Jf(d,s)||i.push(d),d=a.nextNode();let c={value:(u=r==null?void 0:r.startIndex)!=null?u:0},g=t==="char"?Yf:Zf;for(let m of i)g(m,e,c);return o.innerHTML},fi=(n=document)=>{let t=n.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ca=(n=document)=>{let t=n.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let e=n.createElement("div");return e.className="persona-stream-skeleton-line",t.appendChild(e),t},pm=new WeakMap,eh=(n,t)=>{var s;if(!n.styles)return;let e=pm.get(t);if(e||(e=new Set,pm.set(t,e)),e.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;e.delete(n.name)}e.add(n.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,t.appendChild(o)},al=new WeakMap,th=(n,t)=>{if(!n.onAttach)return;let e=al.get(t);if(e||(e=new Map,al.set(t,e)),e.has(n.name))return;let r=n.onAttach(t);e.set(n.name,r)},mm=n=>{let t=al.get(n);if(t){for(let e of t.values())typeof e=="function"&&e();t.clear()}},il=(n,t)=>{eh(n,t),th(n,t)};function ll(n,t=In){let e=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(t),n.style.isolation="isolate",()=>{a&&(n.style.position=e),n.style.zIndex=r,n.style.isolation=o}}var da=0,wo=null;function cl(n=document){var e;if(da++,da===1){let r=n.body,s=((e=n.defaultView)!=null?e:window).scrollY||n.documentElement.scrollTop;wo={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&&wo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=wo.originalOverflow,o.style.position=wo.originalPosition,o.style.top=wo.originalTop,o.style.width=wo.originalWidth,s.scrollTo(0,wo.scrollY),wo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},An=n=>{var t,e;return((e=(t=n==null?void 0:n.launcher)==null?void 0:t.mountMode)!=null?e:"floating")==="docked"},ua=n=>{var t,e;return((e=(t=n==null?void 0:n.launcher)==null?void 0:t.mountMode)!=null?e:"floating")==="composer-bar"},vr=n=>{var e,r,o,s,a,i;let t=(e=n==null?void 0:n.launcher)==null?void 0:e.dock;return{side:(r=t==null?void 0:t.side)!=null?r: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 xr={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var nh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",hi=(n,t={})=>{var E,M,S,B,I,R;let{showClose:e=!0,wrapperClassName:r=nh,buttonSize:o,iconSize:s="28px"}=t,a=(E=n==null?void 0:n.launcher)!=null?E:{},i=(M=o!=null?o:a.closeButtonSize)!=null?M:"32px",d=y("div",r),c=(S=a.closeButtonTooltipText)!=null?S:"Close chat",g=(B=a.closeButtonShowTooltip)!=null?B:!0,f=(I=a.closeButtonIconName)!=null?I:"x",u=(R=a.closeButtonIconText)!=null?R:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=It("button",{className:Ks("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:e?void 0:"none",color:a.closeButtonColor||_n.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=Se(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=u,d.appendChild(v),g&&c){let A=null,L=()=>{if(A)return;let F=v.ownerDocument,k=F.body;if(!k)return;A=Dr(F,"div","persona-clear-chat-tooltip"),A.textContent=c;let z=Dr(F,"div");z.className="persona-clear-chat-tooltip-arrow",A.appendChild(z);let j=v.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(xo),A.style.left=`${j.left+j.width/2}px`,A.style.top=`${j.top-8}px`,A.style.transform="translate(-50%, -100%)",k.appendChild(A)},N=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",L),d.addEventListener("mouseleave",N),v.addEventListener("focus",L),v.addEventListener("blur",N),d._cleanupTooltip=()=>{N(),d.removeEventListener("mouseenter",L),d.removeEventListener("mouseleave",N),v.removeEventListener("focus",L),v.removeEventListener("blur",N)}}return{button:v,wrapper:d}},rh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bi=(n,t={})=>{var A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe;let{wrapperClassName:e=rh,buttonSize:r,iconSize:o="20px"}=t,a=(L=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?L:{},i=(N=r!=null?r:a.size)!=null?N:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",c=(k=a.iconColor)!=null?k:"",g=(z=a.backgroundColor)!=null?z:"",f=(j=a.borderWidth)!=null?j:"",u=(re=a.borderColor)!=null?re:"",m=(Ie=a.borderRadius)!=null?Ie:"",v=(Ve=a.paddingX)!=null?Ve:"",x=(ve=a.paddingY)!=null?ve:"",E=(Ne=a.tooltipText)!=null?Ne:"Clear chat",M=(qe=a.showTooltip)!=null?qe:!0,S=y("div",e),B=!!(f||u),I=It("button",{className:Ks("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"hover:persona-bg-gray-100",!B&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:c||_n.actionIconColor,backgroundColor:g||void 0,border:B?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),R=Se(d,o,"currentColor",1);if(R&&(R.style.display="block",I.appendChild(R)),S.appendChild(I),M&&E){let Te=null,we=()=>{if(Te)return;let X=I.ownerDocument,se=X.body;if(!se)return;Te=Dr(X,"div","persona-clear-chat-tooltip"),Te.textContent=E;let fe=Dr(X,"div");fe.className="persona-clear-chat-tooltip-arrow",Te.appendChild(fe);let pe=I.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(xo),Te.style.left=`${pe.left+pe.width/2}px`,Te.style.top=`${pe.top-8}px`,Te.style.transform="translate(-50%, -100%)",se.appendChild(Te)},oe=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};S.addEventListener("mouseenter",we),S.addEventListener("mouseleave",oe),I.addEventListener("focus",we),I.addEventListener("blur",oe),S._cleanupTooltip=()=>{oe(),S.removeEventListener("mouseenter",we),S.removeEventListener("mouseleave",oe),I.removeEventListener("focus",we),I.removeEventListener("blur",oe)}}return{button:I,wrapper:S}};var _n={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))"},zo=n=>{var R,A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we;let{config:t,showClose:e=!0}=n,r=It("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=(R=t==null?void 0:t.launcher)!=null?R:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(L=o.closeButtonPlacement)!=null?L:"inline",i=(N=o.headerIconHidden)!=null?N:!1,d=o.headerIconName,c=It("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let oe=parseFloat(s)||24,X=Se(d,oe*.6,"currentColor",1);X?c.replaceChildren(X):c.textContent=(k=(F=t==null?void 0:t.launcher)==null?void 0:F.agentIconText)!=null?k:"\u{1F4AC}"}else if((z=t==null?void 0:t.launcher)!=null&&z.iconUrl){let oe=y("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(re=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?re:"\u{1F4AC}";let g=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=It("span",{className:"persona-text-base persona-font-semibold",text:(Ve=(Ie=t==null?void 0:t.launcher)==null?void 0:Ie.title)!=null?Ve:"Chat Assistant",style:{color:_n.titleColor}}),u=It("span",{className:"persona-text-xs",text:(Ne=(ve=t==null?void 0:t.launcher)==null?void 0:ve.subtitle)!=null?Ne:"Here to help you get answers fast",style:{color:_n.subtitleColor}});g.append(f,u),i?r.append(g):r.append(c,g);let m=(qe=o.clearChat)!=null?qe:{},v=(Te=m.enabled)!=null?Te:!0,x=(we=m.placement)!=null?we:"inline",E=null,M=null;if(v){let X=bi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=X.button,M=X.wrapper,x==="top-right"&&(M.style.right="48px"),x==="inline"&&r.appendChild(M)}let S=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:B,wrapper:I}=hi(t,{showClose:e,wrapperClassName:S});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:u,closeButton:B,closeButtonWrapper:I,clearChatButton:E,clearChatButtonWrapper:M}},ma=(n,t,e)=>{var a,i,d,c;let r=(a=e==null?void 0:e.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};function xs(n){let{items:t,onSelect:e,anchor:r,position:o="bottom-left",portal:s}=n,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(xo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let E=Se(m.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),g(),e(m.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&g()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function g(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():g()}function u(){g(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:g,toggle:f,destroy:u}}function Pn(n){let{icon:t,label:e,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",e),d.title=e;let c=Se(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[g,f]of Object.entries(i))d.setAttribute(g,f);return d}function dl(n){let{icon:t,label:e,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let g=y("button",c);if(g.type="button",g.setAttribute("aria-label",e),t){let u=Se(t,s!=null?s:14,"currentColor",2);u&&g.appendChild(u)}let f=y("span");if(f.textContent=e,g.appendChild(f),i&&g.addEventListener("click",i),d)for(let[u,m]of Object.entries(d))g.setAttribute(u,m);return g}function gm(n){var m,v;let{label:t,icon:e="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let g=y("span","persona-combo-btn-label");g.textContent=t,c.appendChild(g);let f=Se(e,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var x,E;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(E=d.border)!=null?E:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let u=xs({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(u.element),c.addEventListener("click",x=>{x.stopPropagation();let E=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),u.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{g.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),u.show()},close:()=>{c.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let x=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),c.remove()}}}var oh=n=>{var r;let t=zo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),e=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(e){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>e()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),e())}))}return t};function sh(n,t,e){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Se(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=xs({items:a.menuItems,onSelect:g=>e==null?void 0:e(g),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",g=>{g.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>e==null?void 0:e(a.id)),n.appendChild(i)}}var ah=n=>{var S,B,I,R,A,L,N,F,k;let{config:t,showClose:e=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(S=t==null?void 0:t.launcher)!=null?S:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,g;if(d)c=gm({label:(B=a.title)!=null?B:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=_n.titleColor,g=(I=c.querySelector(".persona-combo-btn-label"))!=null?I:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=y("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=_n.titleColor,g.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(g),sh(c,o==null?void 0:o.trailingActions,(A=o==null?void 0:o.onAction)!=null?A:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let j=o.onTitleClick;c.addEventListener("click",re=>{re.target.closest("button")||j()}),c.addEventListener("keydown",re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),j())})}let z=o==null?void 0:o.titleRowHover;z&&(c.style.borderRadius=(L=z.borderRadius)!=null?L:"10px",c.style.padding=(N=z.padding)!=null?N:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var j,re;c.style.backgroundColor=(j=z.background)!=null?j:"",c.style.borderColor=(re=z.border)!=null?re:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(F=a.closeButtonSize)!=null?F:"32px",u=y("div",""),m=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=e?"":"none",m.style.color=a.closeButtonColor||_n.actionIconColor;let v=(k=a.closeButtonIconName)!=null?k:"x",x=Se(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),u.appendChild(m),i.appendChild(u);let E=y("div");E.style.display="none";let M=y("span");return M.style.display="none",{header:i,iconHolder:E,headerTitle:g,headerSubtitle:M,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},fm={default:oh,minimal:ah},ih=n=>{var t;return(t=fm[n])!=null?t:fm.default},yi=(n,t,e)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:e==null?void 0:e.onClose,onClearChat:e==null?void 0:e.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),g=y("div");g.style.display="none";let f=y("span"),u=y("span"),m=y("button");m.style.display="none";let v=y("div");return v.style.display="none",{header:c,iconHolder:g,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=ih(r)({config:n,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:e==null?void 0:e.showClose)!=null?d:!0,onClose:e==null?void 0:e.onClose,onClearChat:e==null?void 0:e.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var vi=n=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let e=3,r=20;t.style.maxHeight=`${e*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:e*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},xi=n=>{var R,A,L,N,F,k,z,j,re,Ie,Ve,ve;let t=(R=n==null?void 0:n.sendButton)!=null?R:{},e=(A=t.useIcon)!=null?A:!1,r=(L=t.iconText)!=null?L:"\u2191",o=t.iconName,s=(N=t.stopIconName)!=null?N:"square",a=(F=t.tooltipText)!=null?F:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=(j=(z=n==null?void 0:n.copy)==null?void 0:z.sendButtonLabel)!=null?j:"Send",c=(Ie=(re=n==null?void 0:n.copy)==null?void 0:re.stopButtonLabel)!=null?Ie:"Stop",g=(Ve=t.showTooltip)!=null?Ve:!1,f=(ve=t.size)!=null?ve:"40px",u=t.backgroundColor,m=t.textColor,v=y("div","persona-send-button-wrapper"),x=It("button",{className:Ks("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",e?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",e&&!u&&"persona-bg-persona-primary",!e&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:e?f:void 0,height:e?f:void 0,minWidth:e?f:void 0,minHeight:e?f:void 0,fontSize:e?"18px":void 0,lineHeight:e?"1":void 0,color:e?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:e&&u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,M=null;if(e){let Ne=parseFloat(f)||24,qe=(m==null?void 0:m.trim())||"currentColor";o?(E=Se(o,Ne,qe,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,M=Se(s,Ne,qe,2)}else x.textContent=d;let S=null;g&&a&&(S=y("div","persona-send-button-tooltip"),S.textContent=a,v.appendChild(S)),x.setAttribute("aria-label",a),v.appendChild(x);let B="send";return{button:x,wrapper:v,setMode:Ne=>{if(Ne===B)return;B=Ne;let qe=Ne==="stop"?i:a;if(x.setAttribute("aria-label",qe),S&&(S.textContent=qe),e){if(E&&M){let Te=Ne==="stop"?M:E;x.replaceChildren(Te)}}else x.textContent=Ne==="stop"?c:d}}},wi=n=>{var S,B,I,R,A,L,N,F,k,z,j,re;let t=(S=n==null?void 0:n.voiceRecognition)!=null?S:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((B=t.provider)==null?void 0:B.type)==="runtype";if(!(r||o))return null;let a=(R=(I=n==null?void 0:n.sendButton)==null?void 0:I.size)!=null?R:"40px",i=(A=t.iconName)!=null?A:"mic",d=(L=t.iconSize)!=null?L:a,c=parseFloat(d)||24,g=(F=t.backgroundColor)!=null?F:(N=n==null?void 0:n.sendButton)==null?void 0:N.backgroundColor,f=(z=t.iconColor)!=null?z:(k=n==null?void 0:n.sendButton)==null?void 0:k.textColor,u=y("div","persona-send-button-wrapper"),m=It("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=Se(i,c,f||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",u.appendChild(m);let E=(j=t.tooltipText)!=null?j:"Start voice recognition";if(((re=t.showTooltip)!=null?re:!1)&&E){let Ie=y("div","persona-send-button-tooltip");Ie.textContent=E,u.appendChild(Ie)}return{button:m,wrapper:u}},Ci=n=>{var v,x,E,M,S,B,I,R;let t=(v=n==null?void 0:n.attachments)!=null?v:{};if(t.enabled!==!0)return null;let e=(E=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?E:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((M=t.allowedTypes)!=null?M:Qr).join(","),o.multiple=((S=t.maxFiles)!=null?S:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(B=t.buttonIconName)!=null?B:"paperclip",a=e,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),g=It("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":(I=t.buttonTooltipText)!=null?I:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});g.addEventListener("mouseenter",()=>{g.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),g.addEventListener("mouseleave",()=>{g.style.backgroundColor="transparent"});let f=Se(s,d,"currentColor",1.5);f?g.appendChild(f):g.textContent="\u{1F4CE}",g.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(g);let u=(R=t.buttonTooltipText)!=null?R:"Attach file",m=y("div","persona-send-button-tooltip");return m.textContent=u,c.appendChild(m),{button:g,wrapper:c,input:o,previewsContainer:r}},Ai=n=>{var a,i,d;let t=(a=n==null?void 0:n.statusIndicator)!=null?a:{},e=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${e} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Si=()=>It("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ti=n=>{var v,x,E,M,S,B;let{config:t}=n,e=It("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=Si(),o=It("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}=vi(t);a();let i=xi(t),d=wi(t),c=Ci(t),g=Ai(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=It("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&u.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(u,m),o.append(f),o.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),e.append(r,o,g),{footer:e,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:g,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(B=c==null?void 0:c.previewsContainer)!=null?B:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var hm=()=>{let n=It("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),e=Se("message-square",16,"currentColor",1.5);e&&t.appendChild(e);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=Se("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(t,r,o),{root:n,textNode:r}},bm=n=>{var v,x,E,M,S,B;let{config:t}=n,e=It("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Si();r.style.display="none";let o=Ai(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=vi(t);s.style.maxHeight="100px",a();let i=xi(t),d=wi(t),c=Ci(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let g=It("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let u=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),g.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&g.append(c.input),g.append(f,s,u),c&&e.append(c.previewsContainer),e.append(g,r,o);let m=g;return{footer:e,suggestions:r,composerForm:g,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(B=c==null?void 0:c.previewsContainer)!=null?B:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var ym=n=>{var g,f,u,m,v,x,E,M,S,B,I,R,A,L,N,F,k;let t=(f=(g=n==null?void 0:n.launcher)==null?void 0:g.enabled)!=null?f:!0,e=An(n);if(ua(n)){let z=(m=(u=n==null?void 0:n.launcher)==null?void 0:u.composerBar)!=null?m:{},j=y("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(v=z.expandedSize)!=null?v:"anchored",j.style.zIndex=String((E=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?E:In);let re=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");re.style.width="100%",j.appendChild(re);let Ie=y("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(M=z.expandedSize)!=null?M:"anchored",Ie.style.zIndex=String((B=(S=n==null?void 0:n.launcher)==null?void 0:S.zIndex)!=null?B:In),{wrapper:j,panel:re,pillRoot:Ie}}if(e){let z=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return z.appendChild(j),{wrapper:z,panel:j}}if(!t){let z=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),re=(R=(I=n==null?void 0:n.launcher)==null?void 0:I.width)!=null?R:"100%";return z.style.width=re,j.style.width="100%",z.appendChild(j),{wrapper:z,panel:j}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&xr[o.position]?xr[o.position]:xr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((N=(L=n==null?void 0:n.launcher)==null?void 0:L.zIndex)!=null?N:In);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(F=n==null?void 0:n.launcher)==null?void 0:F.width)!=null?k:n==null?void 0:n.launcherWidth,c=d!=null?d:Xr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},lh=(n,t)=>{var I,R,A,L,N,F,k,z,j;let e=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");e.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=hi(n,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(A=(R=(I=n==null?void 0:n.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?A:!0,a=null,i=null;if(s){let re=bi(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=re.button,i=re.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=It("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=It("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let g=It("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),f=It("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(F=n==null?void 0:n.copy)==null?void 0:F.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),u=It("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},g,f),m=y("div","persona-flex persona-flex-col persona-gap-3"),v=(z=n==null?void 0:n.layout)==null?void 0:z.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((j=n==null?void 0:n.copy)==null?void 0:j.showWelcomeCard)!==!1||(u.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(u,m);let E=It("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"}}),M=bm({config:n}),{root:S,textNode:B}=hm();return e.append(d,o,c,E),i&&e.appendChild(i),{container:e,body:c,messagesWrapper:m,composerOverlay:E,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,introTitle:g,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:S,peekTextNode:B}},vm=(n,t=!0)=>{var E,M,S,B,I,R,A,L,N;if(ua(n))return lh(n,t);let e=It("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=n==null?void 0:n.layout)==null?void 0:E.header,o=((M=n==null?void 0:n.layout)==null?void 0:M.showHeader)!==!1,s=r?yi(n,r,{showClose:t}):zo({config:n,showClose:t}),a=It("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=It("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(B=(S=n==null?void 0:n.copy)==null?void 0:S.welcomeTitle)!=null?B:"Hello \u{1F44B}"}),d=It("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(I=n==null?void 0:n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),c=It("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:An(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),g=y("div","persona-flex persona-flex-col persona-gap-3"),f=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;f&&(g.style.maxWidth=f,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((L=n==null?void 0:n.copy)==null?void 0:L.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,g);let m=Ti({config:n}),v=((N=n==null?void 0:n.layout)==null?void 0:N.showFooter)!==!1;o?ma(e,s,n):(s.header.style.display="none",ma(e,s,n)),e.append(a);let x=It("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(m.footer.style.display="none"),e.append(m.footer),e.append(x),{container:e,body:a,messagesWrapper:g,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var pl=(n,t)=>{let e=y("button");e.type="button",e.innerHTML=`
18
18
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
19
19
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
20
20
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -22,14 +22,14 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
22
22
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
23
23
  </span>
24
24
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
25
- `,t.addEventListener("click",e);let r=s=>{var F,I,R,A,W,D,N,M,z,j,oe,Le,Ve;let a=(F=s.launcher)!=null?F:{},i=Cn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let ve=(I=a.title)!=null?I:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ve=(R=a.subtitle)!=null?R:"Here to help you get answers fast";c.textContent=ve,c.setAttribute("title",ve)}let g=t.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let ve=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=ve,f.style.width=ve,f.innerHTML="",a.agentIconName){let Be=parseFloat(ve)||24,Oe=Se(a.agentIconName,Be*.6,"var(--persona-text-inverse, #ffffff)",2);Oe?(f.appendChild(Oe),f.style.display=""):(f.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(D=a.agentIconText)!=null?D:"\u{1F4AC}",f.style.display="")}let u=t.querySelector("[data-role='launcher-image']");if(u){let ve=(N=a.agentIconSize)!=null?N:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ve=(M=a.callToActionIconSize)!=null?M:"32px";m.style.height=ve,m.style.width=ve,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Be=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Be=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Oe=parseFloat(ve)||24,Te=Math.max(Oe-Be,8),we=Se(a.callToActionIconName,Te,"currentColor",2);we?m.appendChild(we):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}let v=a.position&&wr[a.position]?wr[a.position]:wr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?E:`${x} ${v}`,i||(t.style.zIndex=String((oe=a.zIndex)!=null?oe:En));let k="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Le=a.border)!=null?Le:k,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ve=a.collapsedMaxWidth)!=null?Ve:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return n&&r(n),{element:t,update:r,destroy:o}};var ym=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=fm(n),s=hm(n,e),a={wrapper:t,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:u=>(d.element.replaceWith(u.header),d.element=u.header,d.iconHolder=u.iconHolder,d.headerTitle=u.headerTitle,d.headerSubtitle=u.headerSubtitle,d.closeButton=u.closeButton,d.closeButtonWrapper=u.closeButtonWrapper,d.clearChatButton=u.clearChatButton,d.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{c.footer.replaceWith(u),c.footer=u}}},dl=({config:n,plugins:e,onToggle:t})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>cl(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=cl(n,t);return{instance:o,element:o.element}};var ah=n=>{switch(n){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},ih=(n,e)=>{if(!n)return null;let t=ah(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},lh=(n,e)=>{let t=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",n),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},ch=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},pl=n=>{let e=n.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:")||!n.includes(":"))},ul=320,vm=320,dh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ph=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),uh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),mh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),gh=(n,e,t)=>{if(n.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return n.forEach((i,d)=>{var f;let c=b("img");c.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${ul}px`,c.style.maxHeight=`${vm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),ch(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},fh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!pl(r.audio))return;let o=b("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${ul}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},hh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!pl(r.video))return;let o=b("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${ul}px`,o.style.maxHeight=`${vm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},yh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!pl(r.data))return;let o=b("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},fa=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(t),n.appendChild(r),n.appendChild(o),n},bh=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:fa};if(e){let o=e(r);if(o!==null)return o}return fa()},vh=(n,e)=>{let t=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},bm=(n,e,t="div")=>{let r=b(t,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},xh=(n,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},wh=(n,e,t)=>{var v,x,E,k,L,F,I;let r=(v=e.showCopy)!=null?v:!0,o=(x=e.showUpvote)!=null?x:!0,s=(E=e.showDownvote)!=null?E:!0,a=(k=e.showReadAloud)!=null?k:!1;if(!r&&!o&&!s&&!a){let R=b("div");return R.style.display="none",R.id=`actions-${n.id}`,R.setAttribute("data-actions-for",n.id),R}let i=(L=e.visibility)!=null?L:"hover",d=(F=e.align)!=null?F:"right",c=(I=e.layout)!=null?I:"pill-inside",g={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],u=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${g} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${n.id}`,u.setAttribute("data-actions-for",n.id);let m=(R,A,W)=>{let D=kn({icon:R,label:A,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",W),D};return r&&u.appendChild(m("copy","Copy message","copy")),a&&u.appendChild(m("volume-2","Read aloud","read-aloud")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},ml=(n,e,t,r,o,s)=>{var se,Q,ae,fe,ue,K,ie,We,te,ee,re,it,lt,st,Ee,he,Je;let a=t!=null?t:{},i=(se=a.layout)!=null?se:"bubble",d=a.avatar,c=a.timestamp,g=(Q=d==null?void 0:d.show)!=null?Q:!1,f=(ae=c==null?void 0:c.show)!=null?ae:!1,u=(fe=d==null?void 0:d.position)!=null?fe:"left",m=(ue=c==null?void 0:c.position)!=null?ue:"below",v=xh(n.role,i),x=b("div",v.join(" "));x.id=`bubble-${n.id}`,x.setAttribute("data-message-id",n.id),x.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=dh(n),k=(ie=(K=n.content)==null?void 0:K.trim())!=null?ie:"",F=E.length>0&&k===Ya,I=pi((te=(We=s==null?void 0:s.widgetConfig)==null?void 0:We.features)==null?void 0:te.streamAnimation),R=(it=(re=(ee=s==null?void 0:s.widgetConfig)==null?void 0:ee.features)==null?void 0:re.streamAnimation)==null?void 0:it.plugins,A=n.role==="assistant"&&I.type!=="none"?la(I.type,R):null,W=n.role==="assistant"&&((lt=A==null?void 0:A.isAnimating)==null?void 0:lt.call(A,n))===!0,D=n.role==="assistant"&&A!==null&&(!!n.streaming||W);D&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),D&&A&&(A.containerClass&&N.classList.add(A.containerClass),N.style.setProperty("--persona-stream-step",`${I.speed}ms`),N.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let M=D?ui((st=n.content)!=null?st:"",I.buffer,A,n,!!n.streaming):(Ee=n.content)!=null?Ee:"",z=e({text:M,message:n,streaming:!!n.streaming,raw:n.rawContent}),j=z;D&&(A==null?void 0:A.wrap)==="char"?j=ca(z,"char",n.id,{skipTags:A.skipTags}):D&&(A==null?void 0:A.wrap)==="word"&&(j=ca(z,"word",n.id,{skipTags:A.skipTags}));let oe=null;if(F?(oe=document.createElement("div"),oe.innerHTML=j,oe.style.display="none",N.appendChild(oe)):N.innerHTML=j,D&&(A!=null&&A.useCaret)&&!F&&k){let Y=mi(),me=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),ke=me[me.length-1];if(ke!=null&&ke.parentNode)ke.parentNode.insertBefore(Y,ke.nextSibling);else{let Ye=N.lastElementChild;Ye?Ye.appendChild(Y):N.appendChild(Y)}}if(f&&m==="inline"&&n.createdAt){let Y=bm(n,c,"span");Y.classList.add("persona-timestamp-inline");let me=N.lastElementChild;me?me.appendChild(Y):N.appendChild(Y)}if(E.length>0){let Y=gh(E,!F&&!!k,()=>{F&&oe&&(oe.style.display="")});Y?x.appendChild(Y):F&&oe&&(oe.style.display="")}let Le=ph(n);if(Le.length>0){let Y=fh(Le);Y&&x.appendChild(Y)}let Ve=uh(n);if(Ve.length>0){let Y=hh(Ve);Y&&x.appendChild(Y)}let ve=mh(n);if(ve.length>0){let Y=yh(ve);Y&&x.appendChild(Y)}if(x.appendChild(N),f&&m==="below"&&n.createdAt){let Y=bm(n,c);Y.classList.add("persona-mt-1"),x.appendChild(Y)}let Be=n.role==="assistant"?ih(n.stopReason,(Je=(he=s==null?void 0:s.widgetConfig)==null?void 0:he.copy)==null?void 0:Je.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let Y=!!(M&&M.trim()),me=I.placeholder==="skeleton",ke=me&&I.buffer==="line"&&Y;if(Y)ke&&x.appendChild(da());else if(me)x.appendChild(da());else{let Ye=bh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ye&&x.appendChild(Ye)}}if(Be&&n.stopReason&&!n.streaming&&(k||(N.style.display="none"),x.appendChild(lh(n.stopReason,Be))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Y=wh(n,r,o);x.appendChild(Y)}if(!g||n.role==="system")return x;let Te=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),we=vh(d,n.role);return u==="right"||u==="left"&&n.role==="user"?Te.append(x,we):Te.append(we,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te};var Cs=new Set,Ch=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Ah=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
26
- `):""},xm=(n,e)=>{let t=Cs.has(n),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=Se(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},gl=(n,e)=>{var Ve,ve,Be,Oe,Te,we,se,Q,ae,fe,ue;let t=n.reasoning,r=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let o=(ve=(Ve=e==null?void 0:e.features)==null?void 0:Ve.reasoningDisplay)!=null?ve:{},s=o.expandable!==!1,a=s&&Cs.has(n.id),i=t.status!=="complete",d=Ah(n,(Be=o.previewMaxLines)!=null?Be:3),c=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let g=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(Oe=e==null?void 0:e.reasoning)!=null?Oe:{},v=String((Te=t.startedAt)!=null?Te:Date.now()),x=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Ka(t),K},E=(we=m.renderCollapsedSummary)==null?void 0:we.call(m,{message:n,reasoning:t,defaultSummary:u,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ka(t),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=u,g.appendChild(f));let k=b("span","persona-text-xs persona-text-persona-primary");k.textContent=xu(t),g.appendChild(k);let L=(se=o.loadingAnimation)!=null?se:"none",F=m.activeTextTemplate,I=m.completeTextTemplate,R=i?F:I,A=E instanceof HTMLElement,W=(K,ie,We)=>{let te=We;for(let ee of ie){let re=b("span","persona-tool-char");re.style.setProperty("--char-index",String(te)),re.textContent=ee===" "?"\xA0":ee,K.appendChild(re),te++}return te},D=(K,ie)=>{f.textContent="";let We=Ga(K,""),te=0;for(let ee of We){let re=ee.styles.length>0?(()=>{let it=b("span",ee.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return f.appendChild(it),it})():f;if(ee.isDuration&&i)re.appendChild(x());else{let it=ee.isDuration?Ka(t):ee.text;ie?te=W(re,it,te):re.appendChild(document.createTextNode(it))}}};if(!A&&R)if(k.style.display="none",f.style.display="",i&&L!=="none"){let K=(Q=m.loadingAnimationDuration)!=null?Q:2e3;f.setAttribute("data-preserve-animation","true"),L==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),D(R,!1)):(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),L==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),D(R,!0))}else D(R,!1);else if(!A&&i&&L!=="none"){f.style.display="";let K=(ae=m.loadingAnimationDuration)!=null?ae:2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),L==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ie=f.textContent||u;f.textContent="",W(f,ie,0)}t.status==="complete"&&(f.style.display="none")}else A||(t.status==="complete"?f.style.display="none":f.style.display="");let N=null;if(s){N=b("div","persona-flex persona-items-center");let ie=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ie?N.appendChild(ie):N.textContent=a?"Hide":"Show";let We=b("div","persona-flex persona-items-center persona-ml-auto");We.append(N),c.append(g,We)}else c.append(g);let M=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(M.setAttribute("data-persona-collapsed-preview","reasoning"),M.style.display="none",M.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(ue=(fe=e==null?void 0:e.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:ue.call(fe,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});Ch(M,K)||(M.textContent=d),M.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,M),r;let z=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");z.style.display=a?"":"none";let j=t.chunks.join(""),oe=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=j||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),z.appendChild(oe),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),N){N.innerHTML="";let ie=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ie?N.appendChild(ie):N.textContent=a?"Hide":"Show"}z.style.display=a?"":"none",M.style.display=a?"none":M.textContent||M.childNodes.length?"":"none"})(),r.append(c,M,z),r};var As=new Set,Sh=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Th=(n,e)=>{var s;let t=n.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
27
- `);let o=fs(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
28
- `):""},Mh=(n,e)=>{var g,f,u,m,v;let t=n.toolCall,r=(g=e==null?void 0:e.features)==null?void 0:g.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=Th(n,(u=r==null?void 0:r.previewMaxLines)!=null?u:3),a=t?wu(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Qi(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Qi(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},wm=(n,e,t)=>{var g;let r=As.has(n),o=(g=t==null?void 0:t.toolCall)!=null?g:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"currentColor",u=Se(r?"chevron-up":"chevron-down",16,f,2);u?c.appendChild(u):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},fl=(n,e)=>{var j,oe,Le,Ve,ve,Be,Oe,Te,we;let t=n.toolCall,r=(j=e==null?void 0:e.toolCall)!=null?j:{},o=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let s=(Le=(oe=e==null?void 0:e.features)==null?void 0:oe.toolCallDisplay)!=null?Le:{},a=s.expandable!==!1,i=a&&As.has(n.id),{summary:d,previewText:c,isActive:g}=Mh(n,e),f=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let u=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((Ve=t.startedAt)!=null?Ve:Date.now()),x=()=>{let se=b("span","");return se.setAttribute("data-tool-elapsed",v),se.textContent=Ys(t),se},E=(Be=r.renderCollapsedSummary)==null?void 0:Be.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(ve=s.collapsedMode)!=null?ve:"tool-call",isActive:g,config:e!=null?e:{},elapsed:Ys(t),createElapsedElement:x});typeof E=="string"&&E.trim()?(m.textContent=E,u.appendChild(m)):E instanceof HTMLElement?u.appendChild(E):(m.textContent=d,u.appendChild(m));let k=(Oe=s.loadingAnimation)!=null?Oe:"none",L=r.activeTextTemplate,F=r.completeTextTemplate,I=g?L:F,R=E instanceof HTMLElement,A=(se,Q,ae)=>{let fe=ae;for(let ue of Q){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(fe)),K.textContent=ue===" "?"\xA0":ue,se.appendChild(K),fe++}return fe},W=(se,Q)=>{var K;m.textContent="";let ae=((K=t.name)==null?void 0:K.trim())||"tool",fe=Ga(se,ae),ue=0;for(let ie of fe){let We=ie.styles.length>0?(()=>{let te=b("span",ie.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(te),te})():m;if(ie.isDuration&&g)We.appendChild(x());else{let te=ie.isDuration?Ys(t):ie.text;Q?ue=A(We,te,ue):We.appendChild(document.createTextNode(te))}}};if(!R)if(g&&k!=="none"){let se=(Te=r.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),k==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${se}ms`),I&&W(I,!1);else if(m.classList.add(`persona-tool-loading-${k}`),m.style.setProperty("--persona-tool-anim-duration",`${se}ms`),k==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)W(I,!0);else{let Q=m.textContent||d;m.textContent="",A(m,Q,0)}}else I&&W(I,!1);let D=null;if(a){D=b("div","persona-flex persona-items-center");let se=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Se(i?"chevron-up":"chevron-down",16,se,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show";let ae=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(D),f.append(u,ae)}else f.append(u);let N=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","tool"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&g&&s.activePreview&&c){let se=(we=r.renderCollapsedPreview)==null?void 0:we.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:g,config:e!=null?e:{}});Sh(N,se)||(N.textContent=c),N.style.display=""}if(!i&&g&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,N),o;let M=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(M.style.display=i?"":"none",r.contentBackgroundColor&&(M.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(M.style.color=r.contentTextColor),r.contentPaddingX&&(M.style.paddingLeft=r.contentPaddingX,M.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(M.style.paddingTop=r.contentPaddingY,M.style.paddingBottom=r.contentPaddingY),t.name){let se=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?se.style.color=r.contentTextColor:r.headerTextColor&&(se.style.color=r.headerTextColor),se.textContent=t.name,M.appendChild(se)}if(t.args!==void 0){let se=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Arguments";let ae=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ae.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ae.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ae.style.color=r.codeBlockTextColor),ae.textContent=fs(t.args),se.append(Q,ae),M.appendChild(se)}if(t.chunks&&t.chunks.length){let se=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Activity";let ae=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ae.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ae.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ae.style.color=r.codeBlockTextColor),ae.textContent=t.chunks.join(""),se.append(Q,ae),M.appendChild(se)}if(t.status==="complete"&&t.result!==void 0){let se=b("div","persona-space-y-1"),Q=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Q.style.color=r.labelTextColor),Q.textContent="Result";let ae=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(ae.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(ae.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(ae.style.color=r.codeBlockTextColor),ae.textContent=fs(t.result),se.append(Q,ae),M.appendChild(se)}if(t.status==="complete"&&typeof t.duration=="number"){let se=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(se.style.color=r.contentTextColor),se.textContent=`Duration: ${t.duration}ms`,M.appendChild(se)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),D){D.innerHTML="";let se=r.toggleTextColor||r.headerTextColor||"currentColor",Q=Se(i?"chevron-up":"chevron-down",16,se,2);Q?D.appendChild(Q):D.textContent=i?"Hide":"Show"}M.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),o.append(f,N,M),o};var Si=new Map,Eh=n=>{let t=(n.startsWith(No)?n.slice(No.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return n;let r=t.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Cm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Am=(n,e)=>{var r,o,s;let t=(o=(r=Cm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Si.get(n))!=null?s:t==="expanded"},Sm=(n,e,t)=>{var a,i;let r=Cm(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Se(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Tm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=Am(n,t);Sm(r,s,t),o.style.display=s?"":"none"};var Ti=(n,e)=>{var W,D,N,M,z,j,oe,Le,Ve,ve,Be,Oe,Te,we,se;let t=n.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(D=r==null?void 0:r.borderColor)!=null?D:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(N=r==null?void 0:r.titleColor)!=null?N:"currentColor",g=Se(d,20,c,2);g&&i.appendChild(g);let f=b("div","persona-flex-1 persona-min-w-0"),u=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(M=r==null?void 0:r.title)!=null?M:"Approval Required",u.appendChild(m),!o){let Q=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");Q.setAttribute("data-approval-status",t.status),t.status==="approved"?(Q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",Q.style.color="var(--persona-palette-colors-success-700, #15803d)",Q.textContent="Approved"):t.status==="denied"?(Q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",Q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",Q.textContent="Denied"):t.status==="timeout"&&(Q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",Q.style.color="var(--persona-palette-colors-warning-700, #b45309)",Q.textContent="Timeout"),u.appendChild(Q)}f.appendChild(u);let x=t.toolType==="webmcp"||t.toolName.startsWith(No)?Fi(t.toolName):void 0,E=(z=r==null?void 0:r.formatDescription)==null?void 0:z.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),k=!t.toolName,L=E||(k?t.description:`The assistant wants to use \u201C${x!=null?x:Eh(t.toolName)}\u201D.`),F=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(F.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(F.style.color=r.descriptionColor),F.textContent=L,f.appendChild(F),t.reason){let Q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");Q.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?Q.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor);let ae=b("span","persona-font-medium");ae.textContent=`${(j=r==null?void 0:r.reasonLabel)!=null?j:"Agent's stated reason:"} `,Q.appendChild(ae),Q.appendChild(document.createTextNode(t.reason)),f.appendChild(Q)}let I=(oe=r==null?void 0:r.detailsDisplay)!=null?oe:"collapsed",R=!!t.description&&!k,A=R||!!t.parameters;if(I!=="hidden"&&A){let Q=Am(n.id,e),ae=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let fe=b("span");fe.setAttribute("data-approval-details-label","true");let ue=b("span","persona-inline-flex persona-items-center");ue.setAttribute("data-approval-details-chevron","true"),ae.append(fe,ue),Sm(ae,Q,e),f.appendChild(ae);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=Q?"":"none",R){let ie=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor),ie.textContent=t.description,K.appendChild(ie)}if(t.parameters){let ie=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(ie.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ie.style.color=r.parameterTextColor),ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",ie.textContent=fs(t.parameters),K.appendChild(ie)}f.appendChild(K)}if(o){let Q=b("div","persona-flex persona-gap-2 persona-mt-2");Q.setAttribute("data-approval-buttons","true");let ae=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ae.type="button",ae.style.backgroundColor=(Le=r==null?void 0:r.approveButtonColor)!=null?Le:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(Ve=r==null?void 0:r.approveButtonTextColor)!=null?Ve:"#ffffff",ae.setAttribute("data-approval-action","approve");let fe=Se("shield-check",14,(ve=r==null?void 0:r.approveButtonTextColor)!=null?ve:"#ffffff",2);fe&&(fe.style.marginRight="4px",ae.appendChild(fe));let ue=document.createTextNode((Be=r==null?void 0:r.approveLabel)!=null?Be:"Approve");ae.appendChild(ue);let K=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Oe=r==null?void 0:r.denyButtonColor)!=null?Oe:"transparent",K.style.color=(Te=r==null?void 0:r.denyButtonTextColor)!=null?Te:"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 ie=Se("shield-x",14,(we=r==null?void 0:r.denyButtonTextColor)!=null?we:"var(--persona-feedback-error, #dc2626)",2);ie&&(ie.style.marginRight="4px",K.appendChild(ie));let We=document.createTextNode((se=r==null?void 0:r.denyLabel)!=null?se:"Deny");K.appendChild(We),Q.append(ae,K),f.appendChild(Q)}return a.append(i,f),s.appendChild(a),s};var Mm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let g=(c==null?void 0:c.agentPushed)===!0;if(g||(t=null),!o||!o.length||!g&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let f=document.createDocumentFragment(),u=s?s.isStreaming():!1,m=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(v=>{let x=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=u,d!=null&&d.fontFamily&&(x.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",g&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),e.push(x)}),n.appendChild(f),g){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ha=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ya=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var kh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Lh=new Set(["step_start","execution_start"]),Ph=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ih=new Set(["step_complete","agent_turn_complete"]),Wh=new Set(["flow_complete","agent_complete"]),Em=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Lm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),tr=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,jo=(n,e)=>{let t=n[e];return Lm(t)?t:void 0};function hl(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function Mi(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Rh(n,e){return typeof e.type=="string"?e.type:n}function Hh(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function Bh(n,e){return n==="step_delta"||n==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function km(n){var r,o,s,a,i;let e=jo(n,"result"),t=[jo(n,"tokens"),jo(n,"totalTokens"),e?jo(e,"tokens"):void 0,jo(n,"usage"),e?jo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=tr(d.output))!=null?r:tr(d.outputTokens))!=null?o:tr(d.completionTokens);if(c!==void 0)return c}return(i=(s=tr(n.outputTokens))!=null?s:tr(n.completionTokens))!=null?i:e?(a=tr(e.outputTokens))!=null?a:tr(e.completionTokens):void 0}function Dh(n){var t,r,o,s,a;let e=jo(n,"result");return(a=(o=(r=(t=tr(n.executionTime))!=null?t:tr(n.executionTimeMs))!=null?r:tr(n.execution_time))!=null?o:tr(n.duration))!=null?a:e?(s=tr(e.executionTime))!=null?s:tr(e.executionTimeMs):void 0}function Nh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ba=class{constructor(e=Nh){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:Mi(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var s;if(!Lm(t)){Em.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Rh(e,t),o=this.now();if(kh.has(r)){this.startRun(o);return}if(Lh.has(r)){this.run||this.startRun(o);return}if(Ph.has(r)){if(!Bh(r,t))return;let a=Hh(t);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+hl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Mi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ih.has(r)){if(!this.run)return;let a=this.run,i=km(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+hl(a.visibleCharCount),g=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:Mi(c,g),outputTokens:c,durationMs:g,source:d?"usage":"estimate"};return}if(Wh.has(r)){if(!this.run)return;let a=this.run,i=km(t),d=i!=null?i:a.exactOutputTokens+hl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",g=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:Mi(d,g),outputTokens:d,durationMs:g,source:c},this.run=null;return}if(Em.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Dh(t);return s!=null?s:r-e.startedAt}};function Ss(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Fh={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)"}},Oh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},_h=["flowName","stepName","reasoningText","text","name","tool","toolName"],$h=100;function qh(n,e){let t={...Fh,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Oh}function Uh(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function zh(n){let e=new Date(n),t=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function jh(n,e){try{let t=JSON.parse(n);if(typeof t!="object"||t===null)return null;for(let r of e){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Vh(n){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(n):new Promise(t=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Kh(n){let e;try{e=JSON.parse(n.payload)}catch{e=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:e},null,2)}function Gh(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Qh(n){let e=[];return n.outputTokens!==void 0&&e.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&e.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&e.push(n.source),e.join(" \xB7 ")}function Xh(n,e,t){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function yl(n,e,t,r,o,s,a,i){var u;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Ss(c,(u=r.classNames)==null?void 0:u.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var j,oe;let m=b("div",""),v=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",n.id);let x=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Se(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let k=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(j=r.timestampFormat)!=null?j:"relative";k.textContent=L==="relative"?Uh(n.timestamp,t):zh(n.timestamp);let F=null;r.showSequenceNumbers!==!1&&(F=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),F.textContent=String(e+1));let I=qh(n.type,r.badgeColors),R=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");R.style.backgroundColor=I.bg,R.style.color=I.text,R.style.borderColor=I.text+"50",R.textContent=n.type;let A=(oe=r.descriptionFields)!=null?oe:_h,W=jh(n.payload,A),D=null;W&&(D=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),D.textContent=W);let N=b("div","persona-flex-1 persona-min-w-0"),M=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),z=Se("clipboard","12px","currentColor",1.5);return z&&M.appendChild(z),M.addEventListener("click",async Le=>{Le.stopPropagation(),await Vh(Kh(n)),M.innerHTML="";let Ve=Se("check","12px","currentColor",1.5);Ve&&M.appendChild(Ve),setTimeout(()=>{M.innerHTML="";let ve=Se("clipboard","12px","currentColor",1.5);ve&&M.appendChild(ve)},1500)}),v.appendChild(x),v.appendChild(k),F&&v.appendChild(F),v.appendChild(R),D&&v.appendChild(D),v.appendChild(N),v.appendChild(M),m.appendChild(v),d&&m.appendChild(Xh(n,a,i)),m}}function Pm(n){var v,x,E,k,L;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",g=(E=i==null?void 0:i.label)!=null?E:"",f=(L=(k=o==null?void 0:o.features)==null?void 0:k.eventStream)!=null?L:{},u=s.find(F=>F.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let F=u.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(F)return{element:F,update:()=>{},destroy:()=>{}}}return m();function m(){let F=f.classNames,I=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ss(I,F==null?void 0:F.panel);let R=[],A="",W="",D=null,N=[],M={},z=0,j=li(),oe=0,Le=0,Ve=!1,ve=null,Be=!1,Oe=0,Te=new Set,we=new Map,se="",Q="",ae=null,fe,ue,K,ie,We,te=null,ee=null,re=null;function it(){let ce=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ce=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Ss(Ce,F==null?void 0:F.headerBar);let Fe=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Fe.textContent="Events",fe=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),fe.textContent="0",a){ee=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ee.style.cursor="help";let nr=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");nr.textContent="Throughput",te=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),te.textContent="-- tok/s",re=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),re.style.display="none",re.style.pointerEvents="none";let Pn=ee,an=re,On=()=>{if(!an.textContent)return;let xt=Pn.getBoundingClientRect(),zn=ce.getBoundingClientRect();an.style.left=`${xt.left-zn.left}px`,an.style.top=`${xt.bottom-zn.top+4}px`,an.style.display="block"},Ar=()=>{an.style.display="none"};ee.addEventListener("mouseenter",On),ee.addEventListener("mouseleave",Ar),ee.appendChild(nr),ee.appendChild(te)}let Tt=b("div","persona-flex-1");ue=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let on=b("option","");on.value="",on.textContent="All events",ue.appendChild(on),K=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let xn=Se("clipboard-copy","12px","currentColor",1.5);xn&&K.appendChild(xn);let Nt=b("span","persona-text-xs");Nt.textContent="Copy All",K.appendChild(Nt),Ce.appendChild(Fe),Ce.appendChild(fe),ee&&Ce.appendChild(ee),Ce.appendChild(Tt),Ce.appendChild(ue),Ce.appendChild(K);let rt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ss(rt,F==null?void 0:F.searchBar);let Dt=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),pt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Dt&&pt.appendChild(Dt),ie=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ss(ie,F==null?void 0:F.searchInput),ie.type="text",ie.placeholder="Search event payloads...",We=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),We.type="button",We.style.display="none";let Yt=Se("x","12px","currentColor",2);return Yt&&We.appendChild(Yt),rt.appendChild(pt),rt.appendChild(ie),rt.appendChild(We),ce.appendChild(Ce),ce.appendChild(rt),re&&ce.appendChild(re),ce}let lt,st=s.find(ce=>ce.renderEventStreamToolbar);if(st!=null&&st.renderEventStreamToolbar&&o){let ce=st.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Ce=>{A=Ce,Rt(),q()},onSearchChange:Ce=>{W=Ce,Rt(),q()}});lt=ce!=null?ce:it()}else lt=it();let Ee=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ee.style.display="none";function he(){if(!a||!te||!ee)return;let ce=a();te.textContent=Gh(ce);let Ce=Qh(ce);re&&(re.textContent=Ce,Ce||(re.style.display="none")),Ce?ee.setAttribute("aria-label",Ce):ee.removeAttribute("aria-label")}let Je=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Y=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Y.style.height="100%";let me=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ss(me,F==null?void 0:F.scrollIndicator),me.style.display="none",me.setAttribute("data-persona-scroll-to-bottom-has-label",g?"true":"false");let ke=Se(c,"14px","currentColor",2);ke&&me.appendChild(ke);let Ye=b("span","");Ye.textContent=g,me.appendChild(Ye);let Ge=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ge.style.display="none",Je.appendChild(Y),Je.appendChild(Ge),Je.appendChild(me),I.setAttribute("tabindex","0"),I.appendChild(lt),I.appendChild(Ee),I.appendChild(Je);function Ie(){let ce=e.getAll(),Ce={};for(let Nt of ce)Ce[Nt.type]=(Ce[Nt.type]||0)+1;let Fe=Object.keys(Ce).sort(),Tt=Fe.length!==N.length||!Fe.every((Nt,rt)=>Nt===N[rt]),on=!Tt&&Fe.some(Nt=>Ce[Nt]!==M[Nt]),sn=ce.length!==Object.values(M).reduce((Nt,rt)=>Nt+rt,0);if(!Tt&&!on&&!sn||(N=Fe,M=Ce,!ue))return;let xn=ue.value;if(ue.options[0].textContent="All events",Tt){for(;ue.options.length>1;)ue.remove(1);for(let Nt of Fe){let rt=b("option","");rt.value=Nt,rt.textContent=`${Nt} (${Ce[Nt]||0})`,ue.appendChild(rt)}xn&&Fe.includes(xn)?ue.value=xn:xn&&(ue.value="",A="")}else for(let Nt=1;Nt<ue.options.length;Nt++){let rt=ue.options[Nt];rt.textContent=`${rt.value} (${Ce[rt.value]||0})`}}function Ke(){let ce=e.getAll();if(A&&(ce=ce.filter(Ce=>Ce.type===A)),W){let Ce=W.toLowerCase();ce=ce.filter(Fe=>Fe.type.toLowerCase().includes(Ce)||Fe.payload.toLowerCase().includes(Ce))}return ce}function vn(){return A!==""||W!==""}function Rt(){z=0,oe=0,j.resume(),me.style.display="none"}function pn(ce){Te.has(ce)?Te.delete(ce):Te.add(ce),ae=ce;let Ce=Y.scrollTop,Fe=j.isFollowing();Be=!0,j.pause(),q(),Y.scrollTop=Ce,Fe&&j.resume(),Be=!1}function Cr(){return Uo(Y,50)}function q(){Le=Date.now(),Ve=!1,he(),Ie();let ce=e.getEvictedCount();ce>0?(Ee.textContent=`${ce.toLocaleString()} older events truncated`,Ee.style.display=""):Ee.style.display="none",R=Ke();let Ce=R.length,Fe=e.getSize()>0;fe&&(fe.textContent=String(e.getSize())),Ce===0&&Fe&&vn()?(Ge.textContent=W?`No events matching '${W}'`:"No events matching filter",Ge.style.display="",Y.style.display="none"):(Ge.style.display="none",Y.style.display=""),K&&(K.title=vn()?`Copy Filtered (${Ce})`:"Copy All"),d&&!j.isFollowing()&&Ce>z&&(oe+=Ce-z,Ye.textContent=g?`${g}${oe>0?` (${oe})`:""}`:"",me.style.display=""),z=Ce;let Tt=e.getAll(),on=Tt.length>0?Tt[0].timestamp:0,sn=new Set(R.map(rt=>rt.id));for(let rt of Te)sn.has(rt)||Te.delete(rt);let xn=A!==se||W!==Q,Nt=we.size===0&&R.length>0;if(xn||Nt||R.length===0){Y.innerHTML="",we.clear();let rt=document.createDocumentFragment();for(let Dt=0;Dt<R.length;Dt++){let pt=yl(R[Dt],Dt,on,f,Te,pn,s,o);we.set(R[Dt].id,pt),rt.appendChild(pt)}Y.appendChild(rt),se=A,Q=W,ae=null}else{if(ae!==null){let Dt=we.get(ae);if(Dt&&Dt.parentNode===Y){let pt=R.findIndex(Yt=>Yt.id===ae);if(pt>=0){let Yt=yl(R[pt],pt,on,f,Te,pn,s,o);Y.insertBefore(Yt,Dt),Dt.remove(),we.set(ae,Yt)}}ae=null}let rt=new Set(R.map(Dt=>Dt.id));for(let[Dt,pt]of we)rt.has(Dt)||(pt.remove(),we.delete(Dt));for(let Dt=0;Dt<R.length;Dt++){let pt=R[Dt];if(!we.has(pt.id)){let Yt=yl(pt,Dt,on,f,Te,pn,s,o);we.set(pt.id,Yt),Y.appendChild(Yt)}}}j.isFollowing()&&(Y.scrollTop=Y.scrollHeight)}function G(){if(Date.now()-Le>=$h){ve!==null&&(cancelAnimationFrame(ve),ve=null),q();return}Ve||(Ve=!0,ve=requestAnimationFrame(()=>{ve=null,q()}))}let ye=(ce,Ce)=>{if(!K)return;K.innerHTML="";let Fe=Se(ce,"12px","currentColor",1.5);Fe&&K.appendChild(Fe);let Tt=b("span","persona-text-xs");Tt.textContent="Copy All",K.appendChild(Tt),setTimeout(()=>{K.innerHTML="";let on=Se("clipboard-copy","12px","currentColor",1.5);on&&K.appendChild(on);let sn=b("span","persona-text-xs");sn.textContent="Copy All",K.appendChild(sn),K.disabled=!1},Ce)},Qe=async()=>{if(K){K.disabled=!0;try{let ce;vn()?ce=R:t?(ce=await t(),ce.length===0&&(ce=e.getAll())):ce=e.getAll();let Ce=ce.map(Fe=>{try{return JSON.parse(Fe.payload)}catch{return Fe.payload}});await navigator.clipboard.writeText(JSON.stringify(Ce,null,2)),ye("check",1500)}catch{ye("x",1500)}}},et=()=>{ue&&(A=ue.value,Rt(),q())},qe=()=>{!ie||!We||(We.style.display=ie.value?"":"none",D&&clearTimeout(D),D=setTimeout(()=>{W=ie.value,Rt(),q()},150))},_e=()=>{!ie||!We||(ie.value="",W="",We.style.display="none",D&&clearTimeout(D),Rt(),q())},Pt=()=>{if(Be)return;let ce=Y.scrollTop,{action:Ce,nextLastScrollTop:Fe}=ci({following:j.isFollowing(),currentScrollTop:ce,lastScrollTop:Oe,nearBottom:Cr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Oe=Fe,Ce==="resume"?(j.resume(),oe=0,me.style.display="none"):Ce==="pause"&&(j.pause(),d&&(Ye.textContent=g,me.style.display=""))},Kt=ce=>{let Ce=di({following:j.isFollowing(),deltaY:ce.deltaY,nearBottom:Cr(),resumeWhenNearBottom:!0});Ce==="pause"?(j.pause(),d&&(Ye.textContent=g,me.style.display="")):Ce==="resume"&&(j.resume(),oe=0,me.style.display="none")},Jt=()=>{d&&(Y.scrollTop=Y.scrollHeight,j.resume(),oe=0,me.style.display="none")},Ln=ce=>{let Ce=ce.target;if(!Ce||Ce.closest("button"))return;let Fe=Ce.closest("[data-event-id]");if(!Fe)return;let Tt=Fe.getAttribute("data-event-id");Tt&&pn(Tt)},V=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),ie==null||ie.focus(),ie==null||ie.select();return}ce.key==="Escape"&&(ie&&document.activeElement===ie?(_e(),ie.blur(),I.focus()):r&&r())};K&&K.addEventListener("click",Qe),ue&&ue.addEventListener("change",et),ie&&ie.addEventListener("input",qe),We&&We.addEventListener("click",_e),Y.addEventListener("scroll",Pt),Y.addEventListener("wheel",Kt,{passive:!0}),Y.addEventListener("click",Ln),me.addEventListener("click",Jt),I.addEventListener("keydown",V);function Ht(){D&&clearTimeout(D),ve!==null&&(cancelAnimationFrame(ve),ve=null),Ve=!1,we.clear(),K&&K.removeEventListener("click",Qe),ue&&ue.removeEventListener("change",et),ie&&ie.removeEventListener("input",qe),We&&We.removeEventListener("click",_e),Y.removeEventListener("scroll",Pt),Y.removeEventListener("wheel",Kt),Y.removeEventListener("click",Ln),me.removeEventListener("click",Jt),I.removeEventListener("keydown",V)}return{element:I,update:G,destroy:Ht}}}function Im(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=t;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(g,f),i.append(d,c),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${t}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",r),i.append(u)}return i}var Wm=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",g=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Im(n,e)});if(g)return g}return Im(n,e)};var bl=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,r])=>{this.register(t,r)})}},Vo=new bl;Vo.register("PersonaArtifactCard",Wm);function Jh(n){var o;let e=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=b("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(r),e}function Rm(n,e){var ue,K,ie,We;let t=(K=(ue=n.features)==null?void 0:ue.artifacts)==null?void 0:K.layout,o=((ie=t==null?void 0:t.toolbarPreset)!=null?ie:"default")==="document",s=(We=t==null?void 0:t.panePadding)==null?void 0:We.trim(),a=n.markdown?Oa(n.markdown):null,i=_a(n.sanitize),d=te=>{let ee=a?a(te):ho(te);return i?i(ee):ee},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var te;g(),(te=e.onDismiss)==null||te.call(e)});let f=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let u=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var te;g(),(te=e.onDismiss)==null||te.call(e)});let x="rendered",E=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),k=o?kn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):kn({icon:"eye",label:"Rendered view"}),L=o?kn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):kn({icon:"code-2",label:"Source"}),F=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,R=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,A=t==null?void 0:t.documentToolbarCopyMenuItems,W=!!(R&&A&&A.length>0),D=null,N,M=null,z=null;if(o&&(I||R)&&!W){if(N=I?ll({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let te=Se("chevron-down",14,"currentColor",2);te&&N.appendChild(te)}}else o&&W?(D=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),N=I?ll({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),M=kn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),D.append(N,M)):o?N=kn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):N=kn({icon:"copy",label:"Copy"});let j=o?kn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):kn({icon:"refresh-cw",label:"Refresh"}),oe=o?kn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):kn({icon:"x",label:"Close"}),Le=()=>{var lt,st,Ee;let te=(lt=we.find(he=>he.id===se))!=null?lt:we[we.length-1],ee=(st=te==null?void 0:te.id)!=null?st:null,re=(te==null?void 0:te.artifactType)==="markdown"&&(Ee=te.markdown)!=null?Ee:"",it=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:re,jsonPayload:it,id:ee}},Ve=async()=>{var lt;let{markdown:te,jsonPayload:ee}=Le(),re=(lt=we.find(st=>st.id===se))!=null?lt:we[we.length-1],it=(re==null?void 0:re.artifactType)==="markdown"?te:re?ee:"";try{await navigator.clipboard.writeText(it)}catch{}};if(N.addEventListener("click",async()=>{let te=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(te&&W){let{markdown:ee,jsonPayload:re,id:it}=Le();try{await te({actionId:"primary",artifactId:it,markdown:ee,jsonPayload:re})}catch{}return}await Ve()}),M&&(A!=null&&A.length)){let te=()=>{var re;return(re=f.closest("[data-persona-root]"))!=null?re:document.body},ee=()=>{z=ws({items:A.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:it,jsonPayload:lt,id:st}=Le(),Ee=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ee?await Ee({actionId:re,artifactId:st,markdown:it,jsonPayload:lt}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(it):re==="json"||re==="source"?await navigator.clipboard.writeText(lt):await navigator.clipboard.writeText(it||lt)}catch{}},anchor:D!=null?D:M,position:"bottom-right",portal:te()})};f.isConnected?ee():requestAnimationFrame(ee),M.addEventListener("click",re=>{re.stopPropagation(),z==null||z.toggle()})}j.addEventListener("click",async()=>{var te;try{await((te=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:te.call(t))}catch{}ae()}),oe.addEventListener("click",()=>{var te;g(),(te=e.onDismiss)==null||te.call(e)});let ve=()=>{o&&(k.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};k.addEventListener("click",()=>{x="rendered",ve(),ae()}),L.addEventListener("click",()=>{x="source",ve(),ae()});let Be=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),E.append(k,L),D?F.append(D,j,oe):F.append(N,j,oe),u.append(E,Be,F),ve()):(u.appendChild(m),u.appendChild(v)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let Oe=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Te=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Oe.style.paddingLeft=s,Oe.style.paddingRight=s,Te.style.padding=s),f.appendChild(u),f.appendChild(Oe),f.appendChild(Te);let we=[],se=null,Q=!1,ae=()=>{var it,lt,st,Ee;let te=o&&we.length<=1;Oe.classList.toggle("persona-hidden",te),Oe.replaceChildren();for(let he of we){let Je=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Je.type="button",Je.textContent=he.title||he.id.slice(0,8),he.id===se&&Je.classList.add("persona-bg-persona-container","persona-border-persona-border"),Je.addEventListener("click",()=>e.onSelect(he.id)),Oe.appendChild(Je)}Te.replaceChildren();let ee=se&&we.find(he=>he.id===se)||we[we.length-1];if(!ee)return;if(o){let he=ee.artifactType==="markdown"?"MD":(it=ee.component)!=null?it:"Component",Y=(ee.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Be.textContent=`${Y} \xB7 ${he}`}else m.textContent="Artifacts";if(ee.artifactType==="markdown"){if(o&&x==="source"){let Je=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Je.textContent=(lt=ee.markdown)!=null?lt:"",Te.appendChild(Je);return}let he=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");he.innerHTML=d((st=ee.markdown)!=null?st:""),Te.appendChild(he);return}let re=ee.component?Vo.get(ee.component):void 0;if(re){let Je={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Y=re((Ee=ee.props)!=null?Ee:{},Je);if(Y){Te.appendChild(Y);return}}catch{}}Te.appendChild(Jh(ee))},fe=()=>{var ee;let te=we.length>0;if(f.classList.toggle("persona-hidden",!te),c){let re=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,lt=((ee=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?ee:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;te&&lt&&Q?(c.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:c,update(te){var ee,re,it;we=te.artifacts,se=(it=(re=te.selectedId)!=null?re:(ee=te.artifacts[te.artifacts.length-1])==null?void 0:ee.id)!=null?it:null,we.length>0&&(Q=!0),ae(),fe()},setMobileOpen(te){Q=te,!te&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):fe()}}}function ur(n){var e,t;return((t=(e=n==null?void 0:n.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function Hm(n,e){var s,a,i,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!ur(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function Yh(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ei(n,e){var d,c,g,f,u,m,v,x,E,k;if(!ur(e)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),Yh(n),Hm(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(g=t==null?void 0:t.splitGap)!=null?g:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(u=t==null?void 0:t.paneMaxWidth)!=null?u:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(k=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:k.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Hm(n,e)}var Bm=["panel","seamless"];function ki(n,e){var i,d,c,g,f,u;for(let m of Bm)n.classList.remove(`persona-artifact-appearance-${m}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!ur(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=Bm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((u=t.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Dm(n,e){var t,r,o;return!e||!ur(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Zh(n,e){if(!(n!=null&&n.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):e}function ey(n){if(!(n!=null&&n.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):null}function ty(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function ny(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Nm(n,e){var a;let r=(a=(e.getComputedStyle(n).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Fm(n,e,t,r,o,s){let a=Zh(o,200),i=ny(e,t,r,200);i=Math.max(a,i);let d=ey(s);return d!==null&&(i=Math.min(i,d)),ty(n,a,i)}var Om={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"}},vl=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Om[a])!=null?x:Om.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let k=b("p","persona-text-sm persona-text-persona-muted");k.textContent=i.description,d.appendChild(k)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(k=>{var A,W;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${e.id}-${a}-${k.name}`;let F=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=k.label,L.appendChild(F);let I=(A=k.type)!=null?A:"text",R;I==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=I),R.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",R.id=`${e.id}-${a}-${k.name}`,R.name=k.name,R.placeholder=(W=k.placeholder)!=null?W:"",k.required&&(R.required=!0),L.appendChild(R),g.appendChild(L)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",f.appendChild(u),f.appendChild(m),g.appendChild(f),s.replaceChildren(d,g),g.addEventListener("submit",async k=>{var R,A;k.preventDefault();let L=(R=t.formEndpoint)!=null?R:"/form",F=new FormData(g),I={};F.forEach((W,D)=>{I[D]=W}),I.type=a,m.disabled=!0,u.textContent="Submitting\u2026";try{let W=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let D=await W.json();u.textContent=(A=D.message)!=null?A:"Thanks! We'll be in touch soon.",D.success&&D.nextPrompt&&await r.sendMessage(String(D.nextPrompt))}catch(W){u.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var xl=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var r;let t=this.plugins.get(e);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let r=new Set(e.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},wl=new xl;var _m=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:e,off:t,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ry=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},oy=n=>{let e=n.trim(),t=e.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(t,o+1)}return null},Al=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=ry(n),t=oy(e);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Cl=n=>typeof n=="string"?n:n==null?"":String(n),va={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Cl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=Cl(t.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Cl(t.text)}}},$m=n=>Array.isArray(n)?n.map(e=>String(e)):[],Sl=n=>{let e=new Set($m(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set($m(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,g)=>c||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let g=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:t}};var sy=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},ay=n=>n.map(e=>({...e,streaming:!1})),iy=n=>n.map(e=>({...e,status:"complete"})),qm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?sy(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?ay(t.messages):void 0,artifacts:t.artifacts?iy(t.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Tl=require("partial-json");function Um(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Vo.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(n.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,i),null}}function zm(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let e=n.content.trim();if(e.startsWith("{")||e.startsWith("["))return n.content}return null}function jm(n){let e=zm(n);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Vm(n){let e=zm(n);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var ly=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Km(n){let{onSubmit:e,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=ly}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),u.appendChild(m);let 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 k=[];for(let A=1;A<=5;A++){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",`${A} star${A>1?"s":""}: ${c[A-1]}`),W.title=c[A-1],W.dataset.rating=String(A),W.innerHTML=`
25
+ `,e.addEventListener("click",t);let r=s=>{var B,I,R,A,L,N,F,k,z,j,re,Ie,Ve;let a=(B=s.launcher)!=null?B:{},i=An(s),d=e.querySelector("[data-role='launcher-title']");if(d){let ve=(I=a.title)!=null?I:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let c=e.querySelector("[data-role='launcher-subtitle']");if(c){let ve=(R=a.subtitle)!=null?R:"Here to help you get answers fast";c.textContent=ve,c.setAttribute("title",ve)}let g=e.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let f=e.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let ve=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=ve,f.style.width=ve,f.innerHTML="",a.agentIconName){let Ne=parseFloat(ve)||24,qe=Se(a.agentIconName,Ne*.6,"var(--persona-text-inverse, #ffffff)",2);qe?(f.appendChild(qe),f.style.display=""):(f.textContent=(L=a.agentIconText)!=null?L:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(N=a.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}let u=e.querySelector("[data-role='launcher-image']");if(u){let ve=(F=a.agentIconSize)!=null?F:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let m=e.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ve=(k=a.callToActionIconSize)!=null?k:"32px";m.style.height=ve,m.style.width=ve,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Ne=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Ne=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let qe=parseFloat(ve)||24,Te=Math.max(qe-Ne,8),we=Se(a.callToActionIconName,Te,"currentColor",2);we?m.appendChild(we):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}let v=a.position&&xr[a.position]?xr[a.position]:xr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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";e.className=i?E:`${x} ${v}`,i||(e.style.zIndex=String((re=a.zIndex)!=null?re:In));let M="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";e.style.border=(Ie=a.border)!=null?Ie:M,e.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:S,i?(e.style.width="0",e.style.minWidth="0",e.style.maxWidth="0",e.style.padding="0",e.style.overflow="hidden",e.style.border="none",e.style.boxShadow="none"):(e.style.width="",e.style.minWidth="",e.style.maxWidth=(Ve=a.collapsedMaxWidth)!=null?Ve:"",e.style.justifyContent="",e.style.padding="",e.style.overflow="")},o=()=>{e.removeEventListener("click",t),e.remove()};return n&&r(n),{element:e,update:r,destroy:o}};var xm=({config:n,showClose:t})=>{let{wrapper:e,panel:r,pillRoot:o}=ym(n),s=vm(n,t),a={wrapper:e,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:u=>(d.element.replaceWith(u.header),d.element=u.header,d.iconHolder=u.iconHolder,d.headerTitle=u.headerTitle,d.headerSubtitle=u.headerSubtitle,d.closeButton=u.closeButton,d.closeButtonWrapper=u.closeButtonWrapper,d.clearChatButton=u.clearChatButton,d.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{c.footer.replaceWith(u),c.footer=u}}},ul=({config:n,plugins:t,onToggle:e})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>pl(n,e).element,onToggle:e});if(s)return{instance:null,element:s}}let o=pl(n,e);return{instance:o,element:o.element}};var ch=n=>{switch(n){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},dh=(n,t)=>{if(!n)return null;let e=ch(n);if(e===null)return null;let r=t==null?void 0:t[n],o=r!==void 0?r:e;return o||null},ph=(n,t)=>{let e=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return e.setAttribute("data-stop-reason",n),e.setAttribute("role","note"),e.style.opacity="0.75",e.textContent=t,e},uh=n=>{let t=n.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||t.startsWith("data:image/")||!n.includes(":"))},ml=n=>{let t=n.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||t.startsWith("data:")||!n.includes(":"))},gl=320,Cm=320,mh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),gh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),fh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),hh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),bh=(n,t,e)=>{if(n.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),e==null||e())};return n.forEach((i,d)=>{var f;let c=y("img");c.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${gl}px`,c.style.maxHeight=`${Cm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),uh(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return e==null||e(),null}},yh=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let e=0;return n.forEach(r=>{if(!ml(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=`${gl}px`,t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},vh=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let e=0;return n.forEach(r=>{if(!ml(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=`${gl}px`,o.style.maxHeight=`${Cm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},xh=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let e=0;return n.forEach(r=>{if(!ml(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},ga=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",n.appendChild(t),n.appendChild(e),n.appendChild(r),n.appendChild(o),n},wh=(n,t,e)=>{let r={config:e!=null?e:{},streaming:!0,location:n,defaultRenderer:ga};if(t){let o=t(r);if(o!==null)return o}return ga()},Ch=(n,t)=>{let e=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",e.appendChild(o)}else e.textContent=r,e.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else e.textContent=t==="user"?"U":"A",e.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return e},wm=(n,t,e="div")=>{let r=y(e,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Ah=(n,t="bubble")=>{let e=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):e.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":e.push("persona-text-sm","persona-leading-relaxed"),n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):e.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:e.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):e.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return e},Sh=(n,t,e)=>{var v,x,E,M,S,B,I;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(E=t.showDownvote)!=null?E:!0,a=(M=t.showReadAloud)!=null?M:!1;if(!r&&!o&&!s&&!a){let R=y("div");return R.style.display="none",R.id=`actions-${n.id}`,R.setAttribute("data-actions-for",n.id),R}let i=(S=t.visibility)!=null?S:"hover",d=(B=t.align)!=null?B:"right",c=(I=t.layout)!=null?I:"pill-inside",g={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],u=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${g} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${n.id}`,u.setAttribute("data-actions-for",n.id);let m=(R,A,L)=>{let N=Pn({icon:R,label:A,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",L),N};return r&&u.appendChild(m("copy","Copy message","copy")),a&&u.appendChild(m("volume-2","Read aloud","read-aloud")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},fl=(n,t,e,r,o,s)=>{var oe,X,se,fe,pe,K,ae,Be,ee,Z,ne,st,at,nt,Me,he,Ge;let a=e!=null?e:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,g=(X=d==null?void 0:d.show)!=null?X:!1,f=(se=c==null?void 0:c.show)!=null?se:!1,u=(fe=d==null?void 0:d.position)!=null?fe:"left",m=(pe=c==null?void 0:c.position)!=null?pe:"below",v=Ah(n.role,i),x=y("div",v.join(" "));x.id=`bubble-${n.id}`,x.setAttribute("data-message-id",n.id),x.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=mh(n),M=(ae=(K=n.content)==null?void 0:K.trim())!=null?ae:"",B=E.length>0&&M===ei,I=mi((ee=(Be=s==null?void 0:s.widgetConfig)==null?void 0:Be.features)==null?void 0:ee.streamAnimation),R=(st=(ne=(Z=s==null?void 0:s.widgetConfig)==null?void 0:Z.features)==null?void 0:ne.streamAnimation)==null?void 0:st.plugins,A=n.role==="assistant"&&I.type!=="none"?ia(I.type,R):null,L=n.role==="assistant"&&((at=A==null?void 0:A.isAnimating)==null?void 0:at.call(A,n))===!0,N=n.role==="assistant"&&A!==null&&(!!n.streaming||L);N&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),N&&A&&(A.containerClass&&F.classList.add(A.containerClass),F.style.setProperty("--persona-stream-step",`${I.speed}ms`),F.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let k=N?gi((nt=n.content)!=null?nt:"",I.buffer,A,n,!!n.streaming):(Me=n.content)!=null?Me:"",z=t({text:k,message:n,streaming:!!n.streaming,raw:n.rawContent}),j=z;N&&(A==null?void 0:A.wrap)==="char"?j=la(z,"char",n.id,{skipTags:A.skipTags}):N&&(A==null?void 0:A.wrap)==="word"&&(j=la(z,"word",n.id,{skipTags:A.skipTags}));let re=null;if(B?(re=document.createElement("div"),re.innerHTML=j,re.style.display="none",F.appendChild(re)):F.innerHTML=j,N&&(A!=null&&A.useCaret)&&!B&&M){let J=fi(),ue=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Le=ue[ue.length-1];if(Le!=null&&Le.parentNode)Le.parentNode.insertBefore(J,Le.nextSibling);else{let Xe=F.lastElementChild;Xe?Xe.appendChild(J):F.appendChild(J)}}if(f&&m==="inline"&&n.createdAt){let J=wm(n,c,"span");J.classList.add("persona-timestamp-inline");let ue=F.lastElementChild;ue?ue.appendChild(J):F.appendChild(J)}if(E.length>0){let J=bh(E,!B&&!!M,()=>{B&&re&&(re.style.display="")});J?x.appendChild(J):B&&re&&(re.style.display="")}let Ie=gh(n);if(Ie.length>0){let J=yh(Ie);J&&x.appendChild(J)}let Ve=fh(n);if(Ve.length>0){let J=vh(Ve);J&&x.appendChild(J)}let ve=hh(n);if(ve.length>0){let J=xh(ve);J&&x.appendChild(J)}if(x.appendChild(F),f&&m==="below"&&n.createdAt){let J=wm(n,c);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ne=n.role==="assistant"?dh(n.stopReason,(Ge=(he=s==null?void 0:s.widgetConfig)==null?void 0:he.copy)==null?void 0:Ge.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let J=!!(k&&k.trim()),ue=I.placeholder==="skeleton",Le=ue&&I.buffer==="line"&&J;if(J)Le&&x.appendChild(ca());else if(ue)x.appendChild(ca());else{let Xe=wh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Xe&&x.appendChild(Xe)}}if(Ne&&n.stopReason&&!n.streaming&&(M||(F.style.display="none"),x.appendChild(ph(n.stopReason,Ne))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Sh(n,r,o);x.appendChild(J)}if(!g||n.role==="system")return x;let Te=y("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),we=Ch(d,n.role);return u==="right"||u==="left"&&n.role==="user"?Te.append(x,we):Te.append(we,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te};var ws=new Set,Th=(n,t)=>t==null?!1:typeof t=="string"?(n.textContent=t,!0):(n.appendChild(t),!0),Eh=(n,t)=>{var r,o;let e=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return e?e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},Am=(n,t)=>{let e=ws.has(n),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",e?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=Se(e?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=e?"Hide":"Show"}o.style.display=e?"":"none",s&&(s.style.display=e?"none":s.textContent||s.childNodes.length?"":"none")},hl=(n,t)=>{var Ve,ve,Ne,qe,Te,we,oe,X,se,fe,pe;let e=n.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!e)return r;let o=(ve=(Ve=t==null?void 0:t.features)==null?void 0:Ve.reasoningDisplay)!=null?ve:{},s=o.expandable!==!1,a=s&&ws.has(n.id),i=e.status!=="complete",d=Eh(n,(Ne=o.previewMaxLines)!=null?Ne:3),c=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(qe=t==null?void 0:t.reasoning)!=null?qe:{},v=String((Te=e.startedAt)!=null?Te:Date.now()),x=()=>{let K=y("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Ga(e),K},E=(we=m.renderCollapsedSummary)==null?void 0:we.call(m,{message:n,reasoning:e,defaultSummary:u,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ga(e),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=u,g.appendChild(f));let M=y("span","persona-text-xs persona-text-persona-primary");M.textContent=wu(e),g.appendChild(M);let S=(oe=o.loadingAnimation)!=null?oe:"none",B=m.activeTextTemplate,I=m.completeTextTemplate,R=i?B:I,A=E instanceof HTMLElement,L=(K,ae,Be)=>{let ee=Be;for(let Z of ae){let ne=y("span","persona-tool-char");ne.style.setProperty("--char-index",String(ee)),ne.textContent=Z===" "?"\xA0":Z,K.appendChild(ne),ee++}return ee},N=(K,ae)=>{f.textContent="";let Be=Qa(K,""),ee=0;for(let Z of Be){let ne=Z.styles.length>0?(()=>{let st=y("span",Z.styles.map(at=>`persona-tool-text-${at}`).join(" "));return f.appendChild(st),st})():f;if(Z.isDuration&&i)ne.appendChild(x());else{let st=Z.isDuration?Ga(e):Z.text;ae?ee=L(ne,st,ee):ne.appendChild(document.createTextNode(st))}}};if(!A&&R)if(M.style.display="none",f.style.display="",i&&S!=="none"){let K=(X=m.loadingAnimationDuration)!=null?X:2e3;f.setAttribute("data-preserve-animation","true"),S==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),N(R,!1)):(f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),N(R,!0))}else N(R,!1);else if(!A&&i&&S!=="none"){f.style.display="";let K=(se=m.loadingAnimationDuration)!=null?se:2e3;if(f.setAttribute("data-preserve-animation","true"),S==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ae=f.textContent||u;f.textContent="",L(f,ae,0)}e.status==="complete"&&(f.style.display="none")}else A||(e.status==="complete"?f.style.display="none":f.style.display="");let F=null;if(s){F=y("div","persona-flex persona-items-center");let ae=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?F.appendChild(ae):F.textContent=a?"Hide":"Show";let Be=y("div","persona-flex persona-items-center persona-ml-auto");Be.append(F),c.append(g,Be)}else c.append(g);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&&o.activePreview&&d){let K=(pe=(fe=t==null?void 0:t.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:pe.call(fe,{message:n,reasoning:e,defaultPreview:d,isActive:i,config:t!=null?t:{}});Th(k,K)||(k.textContent=d),k.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,k),r;let z=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");z.style.display=a?"":"none";let j=e.chunks.join(""),re=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return re.textContent=j||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),z.appendChild(re),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),F){F.innerHTML="";let ae=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?F.appendChild(ae):F.textContent=a?"Hide":"Show"}z.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,z),r};var Cs=new Set,Mh=(n,t)=>t==null?!1:typeof t=="string"?(n.textContent=t,!0):(n.appendChild(t),!0),kh=(n,t)=>{var s;let e=n.toolCall;if(!e)return"";let r=((s=e.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
27
+ `);let o=gs(e.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
28
+ `):""},Lh=(n,t)=>{var g,f,u,m,v;let e=n.toolCall,r=(g=t==null?void 0:t.features)==null?void 0:g.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=kh(n,(u=r==null?void 0:r.previewMaxLines)!=null?u:3),a=e?Cu(e):"";if(!e)return{summary:a,previewText:s,isActive:!1};let i=e.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((v=e.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Ji(e,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Ji(e,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Sm=(n,t,e)=>{var g;let r=Cs.has(n),o=(g=e==null?void 0:e.toolCall)!=null?g:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"currentColor",u=Se(r?"chevron-up":"chevron-down",16,f,2);u?c.appendChild(u):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},bl=(n,t)=>{var j,re,Ie,Ve,ve,Ne,qe,Te,we;let e=n.toolCall,r=(j=t==null?void 0:t.toolCall)!=null?j:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!e)return o;let s=(Ie=(re=t==null?void 0:t.features)==null?void 0:re.toolCallDisplay)!=null?Ie:{},a=s.expandable!==!1,i=a&&Cs.has(n.id),{summary:d,previewText:c,isActive:g}=Lh(n,t),f=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let u=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((Ve=e.startedAt)!=null?Ve:Date.now()),x=()=>{let oe=y("span","");return oe.setAttribute("data-tool-elapsed",v),oe.textContent=Js(e),oe},E=(Ne=r.renderCollapsedSummary)==null?void 0:Ne.call(r,{message:n,toolCall:e,defaultSummary:d,previewText:c,collapsedMode:(ve=s.collapsedMode)!=null?ve:"tool-call",isActive:g,config:t!=null?t:{},elapsed:Js(e),createElapsedElement:x});typeof E=="string"&&E.trim()?(m.textContent=E,u.appendChild(m)):E instanceof HTMLElement?u.appendChild(E):(m.textContent=d,u.appendChild(m));let M=(qe=s.loadingAnimation)!=null?qe:"none",S=r.activeTextTemplate,B=r.completeTextTemplate,I=g?S:B,R=E instanceof HTMLElement,A=(oe,X,se)=>{let fe=se;for(let pe of X){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(fe)),K.textContent=pe===" "?"\xA0":pe,oe.appendChild(K),fe++}return fe},L=(oe,X)=>{var K;m.textContent="";let se=((K=e.name)==null?void 0:K.trim())||"tool",fe=Qa(oe,se),pe=0;for(let ae of fe){let Be=ae.styles.length>0?(()=>{let ee=y("span",ae.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(ee),ee})():m;if(ae.isDuration&&g)Be.appendChild(x());else{let ee=ae.isDuration?Js(e):ae.text;X?pe=A(Be,ee,pe):Be.appendChild(document.createTextNode(ee))}}};if(!R)if(g&&M!=="none"){let oe=(Te=r.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),I&&L(I,!1);else if(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),M==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),I)L(I,!0);else{let X=m.textContent||d;m.textContent="",A(m,X,0)}}else I&&L(I,!1);let N=null;if(a){N=y("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"currentColor",X=Se(i?"chevron-up":"chevron-down",16,oe,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show";let se=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(N),f.append(u,se)}else f.append(u);let F=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!i&&g&&s.activePreview&&c){let oe=(we=r.renderCollapsedPreview)==null?void 0:we.call(r,{message:n,toolCall:e,defaultPreview:c,isActive:g,config:t!=null?t:{}});Mh(F,oe)||(F.textContent=c),F.style.display=""}if(!i&&g&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,F),o;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),e.name){let oe=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?oe.style.color=r.contentTextColor:r.headerTextColor&&(oe.style.color=r.headerTextColor),oe.textContent=e.name,k.appendChild(oe)}if(e.args!==void 0){let oe=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=gs(e.args),oe.append(X,se),k.appendChild(oe)}if(e.chunks&&e.chunks.length){let oe=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=e.chunks.join(""),oe.append(X,se),k.appendChild(oe)}if(e.status==="complete"&&e.result!==void 0){let oe=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=gs(e.result),oe.append(X,se),k.appendChild(oe)}if(e.status==="complete"&&typeof e.duration=="number"){let oe=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${e.duration}ms`,k.appendChild(oe)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"currentColor",X=Se(i?"chevron-up":"chevron-down",16,oe,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",F.style.display=i?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(f,F,k),o};var Ei=new Map,Ih=n=>{let e=(n.startsWith(No)?n.slice(No.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(e.length===0)return n;let r=e.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Tm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Em=(n,t)=>{var r,o,s;let e=(o=(r=Tm(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ei.get(n))!=null?s:e==="expanded"},Mm=(n,t,e)=>{var a,i;let r=Tm(e);n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Se(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},km=(n,t,e)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Em(n,e);Mm(r,s,e),o.style.display=s?"":"none"};var Mi=(n,t)=>{var L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we,oe;let e=n.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(e==null?void 0:e.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(L=r==null?void 0:r.backgroundColor)!=null?L:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(N=r==null?void 0:r.borderColor)!=null?N:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!e)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=e.status==="denied"?"shield-x":e.status==="timeout"?"shield-alert":"shield-check",c=e.status==="approved"?"var(--persona-feedback-success, #16a34a)":e.status==="denied"?"var(--persona-feedback-error, #dc2626)":e.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(F=r==null?void 0:r.titleColor)!=null?F:"currentColor",g=Se(d,20,c,2);g&&i.appendChild(g);let f=y("div","persona-flex-1 persona-min-w-0"),u=y("div","persona-flex persona-items-center persona-gap-2"),m=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",u.appendChild(m),!o){let X=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",e.status),e.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):e.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):e.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),u.appendChild(X)}f.appendChild(u);let x=e.toolType==="webmcp"||e.toolName.startsWith(No)?Oi(e.toolName):void 0,E=(z=r==null?void 0:r.formatDescription)==null?void 0:z.call(r,{toolName:e.toolName,toolType:e.toolType,description:e.description,parameters:e.parameters,...x?{displayTitle:x}:{},...e.reason?{reason:e.reason}:{}}),M=!e.toolName,S=E||(M?e.description:`The assistant wants to use \u201C${x!=null?x:Ih(e.toolName)}\u201D.`),B=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(B.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(B.style.color=r.descriptionColor),B.textContent=S,f.appendChild(B),e.reason){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?X.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor);let se=y("span","persona-font-medium");se.textContent=`${(j=r==null?void 0:r.reasonLabel)!=null?j:"Agent's stated reason:"} `,X.appendChild(se),X.appendChild(document.createTextNode(e.reason)),f.appendChild(X)}let I=(re=r==null?void 0:r.detailsDisplay)!=null?re:"collapsed",R=!!e.description&&!M,A=R||!!e.parameters;if(I!=="hidden"&&A){let X=Em(n.id,t),se=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");se.type="button",se.setAttribute("data-expand-header","true"),se.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let fe=y("span");fe.setAttribute("data-approval-details-label","true");let pe=y("span","persona-inline-flex persona-items-center");pe.setAttribute("data-approval-details-chevron","true"),se.append(fe,pe),Mm(se,X,t),f.appendChild(se);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=X?"":"none",R){let ae=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor),ae.textContent=e.description,K.appendChild(ae)}if(e.parameters){let ae=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&&(ae.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ae.style.color=r.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=gs(e.parameters),K.appendChild(ae)}f.appendChild(K)}if(o){let X=y("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let se=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");se.type="button",se.style.backgroundColor=(Ie=r==null?void 0:r.approveButtonColor)!=null?Ie:"var(--persona-approval-approve-bg, #22c55e)",se.style.color=(Ve=r==null?void 0:r.approveButtonTextColor)!=null?Ve:"#ffffff",se.setAttribute("data-approval-action","approve");let fe=Se("shield-check",14,(ve=r==null?void 0:r.approveButtonTextColor)!=null?ve:"#ffffff",2);fe&&(fe.style.marginRight="4px",se.appendChild(fe));let pe=document.createTextNode((Ne=r==null?void 0:r.approveLabel)!=null?Ne:"Approve");se.appendChild(pe);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=(qe=r==null?void 0:r.denyButtonColor)!=null?qe:"transparent",K.style.color=(Te=r==null?void 0:r.denyButtonTextColor)!=null?Te:"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 ae=Se("shield-x",14,(we=r==null?void 0:r.denyButtonTextColor)!=null?we:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",K.appendChild(ae));let Be=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");K.appendChild(Be),X.append(se,K),f.appendChild(X)}return a.append(i,f),s.appendChild(a),s};var Lm=n=>{let t=[],e=null;return{buttons:t,render:(o,s,a,i,d,c)=>{n.innerHTML="",t.length=0;let g=(c==null?void 0:c.agentPushed)===!0;if(g||(e=null),!o||!o.length||!g&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let f=document.createDocumentFragment(),u=s?s.isStreaming():!1,m=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(v=>{let x=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=u,d!=null&&d.fontFamily&&(x.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",g&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),t.push(x)}),n.appendChild(f),g){let v=JSON.stringify(o);v!==e&&(e=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var fa=class{constructor(t=2e3,e=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=e}push(t){var e;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(e=this.store)==null||e.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let e=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of e)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,e.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let e=this.getAll();return t>=e.length?e:e.slice(e.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ha=class{constructor(t="persona-event-stream",e="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=e}open(){return new Promise((t,e)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{e(r.error)}}catch(r){e(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,e)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{e(a.error)}}catch(r){e(r)}})}getCount(){return new Promise((t,e)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{e(s.error)}}catch(r){e(r)}})}clear(){return new Promise((t,e)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{e(s.error)}}catch(r){e(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,e)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{e(r.error)}}catch(r){e(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var Ph=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Wh=new Set(["step_start","execution_start"]),Rh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Bh=new Set(["step_complete","agent_turn_complete"]),Hh=new Set(["flow_complete","agent_complete"]),Im=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),nr=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,jo=(n,t)=>{let e=n[t];return Wm(e)?e:void 0};function yl(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function ki(n,t){if(!(n<=0||t===void 0||t<250))return n/(t/1e3)}function Dh(n,t){return typeof t.type=="string"?t.type:n}function Nh(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function Fh(n,t){return n==="step_delta"||n==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Pm(n){var r,o,s,a,i;let t=jo(n,"result"),e=[jo(n,"tokens"),jo(n,"totalTokens"),t?jo(t,"tokens"):void 0,jo(n,"usage"),t?jo(t,"usage"):void 0];for(let d of e){if(!d)continue;let c=(o=(r=nr(d.output))!=null?r:nr(d.outputTokens))!=null?o:nr(d.completionTokens);if(c!==void 0)return c}return(i=(s=nr(n.outputTokens))!=null?s:nr(n.completionTokens))!=null?i:t?(a=nr(t.outputTokens))!=null?a:nr(t.completionTokens):void 0}function _h(n){var e,r,o,s,a;let t=jo(n,"result");return(a=(o=(r=(e=nr(n.executionTime))!=null?e:nr(n.executionTimeMs))!=null?r:nr(n.execution_time))!=null?o:nr(n.duration))!=null?a:t?(s=nr(t.executionTime))!=null?s:nr(t.executionTimeMs):void 0}function Oh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ba=class{constructor(t=Oh){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let e=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:e,tokensPerSecond:ki(this.metric.outputTokens,e)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,e){var s;if(!Wm(e)){Im.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Dh(t,e),o=this.now();if(Ph.has(r)){this.startRun(o);return}if(Wh.has(r)){this.run||this.startRun(o);return}if(Rh.has(r)){if(!Fh(r,e))return;let a=Nh(e);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+yl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ki(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Bh.has(r)){if(!this.run)return;let a=this.run,i=Pm(e);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+yl(a.visibleCharCount),g=this.resolveDuration(a,e,o);this.metric={status:"running",tokensPerSecond:ki(c,g),outputTokens:c,durationMs:g,source:d?"usage":"estimate"};return}if(Hh.has(r)){if(!this.run)return;let a=this.run,i=Pm(e),d=i!=null?i:a.exactOutputTokens+yl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",g=this.resolveDuration(a,e,o);this.metric={status:"complete",tokensPerSecond:ki(d,g),outputTokens:d,durationMs:g,source:c},this.run=null;return}if(Im.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,e,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=_h(e);return s!=null?s:r-t.startedAt}};function As(n,t){t&&t.split(/\s+/).forEach(e=>e&&n.classList.add(e))}var $h={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)"}},qh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Uh=["flowName","stepName","reasoningText","text","name","tool","toolName"],zh=100;function jh(n,t){let e={...$h,...t};if(e[n])return e[n];for(let r of Object.keys(e))if(r.endsWith("_")&&n.startsWith(r))return e[r];return qh}function Vh(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function Kh(n){let t=new Date(n),e=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${e}:${r}:${o}.${s}`}function Gh(n,t){try{let e=JSON.parse(n);if(typeof e!="object"||e===null)return null;for(let r of t){let o=r.split("."),s=e;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Qh(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(e=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),e()})}function Xh(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function Jh(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Yh(n){let t=[];return n.outputTokens!==void 0&&t.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&t.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&t.push(n.source),t.join(" \xB7 ")}function Zh(n,t,e){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&e){let i=s.renderEventStreamPayload({event:n,config:e,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function vl(n,t,e,r,o,s,a,i){var u;let d=o.has(n.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");As(c,(u=r.classNames)==null?void 0:u.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:n,index:t,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var j,re;let m=y("div",""),v=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",n.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Se(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let M=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(j=r.timestampFormat)!=null?j:"relative";M.textContent=S==="relative"?Vh(n.timestamp,e):Kh(n.timestamp);let B=null;r.showSequenceNumbers!==!1&&(B=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),B.textContent=String(t+1));let I=jh(n.type,r.badgeColors),R=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");R.style.backgroundColor=I.bg,R.style.color=I.text,R.style.borderColor=I.text+"50",R.textContent=n.type;let A=(re=r.descriptionFields)!=null?re:Uh,L=Gh(n.payload,A),N=null;L&&(N=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=L);let F=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"),z=Se("clipboard","12px","currentColor",1.5);return z&&k.appendChild(z),k.addEventListener("click",async Ie=>{Ie.stopPropagation(),await Qh(Xh(n)),k.innerHTML="";let Ve=Se("check","12px","currentColor",1.5);Ve&&k.appendChild(Ve),setTimeout(()=>{k.innerHTML="";let ve=Se("clipboard","12px","currentColor",1.5);ve&&k.appendChild(ve)},1500)}),v.appendChild(x),v.appendChild(M),B&&v.appendChild(B),v.appendChild(R),N&&v.appendChild(N),v.appendChild(F),v.appendChild(k),m.appendChild(v),d&&m.appendChild(Zh(n,a,i)),m}}function Rm(n){var v,x,E,M,S;let{buffer:t,getFullHistory:e,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",g=(E=i==null?void 0:i.label)!=null?E:"",f=(S=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?S:{},u=s.find(B=>B.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let B=u.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(B)return{element:B,update:()=>{},destroy:()=>{}}}return m();function m(){let B=f.classNames,I=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");As(I,B==null?void 0:B.panel);let R=[],A="",L="",N=null,F=[],k={},z=0,j=di(),re=0,Ie=0,Ve=!1,ve=null,Ne=!1,qe=0,Te=new Set,we=new Map,oe="",X="",se=null,fe,pe,K,ae,Be,ee=null,Z=null,ne=null;function st(){let de=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),me=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");As(me,B==null?void 0:B.headerBar);let Ee=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ee.textContent="Events",fe=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"),fe.textContent="0",a){Z=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let rr=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");rr.textContent="Throughput",ee=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"),ee.textContent="-- tok/s",ne=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"),ne.style.display="none",ne.style.pointerEvents="none";let Wn=Z,ln=ne,On=()=>{if(!ln.textContent)return;let Ct=Wn.getBoundingClientRect(),jn=de.getBoundingClientRect();ln.style.left=`${Ct.left-jn.left}px`,ln.style.top=`${Ct.bottom-jn.top+4}px`,ln.style.display="block"},Cr=()=>{ln.style.display="none"};Z.addEventListener("mouseenter",On),Z.addEventListener("mouseleave",Cr),Z.appendChild(rr),Z.appendChild(ee)}let ut=y("div","persona-flex-1");pe=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 en=y("option","");en.value="",en.textContent="All events",pe.appendChild(en),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 wn=Se("clipboard-copy","12px","currentColor",1.5);wn&&K.appendChild(wn);let Ot=y("span","persona-text-xs");Ot.textContent="Copy All",K.appendChild(Ot),me.appendChild(Ee),me.appendChild(fe),Z&&me.appendChild(Z),me.appendChild(ut),me.appendChild(pe),me.appendChild(K);let et=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");As(et,B==null?void 0:B.searchBar);let _t=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),mt=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");_t&&mt.appendChild(_t),ae=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"),As(ae,B==null?void 0:B.searchInput),ae.type="text",ae.placeholder="Search event payloads...",Be=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Be.type="button",Be.style.display="none";let tn=Se("x","12px","currentColor",2);return tn&&Be.appendChild(tn),et.appendChild(mt),et.appendChild(ae),et.appendChild(Be),de.appendChild(me),de.appendChild(et),ne&&de.appendChild(ne),de}let at,nt=s.find(de=>de.renderEventStreamToolbar);if(nt!=null&&nt.renderEventStreamToolbar&&o){let de=nt.renderEventStreamToolbar({config:o,defaultRenderer:()=>st(),eventCount:t.getSize(),filteredCount:0,onFilterChange:me=>{A=me,Nt(),Sn()},onSearchChange:me=>{L=me,Nt(),Sn()}});at=de!=null?de:st()}else at=st();let Me=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");Me.style.display="none";function he(){if(!a||!ee||!Z)return;let de=a();ee.textContent=Jh(de);let me=Yh(de);ne&&(ne.textContent=me,me||(ne.style.display="none")),me?Z.setAttribute("aria-label",me):Z.removeAttribute("aria-label")}let Ge=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 ue=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");As(ue,B==null?void 0:B.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",g?"true":"false");let Le=Se(c,"14px","currentColor",2);Le&&ue.appendChild(Le);let Xe=y("span","");Xe.textContent=g,ue.appendChild(Xe);let Gt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Gt.style.display="none",Ge.appendChild(J),Ge.appendChild(Gt),Ge.appendChild(ue),I.setAttribute("tabindex","0"),I.appendChild(at),I.appendChild(Me),I.appendChild(Ge);function Pe(){let de=t.getAll(),me={};for(let Ot of de)me[Ot.type]=(me[Ot.type]||0)+1;let Ee=Object.keys(me).sort(),ut=Ee.length!==F.length||!Ee.every((Ot,et)=>Ot===F[et]),en=!ut&&Ee.some(Ot=>me[Ot]!==k[Ot]),an=de.length!==Object.values(k).reduce((Ot,et)=>Ot+et,0);if(!ut&&!en&&!an||(F=Ee,k=me,!pe))return;let wn=pe.value;if(pe.options[0].textContent="All events",ut){for(;pe.options.length>1;)pe.remove(1);for(let Ot of Ee){let et=y("option","");et.value=Ot,et.textContent=`${Ot} (${me[Ot]||0})`,pe.appendChild(et)}wn&&Ee.includes(wn)?pe.value=wn:wn&&(pe.value="",A="")}else for(let Ot=1;Ot<pe.options.length;Ot++){let et=pe.options[Ot];et.textContent=`${et.value} (${me[et.value]||0})`}}function Ue(){let de=t.getAll();if(A&&(de=de.filter(me=>me.type===A)),L){let me=L.toLowerCase();de=de.filter(Ee=>Ee.type.toLowerCase().includes(me)||Ee.payload.toLowerCase().includes(me))}return de}function rt(){return A!==""||L!==""}function Nt(){z=0,re=0,j.resume(),ue.style.display="none"}function yn(de){Te.has(de)?Te.delete(de):Te.add(de),se=de;let me=J.scrollTop,Ee=j.isFollowing();Ne=!0,j.pause(),Sn(),J.scrollTop=me,Ee&&j.resume(),Ne=!1}function wr(){return Uo(J,50)}function Sn(){Ie=Date.now(),Ve=!1,he(),Pe();let de=t.getEvictedCount();de>0?(Me.textContent=`${de.toLocaleString()} older events truncated`,Me.style.display=""):Me.style.display="none",R=Ue();let me=R.length,Ee=t.getSize()>0;fe&&(fe.textContent=String(t.getSize())),me===0&&Ee&&rt()?(Gt.textContent=L?`No events matching '${L}'`:"No events matching filter",Gt.style.display="",J.style.display="none"):(Gt.style.display="none",J.style.display=""),K&&(K.title=rt()?`Copy Filtered (${me})`:"Copy All"),d&&!j.isFollowing()&&me>z&&(re+=me-z,Xe.textContent=g?`${g}${re>0?` (${re})`:""}`:"",ue.style.display=""),z=me;let ut=t.getAll(),en=ut.length>0?ut[0].timestamp:0,an=new Set(R.map(et=>et.id));for(let et of Te)an.has(et)||Te.delete(et);let wn=A!==oe||L!==X,Ot=we.size===0&&R.length>0;if(wn||Ot||R.length===0){J.innerHTML="",we.clear();let et=document.createDocumentFragment();for(let _t=0;_t<R.length;_t++){let mt=vl(R[_t],_t,en,f,Te,yn,s,o);we.set(R[_t].id,mt),et.appendChild(mt)}J.appendChild(et),oe=A,X=L,se=null}else{if(se!==null){let _t=we.get(se);if(_t&&_t.parentNode===J){let mt=R.findIndex(tn=>tn.id===se);if(mt>=0){let tn=vl(R[mt],mt,en,f,Te,yn,s,o);J.insertBefore(tn,_t),_t.remove(),we.set(se,tn)}}se=null}let et=new Set(R.map(_t=>_t.id));for(let[_t,mt]of we)et.has(_t)||(mt.remove(),we.delete(_t));for(let _t=0;_t<R.length;_t++){let mt=R[_t];if(!we.has(mt.id)){let tn=vl(mt,_t,en,f,Te,yn,s,o);we.set(mt.id,tn),J.appendChild(tn)}}}j.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Ke(){if(Date.now()-Ie>=zh){ve!==null&&(cancelAnimationFrame(ve),ve=null),Sn();return}Ve||(Ve=!0,ve=requestAnimationFrame(()=>{ve=null,Sn()}))}let Ft=(de,me)=>{if(!K)return;K.innerHTML="";let Ee=Se(de,"12px","currentColor",1.5);Ee&&K.appendChild(Ee);let ut=y("span","persona-text-xs");ut.textContent="Copy All",K.appendChild(ut),setTimeout(()=>{K.innerHTML="";let en=Se("clipboard-copy","12px","currentColor",1.5);en&&K.appendChild(en);let an=y("span","persona-text-xs");an.textContent="Copy All",K.appendChild(an),K.disabled=!1},me)},q=async()=>{if(K){K.disabled=!0;try{let de;rt()?de=R:e?(de=await e(),de.length===0&&(de=t.getAll())):de=t.getAll();let me=de.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(me,null,2)),Ft("check",1500)}catch{Ft("x",1500)}}},ke=()=>{pe&&(A=pe.value,Nt(),Sn())},Ce=()=>{!ae||!Be||(Be.style.display=ae.value?"":"none",N&&clearTimeout(N),N=setTimeout(()=>{L=ae.value,Nt(),Sn()},150))},_e=()=>{!ae||!Be||(ae.value="",L="",Be.style.display="none",N&&clearTimeout(N),Nt(),Sn())},it=()=>{if(Ne)return;let de=J.scrollTop,{action:me,nextLastScrollTop:Ee}=pi({following:j.isFollowing(),currentScrollTop:de,lastScrollTop:qe,nearBottom:wr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});qe=Ee,me==="resume"?(j.resume(),re=0,ue.style.display="none"):me==="pause"&&(j.pause(),d&&(Xe.textContent=g,ue.style.display=""))},pt=de=>{let me=ui({following:j.isFollowing(),deltaY:de.deltaY,nearBottom:wr(),resumeWhenNearBottom:!0});me==="pause"?(j.pause(),d&&(Xe.textContent=g,ue.style.display="")):me==="resume"&&(j.resume(),re=0,ue.style.display="none")},ot=()=>{d&&(J.scrollTop=J.scrollHeight,j.resume(),re=0,ue.style.display="none")},Mt=de=>{let me=de.target;if(!me||me.closest("button"))return;let Ee=me.closest("[data-event-id]");if(!Ee)return;let ut=Ee.getAttribute("data-event-id");ut&&yn(ut)},V=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}de.key==="Escape"&&(ae&&document.activeElement===ae?(_e(),ae.blur(),I.focus()):r&&r())};K&&K.addEventListener("click",q),pe&&pe.addEventListener("change",ke),ae&&ae.addEventListener("input",Ce),Be&&Be.addEventListener("click",_e),J.addEventListener("scroll",it),J.addEventListener("wheel",pt,{passive:!0}),J.addEventListener("click",Mt),ue.addEventListener("click",ot),I.addEventListener("keydown",V);function St(){N&&clearTimeout(N),ve!==null&&(cancelAnimationFrame(ve),ve=null),Ve=!1,we.clear(),K&&K.removeEventListener("click",q),pe&&pe.removeEventListener("change",ke),ae&&ae.removeEventListener("input",Ce),Be&&Be.removeEventListener("click",_e),J.removeEventListener("scroll",it),J.removeEventListener("wheel",pt),J.removeEventListener("click",Mt),ue.removeEventListener("click",ot),I.removeEventListener("keydown",V)}return{element:I,update:Ke,destroy:St}}}function Bm(n,t){let e=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${e} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=e;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(g,f),i.append(d,c),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${e}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",r),i.append(u)}return i}var Hm=(n,t)=>{var r,o,s;let e=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(e){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",g=e({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Bm(n,t)});if(g)return g}return Bm(n,t)};var xl=class{constructor(){this.components=new Map}register(t,e){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,e)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([e,r])=>{this.register(e,r)})}},Vo=new xl;Vo.register("PersonaArtifactCard",Hm);function eb(n){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),e=y("div","persona-font-semibold persona-text-sm persona-mb-2");e.textContent=n.component?`Component: ${n.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),t.appendChild(e),t.appendChild(r),t}function Dm(n,t){var pe,K,ae,Be;let e=(K=(pe=n.features)==null?void 0:pe.artifacts)==null?void 0:K.layout,o=((ae=e==null?void 0:e.toolbarPreset)!=null?ae:"default")==="document",s=(Be=e==null?void 0:e.panePadding)==null?void 0:Be.trim(),a=n.markdown?Oa(n.markdown):null,i=$a(n.sanitize),d=ee=>{let Z=a?a(ee):ho(ee);return i?i(Z):Z},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var ee;g(),(ee=t.onDismiss)==null||ee.call(t)});let f=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let u=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let m=y("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var ee;g(),(ee=t.onDismiss)==null||ee.call(t)});let x="rendered",E=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Pn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Pn({icon:"eye",label:"Rendered view"}),S=o?Pn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Pn({icon:"code-2",label:"Source"}),B=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(e==null?void 0:e.documentToolbarShowCopyLabel)===!0,R=(e==null?void 0:e.documentToolbarShowCopyChevron)===!0,A=e==null?void 0:e.documentToolbarCopyMenuItems,L=!!(R&&A&&A.length>0),N=null,F,k=null,z=null;if(o&&(I||R)&&!L){if(F=I?dl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let ee=Se("chevron-down",14,"currentColor",2);ee&&F.appendChild(ee)}}else o&&L?(N=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),F=I?dl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Pn({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"}}),N.append(F,k)):o?F=Pn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):F=Pn({icon:"copy",label:"Copy"});let j=o?Pn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pn({icon:"refresh-cw",label:"Refresh"}),re=o?Pn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Pn({icon:"x",label:"Close"}),Ie=()=>{var at,nt,Me;let ee=(at=we.find(he=>he.id===oe))!=null?at:we[we.length-1],Z=(nt=ee==null?void 0:ee.id)!=null?nt:null,ne=(ee==null?void 0:ee.artifactType)==="markdown"&&(Me=ee.markdown)!=null?Me:"",st=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:ne,jsonPayload:st,id:Z}},Ve=async()=>{var at;let{markdown:ee,jsonPayload:Z}=Ie(),ne=(at=we.find(nt=>nt.id===oe))!=null?at:we[we.length-1],st=(ne==null?void 0:ne.artifactType)==="markdown"?ee:ne?Z:"";try{await navigator.clipboard.writeText(st)}catch{}};if(F.addEventListener("click",async()=>{let ee=e==null?void 0:e.onDocumentToolbarCopyMenuSelect;if(ee&&L){let{markdown:Z,jsonPayload:ne,id:st}=Ie();try{await ee({actionId:"primary",artifactId:st,markdown:Z,jsonPayload:ne})}catch{}return}await Ve()}),k&&(A!=null&&A.length)){let ee=()=>{var ne;return(ne=f.closest("[data-persona-root]"))!=null?ne:document.body},Z=()=>{z=xs({items:A.map(ne=>({id:ne.id,label:ne.label})),onSelect:async ne=>{let{markdown:st,jsonPayload:at,id:nt}=Ie(),Me=e==null?void 0:e.onDocumentToolbarCopyMenuSelect;try{Me?await Me({actionId:ne,artifactId:nt,markdown:st,jsonPayload:at}):ne==="markdown"||ne==="md"?await navigator.clipboard.writeText(st):ne==="json"||ne==="source"?await navigator.clipboard.writeText(at):await navigator.clipboard.writeText(st||at)}catch{}},anchor:N!=null?N:k,position:"bottom-right",portal:ee()})};f.isConnected?Z():requestAnimationFrame(Z),k.addEventListener("click",ne=>{ne.stopPropagation(),z==null||z.toggle()})}j.addEventListener("click",async()=>{var ee;try{await((ee=e==null?void 0:e.onDocumentToolbarRefresh)==null?void 0:ee.call(e))}catch{}se()}),re.addEventListener("click",()=>{var ee;g(),(ee=t.onDismiss)==null||ee.call(t)});let ve=()=>{o&&(M.setAttribute("aria-pressed",x==="rendered"?"true":"false"),S.setAttribute("aria-pressed",x==="source"?"true":"false"))};M.addEventListener("click",()=>{x="rendered",ve(),se()}),S.addEventListener("click",()=>{x="source",ve(),se()});let Ne=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(u.replaceChildren(),E.append(M,S),N?B.append(N,j,re):B.append(F,j,re),u.append(E,Ne,B),ve()):(u.appendChild(m),u.appendChild(v)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let qe=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"),Te=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(qe.style.paddingLeft=s,qe.style.paddingRight=s,Te.style.padding=s),f.appendChild(u),f.appendChild(qe),f.appendChild(Te);let we=[],oe=null,X=!1,se=()=>{var st,at,nt,Me;let ee=o&&we.length<=1;qe.classList.toggle("persona-hidden",ee),qe.replaceChildren();for(let he of we){let Ge=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");Ge.type="button",Ge.textContent=he.title||he.id.slice(0,8),he.id===oe&&Ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ge.addEventListener("click",()=>t.onSelect(he.id)),qe.appendChild(Ge)}Te.replaceChildren();let Z=oe&&we.find(he=>he.id===oe)||we[we.length-1];if(!Z)return;if(o){let he=Z.artifactType==="markdown"?"MD":(st=Z.component)!=null?st:"Component",J=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ne.textContent=`${J} \xB7 ${he}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(o&&x==="source"){let Ge=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ge.textContent=(at=Z.markdown)!=null?at:"",Te.appendChild(Ge);return}let he=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");he.innerHTML=d((nt=Z.markdown)!=null?nt:""),Te.appendChild(he);return}let ne=Z.component?Vo.get(Z.component):void 0;if(ne){let Ge={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let J=ne((Me=Z.props)!=null?Me:{},Ge);if(J){Te.appendChild(J);return}}catch{}}Te.appendChild(eb(Z))},fe=()=>{var Z;let ee=we.length>0;if(f.classList.toggle("persona-hidden",!ee),c){let ne=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,at=((Z=ne==null?void 0:ne.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ee&&at&&X?(c.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:c,update(ee){var Z,ne,st;we=ee.artifacts,oe=(st=(ne=ee.selectedId)!=null?ne:(Z=ee.artifacts[ee.artifacts.length-1])==null?void 0:Z.id)!=null?st:null,we.length>0&&(X=!0),se(),fe()},setMobileOpen(ee){X=ee,!ee&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):fe()}}}function pr(n){var t,e;return((e=(t=n==null?void 0:n.features)==null?void 0:t.artifacts)==null?void 0:e.enabled)===!0}function Nm(n,t){var s,a,i,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!pr(t))return;let e=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=e==null?void 0:e.paneBorder)==null?void 0:i.trim(),o=(d=e==null?void 0:e.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function tb(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Li(n,t){var d,c,g,f,u,m,v,x,E,M;if(!pr(t)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),tb(n),Nm(n,t);return}let e=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(g=e==null?void 0:e.splitGap)!=null?g:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=e==null?void 0:e.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(u=e==null?void 0:e.paneMaxWidth)!=null?u:"28rem"),e!=null&&e.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",e.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=e==null?void 0:e.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=e==null?void 0:e.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(x=e==null?void 0:e.documentToolbarIconColor)==null?void 0:x.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=e==null?void 0:e.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=e==null?void 0:e.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Nm(n,t)}var Fm=["panel","seamless"];function Ii(n,t){var i,d,c,g,f,u;for(let m of Fm)n.classList.remove(`persona-artifact-appearance-${m}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!pr(t))return;let e=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=e==null?void 0:e.paneAppearance)!=null?c:"panel",o=Fm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(g=e==null?void 0:e.paneBorderRadius)==null?void 0:g.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=e==null?void 0:e.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(e==null?void 0:e.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((u=e.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function _m(n,t){var e,r,o;return!t||!pr(n)?!1:((o=(r=(e=n.features)==null?void 0:e.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function nb(n,t){if(!(n!=null&&n.trim()))return t;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):t}function rb(n){if(!(n!=null&&n.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):null}function ob(n,t,e){return e<t?t:Math.min(e,Math.max(t,n))}function sb(n,t,e,r){let o=n-r-2*t-e;return Math.max(0,o)}function Om(n,t){var a;let r=(a=(t.getComputedStyle(n).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function $m(n,t,e,r,o,s){let a=nb(o,200),i=sb(t,e,r,200);i=Math.max(a,i);let d=rb(s);return d!==null&&(i=Math.min(i,d)),ob(n,a,i)}var qm={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"}},wl=(n,t,e,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=qm[a])!=null?x:qm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let M=y("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var A,L;let S=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${t.id}-${a}-${M.name}`;let B=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");B.textContent=M.label,S.appendChild(B);let I=(A=M.type)!=null?A:"text",R;I==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=I),R.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",R.id=`${t.id}-${a}-${M.name}`,R.name=M.name,R.placeholder=(L=M.placeholder)!=null?L:"",M.required&&(R.required=!0),S.appendChild(R),g.appendChild(S)});let f=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",f.appendChild(u),f.appendChild(m),g.appendChild(f),s.replaceChildren(d,g),g.addEventListener("submit",async M=>{var R,A;M.preventDefault();let S=(R=e.formEndpoint)!=null?R:"/form",B=new FormData(g),I={};B.forEach((L,N)=>{I[N]=L}),I.type=a,m.disabled=!0,u.textContent="Submitting\u2026";try{let L=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let N=await L.json();u.textContent=(A=N.message)!=null?A:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(L){u.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Cl=class{constructor(){this.plugins=new Map}register(t){var e;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(e=t.onRegister)==null||e.call(t)}unregister(t){var r;let e=this.plugins.get(t);e&&((r=e.onUnregister)==null||r.call(e),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,e)=>{var r,o;return((r=e.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let e=this.getAll();if(!t||t.length===0)return e;let r=new Set(t.map(s=>s.id));return[...e.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var e;return(e=t.onUnregister)==null?void 0:e.call(t)}),this.plugins.clear()}},Al=new Cl;var Um=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>e(o,s)),e=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:t,off:e,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ab=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},ib=n=>{let t=n.trim(),e=t.indexOf("{");if(e===-1)return null;let r=0;for(let o=e;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(e,o+1)}return null},Tl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=ab(n),e=ib(t);if(!e)return null;let r=JSON.parse(e);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Sl=n=>typeof n=="string"?n:n==null?"":String(n),ya={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Sl(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let e=n.payload,r=Sl(e.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Sl(e.text)}}},zm=n=>Array.isArray(n)?n.map(t=>String(t)):[],El=n=>{let t=new Set(zm(n.getSessionMetadata().processedActionMessageIds)),e=()=>{t=new Set(zm(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,g)=>c||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let g=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:e}};var lb=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},cb=n=>n.map(t=>({...t,streaming:!1})),db=n=>n.map(t=>({...t,status:"complete"})),jm=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let e=t();return e?lb(e.getItem(n)):null},save:e=>{let r=t();if(r)try{let o={...e,messages:e.messages?cb(e.messages):void 0,artifacts:e.artifacts?db(e.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let e=t();if(e)try{e.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Ml=require("partial-json");function Vm(n,t){let{config:e,message:r,onPropsUpdate:o}=t,s=Vo.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:e,updateProps:i=>{o&&o(i)}};try{return s(n.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,i),null}}function Km(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let t=n.content.trim();if(t.startsWith("{")||t.startsWith("["))return n.content}return null}function Gm(n){let t=Km(n);if(!t)return!1;try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Qm(n){let t=Km(n);if(!t)return null;try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"){let r=e;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var pb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xm(n){let{onSubmit:t,onDismiss:e,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=pb}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),u.appendChild(m);let 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 M=[];for(let A=1;A<=5;A++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),L.title=c[A-1],L.dataset.rating=String(A),L.innerHTML=`
29
29
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
30
30
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
31
31
  </svg>
32
- `,W.addEventListener("click",()=>{f=A,k.forEach((D,N)=>{let M=N<A;D.classList.toggle("selected",M),D.setAttribute("aria-checked",N===A-1?"true":"false")})}),k.push(W),E.appendChild(W)}u.appendChild(E);let L=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),A.appendChild(L),u.appendChild(A)}let F=document.createElement("div");F.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{t==null||t(),g.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=(L==null?void 0:L.value.trim())||void 0;await e(f,A),g.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),F.appendChild(I),F.appendChild(R),u.appendChild(F),g.appendChild(u),g}function Gm(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=n,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let u=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,v.appendChild(E),m.appendChild(v);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=g,L.appendChild(F),L.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let z=0;z<=10;z++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${z} out of 10`),j.textContent=String(z),j.dataset.rating=String(z),z<=6?j.classList.add("persona-feedback-detractor"):z<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{u=z,A.forEach((oe,Le)=>{oe.classList.toggle("selected",Le===z),oe.setAttribute("aria-checked",Le===z?"true":"false")})}),A.push(j),R.appendChild(j)}k.appendChild(L),k.appendChild(R),m.appendChild(k);let W=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),z.appendChild(W),m.appendChild(z)}let D=document.createElement("div");D.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{t==null||t(),f.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=a,M.addEventListener("click",async()=>{if(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let z=(W==null?void 0:W.value.trim())||void 0;await e(u,z),f.remove()}catch(z){M.disabled=!1,M.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),D.appendChild(N),D.appendChild(M),m.appendChild(D),f.appendChild(m),f}var Ts="persona-chat-history",cy=30*1e3,dy={"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 py(n){var r,o,s;if(!n)return[];let e=[],t=Array.from((r=n.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=dy[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function Li(n){if(!n)return!1;let e=n.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function uy(n){var e,t,r,o,s,a,i,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=n.storage)!=null?e:"session",keyPrefix:(t=n.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=n.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function my(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var Ml=n=>!n||typeof n!="object"?{}:{...n},Qm=n=>n.map(e=>({...e,streaming:!1})),Xm=(n,e,t)=>{let r=n!=null&&n.markdown?Oa(n.markdown):null,o=_a(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var c,g,f;let a=(c=s.text)!=null?c:"",i=(g=s.message.rawContent)!=null?g:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&t&&t())}let d;return n!=null&&n.postprocessMessage?d=n.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""}):r?d=r(a):d=ho(a),o?o(d):d}};function Jm(n){var i,d,c,g;let e=b("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(g=n==null?void 0:n.iconStrokeWidth)!=null?g:.5,a=Se(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let f=b("span","persona-drop-overlay-label");f.textContent=n.label,e.appendChild(f)}return e}var Ym=(n,e,t)=>{var Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,qc,Uc,zc,jc,Vc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=Vu(e),o=wl.getForInstance(r.plugins);r.components&&Vo.registerAll(r.components);let s=_m(),i=r.persistState===!1?null:(Jl=r.storageAdapter)!=null?Jl:qm(),d={},c=null,g=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(g=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(d=Ml(h.metadata)),(Yl=h.messages)!=null&&Yl.length&&(r={...r,initialMessages:h.messages}),(Zl=h.artifacts)!=null&&Zl.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(ec=h.selectedArtifactId)!=null?ec:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(tc=l.messages)!=null&&tc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>d,m=l=>{var h;d=(h=l({...d}))!=null?h:{},es()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Al],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[va.message,va.messageAndClick],E=Sl({parsers:v,handlers:x,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let k=(rc=(nc=r.launcher)==null?void 0:nc.enabled)!=null?rc:!0,L=(sc=(oc=r.launcher)==null?void 0:oc.autoExpand)!=null?sc:!1,F=(ac=r.autoFocusInput)!=null?ac:!1,I=L,R=k,A=(lc=(ic=r.layout)==null?void 0:ic.header)==null?void 0:lc.layout,W=!1,D=()=>ma(r),N=()=>k||D(),M=D()?!1:k?L:!0,z=!1,j=null,oe=()=>{z=!0,j&&clearTimeout(j),j=setTimeout(()=>{z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),z=!1)},1e4)},Le=Xm(r,E,oe),Ve=(dc=(cc=r.features)==null?void 0:cc.showReasoning)!=null?dc:!0,ve=(uc=(pc=r.features)==null?void 0:pc.showToolCalls)!=null?uc:!0,Be=(gc=(mc=r.features)==null?void 0:mc.showEventStreamToggle)!=null?gc:!1,Oe=(hc=(fc=r.features)==null?void 0:fc.scrollToBottom)!=null?hc:{},Te=(bc=(yc=r.features)==null?void 0:yc.scrollBehavior)!=null?bc:{},se=`${(xc=typeof r.persistState=="object"?(vc=r.persistState)==null?void 0:vc.keyPrefix:void 0)!=null?xc:"persona-"}event-stream`,Q=Be?new ya(se):null,ae=(Ac=(Cc=(wc=r.features)==null?void 0:wc.eventStream)==null?void 0:Cc.maxEvents)!=null?Ac:2e3,fe=Be?new ha(ae,Q):null,ue=Be?new ba:null,K=null,ie=!1,We=null,te=0;Q==null||Q.open().then(()=>fe==null?void 0:fe.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ee={onCopy:l=>{var p,h;s.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;s.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},re=(Sc=r.statusIndicator)!=null?Sc:{},it=l=>{var p,h,y,S;return l==="idle"?(p=re.idleText)!=null?p:Mn.idle:l==="connecting"?(h=re.connectingText)!=null?h:Mn.connecting:l==="connected"?(y=re.connectedText)!=null?y:Mn.connected:l==="error"?(S=re.errorText)!=null?S:Mn.error:Mn[l]};function lt(l,p,h,y){if(y==="idle"&&h.idleLink){l.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=p,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=p}let st=ym({config:r,showClose:N()}),{wrapper:Ee,panel:he,pillRoot:Je}=st.shell,Y=st.panelElements,{container:me,body:ke,messagesWrapper:Ye,suggestions:Ge,textarea:Ie,sendButton:Ke,sendButtonWrapper:vn,composerForm:Rt,statusText:pn,introTitle:Cr,introSubtitle:q,closeButton:G,iconHolder:ye,headerTitle:Qe,headerSubtitle:et,header:qe,footer:_e,actionsRow:Pt,leftActions:Kt,rightActions:Jt}=Y,Ln=Y.setSendButtonMode,V=Y.micButton,Ht=Y.micButtonWrapper,ce=Y.attachmentButton,Ce=Y.attachmentButtonWrapper,Fe=Y.attachmentInput,Tt=Y.attachmentPreviewsContainer;me.classList.add("persona-relative"),ke.classList.add("persona-relative");let on=12,sn=()=>{var l;return(l=Oe.label)!=null?l:""},xn=()=>{var l;return(l=Oe.iconName)!=null?l:"arrow-down"},Nt=()=>Oe.enabled!==!1,rt=()=>{var l;return(l=Te.mode)!=null?l:"follow"},Dt=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},pt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let Yt=b("span","persona-flex persona-items-center"),nr=b("span",""),Pn=b("span","");Pn.setAttribute("data-persona-scroll-to-bottom-count",""),Pn.style.display="none",pt.append(Yt,nr,Pn),me.appendChild(pt);let an=b("div","persona-stream-anchor-spacer");an.setAttribute("aria-hidden","true"),an.setAttribute("data-persona-anchor-spacer",""),an.style.flexShrink="0",an.style.pointerEvents="none",an.style.height="0px",ke.appendChild(an);let On=()=>{let p=_e.style.display==="none"?0:_e.offsetHeight;pt.style.bottom=`${p+on}px`};On();let Ar=()=>{let l=!!sn();pt.setAttribute("aria-label",sn()||"Jump to latest"),pt.title=sn(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Yt.innerHTML="";let p=Se(xn(),"14px","currentColor",2);p?(Yt.appendChild(p),Yt.style.display=""):Yt.style.display="none",nr.textContent=sn(),nr.style.display=l?"":"none"};Ar();let xt=null,zn=null,Sr=o.find(l=>l.renderHeader);if(Sr!=null&&Sr.renderHeader){let l=Sr.renderHeader({config:r,defaultRenderer:()=>{let p=zo({config:r,showClose:N()});return ga(me,p,r),p.header},onClose:()=>T(!1,"user")});if(l){let p=me.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),qe=l,st.header.element=l)}}let Fr=()=>{var p,h,y,S;if(!fe)return;if(ie=!0,!K&&fe&&(K=Pm({buffer:fe,getFullHistory:()=>fe.getAllFromStore(),onClose:()=>mr(),config:r,plugins:o,getThroughput:()=>{var B;return(B=ue==null?void 0:ue.getMetric())!=null?B:{status:"idle"}}})),K&&(ke.style.display="none",(p=_e.parentNode)==null||p.insertBefore(K.element,_e),K.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Fn.actionIconColor}`;let B=(S=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:S.toggleButtonActive;B&&B.split(/\s+/).forEach(U=>U&&bt.classList.add(U))}let l=()=>{if(!ie)return;let B=Date.now();B-te>=200&&(K==null||K.update(),te=B),We=requestAnimationFrame(l)};te=0,We=requestAnimationFrame(l),qn(),s.emit("eventStream:opened",{timestamp:Date.now()})},mr=()=>{var l,p,h;if(ie){if(ie=!1,K&&K.element.remove(),ke.style.display="",bt){bt.style.boxShadow="";let y=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(S=>S&&bt.classList.remove(S))}We!==null&&(cancelAnimationFrame(We),We=null),qn(),s.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(Be){let l=(Mc=(Tc=r.features)==null?void 0:Tc.eventStream)==null?void 0:Mc.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");bt=b("button",p),bt.style.width="28px",bt.style.height="28px",bt.style.color=Fn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let h=Se("activity","18px","currentColor",1.5);h&&bt.appendChild(h);let y=Y.clearChatButtonWrapper,S=Y.closeButtonWrapper,B=y||S;B&&B.parentNode===qe?qe.insertBefore(bt,B):qe.appendChild(bt),bt.addEventListener("click",()=>{ie?mr():Fr()})}let Co=l=>{var S,B,U,O,H;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let de=l.querySelector("[data-persona-composer-form]");de!=null&&de.parentNode?de.parentNode.insertBefore(h,de):l.insertBefore(h,l.firstChild)}if(!((B=l.querySelector("[data-persona-composer-attachment-input]"))!=null?B:l.querySelector('input[type="file"]'))){let de=b("input");de.type="file",de.setAttribute("data-persona-composer-attachment-input",""),de.accept=((U=p.allowedTypes)!=null?U:Qr).join(","),de.multiple=((O=p.maxFiles)!=null?O:4)>1,de.style.display="none",de.setAttribute("aria-label",(H=p.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(de)}},Tr=o.find(l=>l.renderComposer);if(Tr!=null&&Tr.renderComposer){let l=r.composer,p=Tr.renderComposer({config:r,defaultRenderer:()=>Ai({config:r}).footer,onSubmit:h=>{var U;if(!_||_.isStreaming())return;let y=h.trim(),S=(U=xt==null?void 0:xt.hasAttachments())!=null?U:!1;if(!y&&!S)return;tt();let B;S&&(B=[],B.push(...xt.getContentParts()),y&&B.push(Ji(y))),_.sendMessage(y,{contentParts:B}),S&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe==null||Fe.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:((Ec=r.voiceRecognition)==null?void 0:Ec.enabled)===!0?()=>{zn==null||zn()}:void 0});p&&(st.replaceComposer(p),_e=st.composer.footer)}let Ao=l=>{let p=(...pe)=>{for(let Z of pe){let xe=l.querySelector(Z);if(xe)return xe}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),B=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");h&&(Rt=h),y&&(Ie=y),S&&(Ke=S),B&&(V=B,Ht=B.parentElement),U&&(pn=U);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ge=O);let H=p("[data-persona-composer-attachment-button]",".persona-attachment-button");H&&(ce=H,Ce=H.parentElement),Fe=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Tt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let de=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");de&&(Pt=de)};Co(_e),Ao(_e);let _n=(Wc=(kc=r.layout)==null?void 0:kc.contentMaxWidth)!=null?Wc:D()?(Ic=(Pc=(Lc=r.launcher)==null?void 0:Lc.composerBar)==null?void 0:Pc.contentMaxWidth)!=null?Ic:"720px":void 0;if(_n&&(Ye.style.maxWidth=_n,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%"),_n&&Rt&&!D()&&(Rt.style.maxWidth=_n,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),_n&&Ge&&!D()&&(Ge.style.maxWidth=_n,Ge.style.marginLeft="auto",Ge.style.marginRight="auto"),_n&&Tt&&!D()&&(Tt.style.maxWidth=_n,Tt.style.marginLeft="auto",Tt.style.marginRight="auto"),(Rc=r.attachments)!=null&&Rc.enabled&&Fe&&Tt){xt=sa.fromConfig(r.attachments),xt.setPreviewsContainer(Tt),Fe.addEventListener("change",h=>{let y=h.target;xt==null||xt.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=Jm(l);me.appendChild(p)}(()=>{var y,S;let l=(S=(y=r.layout)==null?void 0:y.slots)!=null?S:{},p=B=>{switch(B){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ye;case"footer-top":return Ge;case"composer":return Rt;case"footer-bottom":return pn;default:return null}},h=(B,U)=>{var O;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")qe.insertBefore(U,qe.firstChild);else if(B==="header-right")qe.appendChild(U);else{let H=qe.querySelector(".persona-flex-col");H?(O=H.parentNode)==null||O.insertBefore(U,H.nextSibling):qe.appendChild(U)}break;case"body-top":{let H=ke.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(U):ke.insertBefore(U,ke.firstChild);break}case"body-bottom":ke.appendChild(U);break;case"footer-top":Ge.replaceWith(U);break;case"footer-bottom":pn.replaceWith(U);break;default:break}};for(let[B,U]of Object.entries(l))if(U)try{let O=U({config:r,defaultContent:()=>p(B)});O&&h(B,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,O)}})();let Yr=l=>{var U,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-bubble-type");if(B==="reasoning")Cs.has(S)?Cs.delete(S):Cs.add(S),xm(S,y);else if(B==="tool")As.has(S)?As.delete(S):As.add(S),wm(S,y,r);else if(B==="approval"){let H=r.approval!==!1?r.approval:void 0,de=((U=H==null?void 0:H.detailsDisplay)!=null?U:"collapsed")==="expanded",pe=(O=Si.get(S))!=null?O:de;Si.set(S,!pe),Tm(S,y,r)}Pr.delete(S)};Ye.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))}),Ye.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))});let Or=new Map,Zr=null,eo="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(l,p)=>{let{icon:h,label:y}=So[p];l.setAttribute("aria-label",y),l.title=y,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let S=Se(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},to=()=>{Ye.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var B;let h=p.closest("[data-actions-for]"),y=(B=h==null?void 0:h.getAttribute("data-actions-for"))!=null?B:null;To(p,y&&y===Zr?eo:"idle")})};Ye.addEventListener("click",l=>{var U;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let S=y.getAttribute("data-actions-for");if(!S)return;let B=h.getAttribute("data-action");if(B==="copy"){let H=_.getMessages().find(de=>de.id===S);if(H&&ee.onCopy){let de=H.content||"";navigator.clipboard.writeText(de).then(()=>{h.classList.add("persona-message-action-success");let pe=Se("check",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Se("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),ee.onCopy(H)}}else if(B==="read-aloud")_.toggleReadAloud(S);else if(B==="upvote"||B==="downvote"){let H=((U=Or.get(S))!=null?U:null)===B,de=B==="upvote"?"thumbs-up":"thumbs-down";if(H){Or.delete(S),h.classList.remove("persona-message-action-active");let pe=Se(de,14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))}else{let pe=B==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${pe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=Se(pe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}Or.set(S,B),h.classList.add("persona-message-action-active");let xe=Se(de,14,"currentColor",2);xe&&(xe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(xe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=_.getMessages().find(ot=>ot.id===S);Ae&&ee.onFeedback&&ee.onFeedback({type:B,messageId:Ae.id,message:Ae})}}}),Ye.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let B=h.getAttribute("data-approval-action");if(!B)return;let U=B==="approve"?"approved":"denied",H=_.getMessages().find(pe=>pe.id===S);if(!(H!=null&&H.approval))return;let de=y.querySelector("[data-approval-buttons]");de&&de.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,U):_.resolveApproval(H.approval,U)});let Ct=null,jn=null,Vn={artifacts:[],selectedId:null},In=!1,Mt={current:null};Ye.addEventListener("click",l=>{var Z,xe,Ne,Ae,ot;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Ne=(xe=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:Ne.call(xe,{type:"download",artifactId:y}))===!0)return;let B=_.getArtifactById(y),U=B==null?void 0:B.markdown,O=(B==null?void 0:B.title)||"artifact";if(!U){let ze=h.closest("[data-open-artifact]"),ft=ze==null?void 0:ze.closest("[data-message-id]"),ct=ft==null?void 0:ft.getAttribute("data-message-id");if(ct){let Pe=_.getMessages().find(je=>je.id===ct);if(Pe!=null&&Pe.rawContent)try{let je=JSON.parse(Pe.rawContent);U=(Ae=je==null?void 0:je.props)==null?void 0:Ae.markdown,O=((ot=je==null?void 0:je.props)==null?void 0:ot.title)||O}catch{}}}if(!U)return;let H=new Blob([U],{type:"text/markdown"}),de=URL.createObjectURL(H),pe=document.createElement("a");pe.href=de,pe.download=`${O}.md`,pe.click(),URL.revokeObjectURL(de)}),Ye.addEventListener("click",l=>{var B,U,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((O=(U=(B=r.features)==null?void 0:B.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:O.call(U,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),In=!1,_.selectArtifact(y),Qn())}),Ye.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let rr=Y.composerOverlay,or=(l,p,h)=>{var O,H,de,pe;let y=p.trim();if(!y||!Mt.current)return;let S=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",B=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:y,answers:h.structured,values:(H=h.values)!=null?H:h.source==="multi"?y.split(", "):[y],isFreeText:B,source:h.source},bubbles:!0,composed:!0})),ms(rr,S);let U=Mt.current.getMessages().find(Z=>{var xe;return((xe=Z.toolCall)==null?void 0:xe.id)===S});(de=U==null?void 0:U.agentMetadata)!=null&&de.awaitingLocalTool?Mt.current.resolveAskUserQuestion(U,(pe=h.structured)!=null?pe:y):Mt.current.sendMessage(y)},Kn=l=>{var S;let p=Mt.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",y=p.getMessages().find(B=>{var U;return((U=B.toolCall)==null?void 0:U.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:Ua(l,y),currentIndex:pr(l)})},no=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),_r=l=>{var S,B,U;if(((B=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let p=pr(l),h=us(l);if(p>=h-1)return;let y=(U=Mt.current)==null?void 0:U.getMessages().find(O=>{var H;return((H=O.toolCall)==null?void 0:H.id)===l.getAttribute("data-tool-call-id")});y&&(ja(l,y,r,p+1),Kn(l))};rr.addEventListener("click",l=>{var B,U,O,H,de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let S=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let Re=(B=y.getAttribute("data-tool-call-id"))!=null?B:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),ms(rr,Re);let Pe=(U=Mt.current)==null?void 0:U.getMessages().find(je=>{var Xe;return((Xe=je.toolCall)==null?void 0:Xe.id)===Re});(O=Pe==null?void 0:Pe.agentMetadata)!=null&&O.awaitingLocalTool&&((H=Mt.current)==null||H.markAskUserQuestionResolved(Pe),(de=Mt.current)==null||de.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(S==="pick"){let Re=h.getAttribute("data-option-label");if(!Re)return;let Pe=y.getAttribute("data-multi-select")==="true",je=bo(y);if(je&&Pe){let Xe=Oo(y)[pr(y)],vt=new Set(Array.isArray(Xe)?Xe:[]);vt.has(Re)?vt.delete(Re):vt.add(Re),vo(y,Array.from(vt)),Kn(y);return}if(je){vo(y,Re),Kn(y),_r(y);return}if(Pe){let Xe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Xe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Xe);let vt=y.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=ji(y).length===0);return}or(y,Re,{source:"pick",values:[Re]});return}if(S==="submit-multi"){let Re=ji(y);if(Re.length===0)return;or(y,Re.join(", "),{source:"multi",values:Re});return}if(S==="open-free-text"){let Re=y.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Pe=Re.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(S==="focus-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(S==="submit-free-text"){let Re=y.querySelector('[data-ask-free-text-input="true"]'),Pe=(pe=Re==null?void 0:Re.value)!=null?pe:"";if(!Pe.trim())return;if(bo(y)){vo(y,Pe.trim()),Kn(y),_r(y);return}or(y,Pe,{source:"free-text"});return}if(S==="next"||S==="back"){if(!Mt.current)return;let Re=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Pe=Mt.current.getMessages().find(De=>{var He;return((He=De.toolCall)==null?void 0:He.id)===Re});if(!Pe)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Xe=(Ne=(xe=je==null?void 0:je.value)==null?void 0:xe.trim())!=null?Ne:"";if(Xe){let De=Oo(y)[pr(y)];(typeof De!="string"||De!==Xe)&&vo(y,Xe)}let vt=S==="next"?1:-1,P=pr(y)+vt;ja(y,Pe,r,P),Kn(y);return}if(S==="submit-all"){if(!Mt.current)return;let Re=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",Pe=Mt.current.getMessages().find(De=>{var He;return((He=De.toolCall)==null?void 0:He.id)===Re});if(!Pe)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Xe=(ze=(ot=je==null?void 0:je.value)==null?void 0:ot.trim())!=null?ze:"";Xe&&vo(y,Xe);let vt=Ua(y,Pe);Mt.current.persistAskUserQuestionProgress(Pe,{answers:vt,currentIndex:pr(y)});let P=no(vt);or(y,P||"(submitted)",{source:"submit-all",structured:vt});return}if(S==="skip"){if(!Mt.current)return;let Re=(ft=y.getAttribute("data-tool-call-id"))!=null?ft:"",Pe=Mt.current.getMessages().find(He=>{var ge;return((ge=He.toolCall)==null?void 0:ge.id)===Re});if(!Pe)return;let je=bo(y),Xe=pr(y),vt=us(y),P=Xe>=vt-1;if(!je){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),ms(rr,Re),(ct=Pe.agentMetadata)!=null&&ct.awaitingLocalTool&&(Mt.current.markAskUserQuestionResolved(Pe),Mt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}vo(y,"");let De=y.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),P){let He=Ua(y,Pe),ge=no(He);or(y,ge||"(skipped)",{source:"submit-all",structured:He});return}ja(y,Pe,r,Xe+1),Kn(y);return}}),rr.addEventListener("keydown",l=>{var B;if(l.key!=="Enter")return;let h=l.target;if(!((B=h.matches)!=null&&B.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let S=h.value;if(S.trim()){if(bo(y)){vo(y,S.trim()),Kn(y),_r(y);return}or(y,S,{source:"free-text"})}});let ro=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=rr.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),B=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];B&&(l.preventDefault(),B.click())};document.addEventListener("keydown",ro);let Gn=null,Ft=null,Wn=null,sr=null,oo=()=>{};function $r(){sr==null||sr(),sr=null}let so=()=>{var U;if(!Gn||!Ft)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((U=n.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let y=Gn.firstElementChild;if(!y||y===Ft)return;let S=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${S}px`,Ft.style.zIndex="5";let B=y.offsetWidth-S/2;Ft.style.left=`${Math.max(0,B)}px`},Mr=()=>{},Qn=()=>{var h,y,S,B,U;if(!Ct||!ur(r))return;Ei(n,r),ki(n,r),Mr();let l=(B=(S=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:S.narrowHostMaxWidth)!=null?B:520,p=he.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),Ct.update(Vn),In?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(U=Ct.backdrop)==null||U.classList.add("persona-hidden")):Vn.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),oo()};if(ur(r)){he.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(me),Ct=Rm(r,{onSelect:h=>{var y;return(y=Mt.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{In=!0,Qn()}}),Ct.element.classList.add("persona-hidden"),Gn=p,p.appendChild(l),p.appendChild(Ct.element),Ct.backdrop&&he.appendChild(Ct.backdrop),he.appendChild(p),oo=()=>{var y,S,B,U;if(!Gn||!Ct)return;if(!(((B=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:B.resizable)===!0)){Wn==null||Wn(),Wn=null,$r(),Ft&&(Ft.remove(),Ft=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Ft){let O=b("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=n.ownerDocument,de=(U=H.defaultView)!=null?U:window,pe=Z=>{var ft,ct;if(!Ct||Z.button!==0||n.classList.contains("persona-artifact-narrow-host")||de.innerWidth<=640)return;Z.preventDefault(),$r();let xe=Z.clientX,Ne=Ct.element.getBoundingClientRect().width,Ae=(ct=(ft=r.features)==null?void 0:ft.artifacts)==null?void 0:ct.layout,ot=Re=>{let Pe=Gn.getBoundingClientRect().width,je=n.classList.contains("persona-artifact-appearance-seamless"),Xe=je?0:Nm(Gn,de),vt=je?0:O.getBoundingClientRect().width||6,P=Ne-(Re.clientX-xe),De=Fm(P,Pe,Xe,vt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);Ct.element.style.width=`${De}px`,Ct.element.style.maxWidth="none",so()},ze=()=>{H.removeEventListener("pointermove",ot),H.removeEventListener("pointerup",ze),H.removeEventListener("pointercancel",ze),sr=null;try{O.releasePointerCapture(Z.pointerId)}catch{}};sr=ze,H.addEventListener("pointermove",ot),H.addEventListener("pointerup",ze),H.addEventListener("pointercancel",ze);try{O.setPointerCapture(Z.pointerId)}catch{}};O.addEventListener("pointerdown",pe),Ft=O,Gn.insertBefore(O,Ct.element),Wn=()=>{O.removeEventListener("pointerdown",pe)}}if(Ft){let O=Vn.artifacts.length>0&&!In;Ft.classList.toggle("persona-hidden",!O),so()}},Mr=()=>{var de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct,Re,Pe,je,Xe;if(!k||!Ct||((pe=(de=r.launcher)==null?void 0:de.sidebarMode)!=null?pe:!1)||Cn(r)&&xr(r).reveal==="emerge")return;let y=(Z=n.ownerDocument.defaultView)!=null?Z:window,S=(Ne=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?Ne:!0,B=(ot=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?ot:640;if(S&&y.innerWidth<=B||!Dm(r,k))return;let U=(ct=(ft=(ze=r.launcher)==null?void 0:ze.width)!=null?ft:r.launcherWidth)!=null?ct:Xr,O=(Xe=(je=(Pe=(Re=r.features)==null?void 0:Re.artifacts)==null?void 0:Pe.layout)==null?void 0:je.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";Vn.artifacts.length>0&&!In?(he.style.width=O,he.style.maxWidth=O):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(jn=new ResizeObserver(()=>{Qn()}),jn.observe(he))}else he.appendChild(me),D()&&Je&&(Y.peekBanner&&Je.appendChild(Y.peekBanner),Je.appendChild(_e));n.appendChild(Ee),Je&&n.appendChild(Je);let be=()=>{var De,He,ge,$t,Ot,Gt,wt,jt,Yn,rn,Ze,It,dn,dr,Zn,Po,Io,as,is,Qt,Wo,go,fo,Kr,Ro,yr,nt,gn;if(D()){he.style.width="100%",he.style.maxWidth="100%";let Ut=(He=(De=r.launcher)==null?void 0:De.composerBar)!=null?He:{},qt=Ee.dataset.state==="expanded",ht=(ge=Ut.expandedSize)!=null?ge:"anchored";if(!(qt&&ht!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let St=(Ot=($t=r.theme)==null?void 0:$t.components)==null?void 0:Ot.panel,Sn=si(r),Hn=(Dn,Ho)=>{var qs;return Dn==null||Dn===""?Ho:(qs=vs(Sn,Dn))!=null?qs:Dn},Dr="1px solid var(--persona-border)",bn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Bn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=Hn(St==null?void 0:St.border,Dr),me.style.borderRadius=Hn(St==null?void 0:St.borderRadius,Bn),me.style.boxShadow=Hn(St==null?void 0:St.shadow,bn),me.style.overflow="hidden";return}let l=Cn(r),p=(wt=(Gt=r.launcher)==null?void 0:Gt.sidebarMode)!=null?wt:!1,h=l||p||((Yn=(jt=r.launcher)==null?void 0:jt.fullHeight)!=null?Yn:!1),y=((rn=r.launcher)==null?void 0:rn.enabled)===!1,S=(It=(Ze=r.theme)==null?void 0:Ze.components)==null?void 0:It.panel,B=si(r),U=(Ut,qt)=>{var ht;return Ut==null||Ut===""?qt:(ht=vs(B,Ut))!=null?ht:Ut},O=(dn=n.ownerDocument.defaultView)!=null?dn:window,H=(Zn=(dr=r.launcher)==null?void 0:dr.mobileFullscreen)!=null?Zn:!0,de=(Io=(Po=r.launcher)==null?void 0:Po.mobileBreakpoint)!=null?Io:640,pe=O.innerWidth<=de,Z=H&&pe&&k,xe=(is=(as=r.launcher)==null?void 0:as.position)!=null?is:"bottom-left",Ne=xe==="bottom-left"||xe==="top-left",Ae=(Wo=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?Wo:En,ot=p||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":p?Ne?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(ze="none",ot="none");let ft=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=U(S==null?void 0:S.border,ot),Re=U(S==null?void 0:S.shadow,ze),Pe=U(S==null?void 0:S.borderRadius,ft),je=ke.scrollTop;n.style.cssText="",Ee.style.cssText="",he.style.cssText="",me.style.cssText="",ke.style.cssText="",_e.style.cssText="";let Xe=()=>{var qt;if(je<=0)return;((qt=ke.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(ke.scrollTop===je)return;let ht=ke.scrollHeight-ke.clientHeight;ht<=0||(ke.scrollTop=Math.min(je,ht))})};if(Z){Ee.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ee.style.cssText=`
32
+ `,L.addEventListener("click",()=>{f=A,M.forEach((N,F)=>{let k=F<A;N.classList.toggle("selected",k),N.setAttribute("aria-checked",F===A-1?"true":"false")})}),M.push(L),E.appendChild(L)}u.appendChild(E);let S=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),A.appendChild(S),u.appendChild(A)}let B=document.createElement("div");B.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{e==null||e(),g.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=(S==null?void 0:S.value.trim())||void 0;await t(f,A),g.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),B.appendChild(I),B.appendChild(R),u.appendChild(B),g.appendChild(u),g}function Jm(n){let{onSubmit:t,onDismiss:e,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=n,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let u=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,v.appendChild(E),m.appendChild(v);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-nps",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=c;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=g,S.appendChild(B),S.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let z=0;z<=10;z++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${z} out of 10`),j.textContent=String(z),j.dataset.rating=String(z),z<=6?j.classList.add("persona-feedback-detractor"):z<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{u=z,A.forEach((re,Ie)=>{re.classList.toggle("selected",Ie===z),re.setAttribute("aria-checked",Ie===z?"true":"false")})}),A.push(j),R.appendChild(j)}M.appendChild(S),M.appendChild(R),m.appendChild(M);let L=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),z.appendChild(L),m.appendChild(z)}let N=document.createElement("div");N.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=i,F.addEventListener("click",()=>{e==null||e(),f.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(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let z=(L==null?void 0:L.value.trim())||void 0;await t(u,z),f.remove()}catch(z){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),N.appendChild(F),N.appendChild(k),m.appendChild(N),f.appendChild(m),f}var Ss="persona-chat-history",ub=30*1e3,mb={"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 gb(n){var r,o,s;if(!n)return[];let t=[],e=Array.from((r=n.items)!=null?r:[]);for(let a of e){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=mb[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Pi(n){if(!n)return!1;let t=n.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function fb(n){var t,e,r,o,s,a,i,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=n.storage)!=null?t:"session",keyPrefix:(e=n.keyPrefix)!=null?e:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=n.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function hb(n){try{let t=n==="local"?localStorage:sessionStorage,e="__persist_test__";return t.setItem(e,"1"),t.removeItem(e),t}catch{return null}}var kl=n=>!n||typeof n!="object"?{}:{...n},Ym=n=>n.map(t=>({...t,streaming:!1})),Zm=(n,t,e)=>{let r=n!=null&&n.markdown?Oa(n.markdown):null,o=$a(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var c,g,f;let a=(c=s.text)!=null?c:"",i=(g=s.message.rawContent)!=null?g:null;if(t){let u=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&e&&e())}let d;return n!=null&&n.postprocessMessage?d=n.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""}):r?d=r(a):d=ho(a),o?o(d):d}};function eg(n){var i,d,c,g;let t=y("div","persona-attachment-drop-overlay");n!=null&&n.background&&t.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&t.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&t.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let e=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(g=n==null?void 0:n.iconStrokeWidth)!=null?g:.5,a=Se(e,r,o,s);if(a&&t.appendChild(a),n!=null&&n.label){let f=y("span","persona-drop-overlay-label");f.textContent=n.label,t.appendChild(f)}return t}var tg=(n,t,e)=>{var Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Ic,Pc,Wc,Rc,Bc,Hc,Dc,Nc,Fc,_c,Oc,$c,qc,Uc,zc,jc,Vc,Kc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=Qu(t),o=Al.getForInstance(r.plugins);r.components&&Vo.registerAll(r.components);let s=Um(),i=r.persistState===!1?null:(Yl=r.storageAdapter)!=null?Yl:jm(),d={},c=null,g=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:b}=p;return b&&(g=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(d=kl(h.metadata)),(Zl=h.messages)!=null&&Zl.length&&(r={...r,initialMessages:h.messages}),(ec=h.artifacts)!=null&&ec.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(tc=h.selectedArtifactId)!=null?tc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(nc=l.messages)!=null&&nc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>d,m=l=>{var h;d=(h=l({...d}))!=null?h:{},es()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Tl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ya.message,ya.messageAndClick],E=El({parsers:v,handlers:x,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let M=(oc=(rc=r.launcher)==null?void 0:rc.enabled)!=null?oc:!0,S=(ac=(sc=r.launcher)==null?void 0:sc.autoExpand)!=null?ac:!1,B=(ic=r.autoFocusInput)!=null?ic:!1,I=S,R=M,A=(cc=(lc=r.layout)==null?void 0:lc.header)==null?void 0:cc.layout,L=!1,N=()=>ua(r),F=()=>M||N(),k=N()?!1:M?S:!0,z=!1,j=null,re=()=>{z=!0,j&&clearTimeout(j),j=setTimeout(()=>{z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),z=!1)},1e4)},Ie=Zm(r,E,re),Ve=(pc=(dc=r.features)==null?void 0:dc.showReasoning)!=null?pc:!0,ve=(mc=(uc=r.features)==null?void 0:uc.showToolCalls)!=null?mc:!0,Ne=(fc=(gc=r.features)==null?void 0:gc.showEventStreamToggle)!=null?fc:!1,qe=(bc=(hc=r.features)==null?void 0:hc.scrollToBottom)!=null?bc:{},Te=(vc=(yc=r.features)==null?void 0:yc.scrollBehavior)!=null?vc:{},oe=`${(wc=typeof r.persistState=="object"?(xc=r.persistState)==null?void 0:xc.keyPrefix:void 0)!=null?wc:"persona-"}event-stream`,X=Ne?new ha(oe):null,se=(Sc=(Ac=(Cc=r.features)==null?void 0:Cc.eventStream)==null?void 0:Ac.maxEvents)!=null?Sc:2e3,fe=Ne?new fa(se,X):null,pe=Ne?new ba:null,K=null,ae=!1,Be=null,ee=0;X==null||X.open().then(()=>fe==null?void 0:fe.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Z={onCopy:l=>{var p,h;s.emit("message:copy",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;s.emit("message:feedback",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},ne=(Tc=r.statusIndicator)!=null?Tc:{},st=l=>{var p,h,b,T;return l==="idle"?(p=ne.idleText)!=null?p:Ln.idle:l==="connecting"?(h=ne.connectingText)!=null?h:Ln.connecting:l==="connected"?(b=ne.connectedText)!=null?b:Ln.connected:l==="error"?(T=ne.errorText)!=null?T:Ln.error:Ln[l]};function at(l,p,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=p,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=p}let nt=xm({config:r,showClose:F()}),{wrapper:Me,panel:he,pillRoot:Ge}=nt.shell,J=nt.panelElements,{container:ue,body:Le,messagesWrapper:Xe,suggestions:Gt,textarea:Pe,sendButton:Ue,sendButtonWrapper:rt,composerForm:Nt,statusText:yn,introTitle:wr,introSubtitle:Sn,closeButton:Ke,iconHolder:Ft,headerTitle:q,headerSubtitle:ke,header:Ce,footer:_e,actionsRow:it,leftActions:pt,rightActions:ot}=J,Mt=J.setSendButtonMode,V=J.micButton,St=J.micButtonWrapper,de=J.attachmentButton,me=J.attachmentButtonWrapper,Ee=J.attachmentInput,ut=J.attachmentPreviewsContainer;ue.classList.add("persona-relative"),Le.classList.add("persona-relative");let en=12,an=()=>{var l;return(l=qe.label)!=null?l:""},wn=()=>{var l;return(l=qe.iconName)!=null?l:"arrow-down"},Ot=()=>qe.enabled!==!1,et=()=>{var l;return(l=Te.mode)!=null?l:"follow"},_t=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},mt=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");mt.type="button",mt.style.display="none",mt.setAttribute("data-persona-scroll-to-bottom","true");let tn=y("span","persona-flex persona-items-center"),rr=y("span",""),Wn=y("span","");Wn.setAttribute("data-persona-scroll-to-bottom-count",""),Wn.style.display="none",mt.append(tn,rr,Wn),ue.appendChild(mt);let ln=y("div","persona-stream-anchor-spacer");ln.setAttribute("aria-hidden","true"),ln.setAttribute("data-persona-anchor-spacer",""),ln.style.flexShrink="0",ln.style.pointerEvents="none",ln.style.height="0px",Le.appendChild(ln);let On=()=>{let p=_e.style.display==="none"?0:_e.offsetHeight;mt.style.bottom=`${p+en}px`};On();let Cr=()=>{let l=!!an();mt.setAttribute("aria-label",an()||"Jump to latest"),mt.title=an(),mt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),tn.innerHTML="";let p=Se(wn(),"14px","currentColor",2);p?(tn.appendChild(p),tn.style.display=""):tn.style.display="none",rr.textContent=an(),rr.style.display=l?"":"none"};Cr();let Ct=null,jn=null,Ar=o.find(l=>l.renderHeader);if(Ar!=null&&Ar.renderHeader){let l=Ar.renderHeader({config:r,defaultRenderer:()=>{let p=zo({config:r,showClose:F()});return ma(ue,p,r),p.header},onClose:()=>be(!1,"user")});if(l){let p=ue.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Ce=l,nt.header.element=l)}}let Nr=()=>{var p,h,b,T;if(!fe)return;if(ae=!0,!K&&fe&&(K=Rm({buffer:fe,getFullHistory:()=>fe.getAllFromStore(),onClose:()=>ur(),config:r,plugins:o,getThroughput:()=>{var D;return(D=pe==null?void 0:pe.getMetric())!=null?D:{status:"idle"}}})),K&&(Le.style.display="none",(p=_e.parentNode)==null||p.insertBefore(K.element,_e),K.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${_n.actionIconColor}`;let D=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let l=()=>{if(!ae)return;let D=Date.now();D-ee>=200&&(K==null||K.update(),ee=D),Be=requestAnimationFrame(l)};ee=0,Be=requestAnimationFrame(l),Un(),s.emit("eventStream:opened",{timestamp:Date.now()})},ur=()=>{var l,p,h;if(ae){if(ae=!1,K&&K.element.remove(),Le.style.display="",xt){xt.style.boxShadow="";let b=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&xt.classList.remove(T))}Be!==null&&(cancelAnimationFrame(Be),Be=null),Un(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(Ne){let l=(Mc=(Ec=r.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");xt=y("button",p),xt.style.width="28px",xt.style.height="28px",xt.style.color=_n.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let h=Se("activity","18px","currentColor",1.5);h&&xt.appendChild(h);let b=J.clearChatButtonWrapper,T=J.closeButtonWrapper,D=b||T;D&&D.parentNode===Ce?Ce.insertBefore(xt,D):Ce.appendChild(xt),xt.addEventListener("click",()=>{ae?ur():Nr()})}let Co=l=>{var T,D,U,_,H;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(T=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?T: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 le=l.querySelector("[data-persona-composer-form]");le!=null&&le.parentNode?le.parentNode.insertBefore(h,le):l.insertBefore(h,l.firstChild)}if(!((D=l.querySelector("[data-persona-composer-attachment-input]"))!=null?D:l.querySelector('input[type="file"]'))){let le=y("input");le.type="file",le.setAttribute("data-persona-composer-attachment-input",""),le.accept=((U=p.allowedTypes)!=null?U:Qr).join(","),le.multiple=((_=p.maxFiles)!=null?_:4)>1,le.style.display="none",le.setAttribute("aria-label",(H=p.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(le)}},Sr=o.find(l=>l.renderComposer);if(Sr!=null&&Sr.renderComposer){let l=r.composer,p=Sr.renderComposer({config:r,defaultRenderer:()=>Ti({config:r}).footer,onSubmit:h=>{var U;if(!O||O.isStreaming())return;let b=h.trim(),T=(U=Ct==null?void 0:Ct.hasAttachments())!=null?U:!1;if(!b&&!T)return;Re();let D;T&&(D=[],D.push(...Ct.getContentParts()),b&&D.push(Zi(b))),O.sendMessage(b,{contentParts:D}),T&&Ct.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:((kc=r.voiceRecognition)==null?void 0:kc.enabled)===!0?()=>{jn==null||jn()}:void 0});p&&(nt.replaceComposer(p),_e=nt.composer.footer)}let Ao=l=>{let p=(...ce)=>{for(let Y of ce){let xe=l.querySelector(Y);if(xe)return xe}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),D=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");h&&(Nt=h),b&&(Pe=b),T&&(Ue=T),D&&(V=D,St=D.parentElement),U&&(yn=U);let _=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Gt=_);let H=p("[data-persona-composer-attachment-button]",".persona-attachment-button");H&&(de=H,me=H.parentElement),Ee=p("[data-persona-composer-attachment-input]",'input[type="file"]'),ut=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(it=le)};Co(_e),Ao(_e);let $n=(Rc=(Lc=r.layout)==null?void 0:Lc.contentMaxWidth)!=null?Rc:N()?(Wc=(Pc=(Ic=r.launcher)==null?void 0:Ic.composerBar)==null?void 0:Pc.contentMaxWidth)!=null?Wc:"720px":void 0;if($n&&(Xe.style.maxWidth=$n,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%"),$n&&Nt&&!N()&&(Nt.style.maxWidth=$n,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),$n&&Gt&&!N()&&(Gt.style.maxWidth=$n,Gt.style.marginLeft="auto",Gt.style.marginRight="auto"),$n&&ut&&!N()&&(ut.style.maxWidth=$n,ut.style.marginLeft="auto",ut.style.marginRight="auto"),(Bc=r.attachments)!=null&&Bc.enabled&&Ee&&ut){Ct=oa.fromConfig(r.attachments),Ct.setPreviewsContainer(ut),Ee.addEventListener("change",h=>{let b=h.target;Ct==null||Ct.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,p=eg(l);ue.appendChild(p)}(()=>{var b,T;let l=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},p=D=>{switch(D){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Xe;case"footer-top":return Gt;case"composer":return Nt;case"footer-bottom":return yn;default:return null}},h=(D,U)=>{var _;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Ce.insertBefore(U,Ce.firstChild);else if(D==="header-right")Ce.appendChild(U);else{let H=Ce.querySelector(".persona-flex-col");H?(_=H.parentNode)==null||_.insertBefore(U,H.nextSibling):Ce.appendChild(U)}break;case"body-top":{let H=Le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(U):Le.insertBefore(U,Le.firstChild);break}case"body-bottom":Le.appendChild(U);break;case"footer-top":Gt.replaceWith(U);break;case"footer-bottom":yn.replaceWith(U);break;default:break}};for(let[D,U]of Object.entries(l))if(U)try{let _=U({config:r,defaultContent:()=>p(D)});_&&h(D,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,_)}})();let Yr=l=>{var U,_;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 T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")ws.has(T)?ws.delete(T):ws.add(T),Am(T,b);else if(D==="tool")Cs.has(T)?Cs.delete(T):Cs.add(T),Sm(T,b,r);else if(D==="approval"){let H=r.approval!==!1?r.approval:void 0,le=((U=H==null?void 0:H.detailsDisplay)!=null?U:"collapsed")==="expanded",ce=(_=Ei.get(T))!=null?_:le;Ei.set(T,!ce),km(T,b,r)}Lr.delete(T)};Xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))}),Xe.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))});let Fr=new Map,Zr=null,eo="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(l,p)=>{let{icon:h,label:b}=So[p];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let T=Se(h,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},to=()=>{Xe.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var D;let h=p.closest("[data-actions-for]"),b=(D=h==null?void 0:h.getAttribute("data-actions-for"))!=null?D:null;To(p,b&&b===Zr?eo:"idle")})};Xe.addEventListener("click",l=>{var U;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 T=b.getAttribute("data-actions-for");if(!T)return;let D=h.getAttribute("data-action");if(D==="copy"){let H=O.getMessages().find(le=>le.id===T);if(H&&Z.onCopy){let le=H.content||"";navigator.clipboard.writeText(le).then(()=>{h.classList.add("persona-message-action-success");let ce=Se("check",14,"currentColor",2);ce&&(h.innerHTML="",h.appendChild(ce)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=Se("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ce)}),Z.onCopy(H)}}else if(D==="read-aloud")O.toggleReadAloud(T);else if(D==="upvote"||D==="downvote"){let H=((U=Fr.get(T))!=null?U:null)===D,le=D==="upvote"?"thumbs-up":"thumbs-down";if(H){Fr.delete(T),h.classList.remove("persona-message-action-active");let ce=Se(le,14,"currentColor",2);ce&&(h.innerHTML="",h.appendChild(ce))}else{let ce=D==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${ce}"]`);if(Y){Y.classList.remove("persona-message-action-active");let ze=Se(ce==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Y.innerHTML="",Y.appendChild(ze))}Fr.set(T,D),h.classList.add("persona-message-action-active");let xe=Se(le,14,"currentColor",2);xe&&(xe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(xe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=O.getMessages().find(tt=>tt.id===T);Ae&&Z.onFeedback&&Z.onFeedback({type:D,messageId:Ae.id,message:Ae})}}}),Xe.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 T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-approval-action");if(!D)return;let U=D==="approve"?"approved":"denied",H=O.getMessages().find(ce=>ce.id===T);if(!(H!=null&&H.approval))return;let le=b.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?O.resolveWebMcpApproval(T,U):O.resolveApproval(H.approval,U)});let Tt=null,Vn=null,Kn={artifacts:[],selectedId:null},Rn=!1,kt={current:null};Xe.addEventListener("click",l=>{var Y,xe,Oe,Ae,tt;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=(xe=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:Oe.call(xe,{type:"download",artifactId:b}))===!0)return;let D=O.getArtifactById(b),U=D==null?void 0:D.markdown,_=(D==null?void 0:D.title)||"artifact";if(!U){let ze=h.closest("[data-open-artifact]"),bt=ze==null?void 0:ze.closest("[data-message-id]"),ct=bt==null?void 0:bt.getAttribute("data-message-id");if(ct){let We=O.getMessages().find(je=>je.id===ct);if(We!=null&&We.rawContent)try{let je=JSON.parse(We.rawContent);U=(Ae=je==null?void 0:je.props)==null?void 0:Ae.markdown,_=((tt=je==null?void 0:je.props)==null?void 0:tt.title)||_}catch{}}}if(!U)return;let H=new Blob([U],{type:"text/markdown"}),le=URL.createObjectURL(H),ce=document.createElement("a");ce.href=le,ce.download=`${_}.md`,ce.click(),URL.revokeObjectURL(le)}),Xe.addEventListener("click",l=>{var D,U,_;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(U=(D=r.features)==null?void 0:D.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:_.call(U,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Rn=!1,O.selectArtifact(b),Xn())}),Xe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let or=J.composerOverlay,sr=(l,p,h)=>{var _,H,le,ce;let b=p.trim();if(!b||!kt.current)return;let T=(_=l.getAttribute("data-tool-call-id"))!=null?_:"",D=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(H=h.values)!=null?H:h.source==="multi"?b.split(", "):[b],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),us(or,T);let U=kt.current.getMessages().find(Y=>{var xe;return((xe=Y.toolCall)==null?void 0:xe.id)===T});(le=U==null?void 0:U.agentMetadata)!=null&&le.awaitingLocalTool?kt.current.resolveAskUserQuestion(U,(ce=h.structured)!=null?ce:b):kt.current.sendMessage(b)},Gn=l=>{var T;let p=kt.current;if(!p)return;let h=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",b=p.getMessages().find(D=>{var U;return((U=D.toolCall)==null?void 0:U.id)===h});b&&p.persistAskUserQuestionProgress(b,{answers:za(l,b),currentIndex:dr(l)})},no=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),_r=l=>{var T,D,U;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let p=dr(l),h=ps(l);if(p>=h-1)return;let b=(U=kt.current)==null?void 0:U.getMessages().find(_=>{var H;return((H=_.toolCall)==null?void 0:H.id)===l.getAttribute("data-tool-call-id")});b&&(Va(l,b,r,p+1),Gn(l))};or.addEventListener("click",l=>{var D,U,_,H,le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct;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 T=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let He=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),us(or,He);let We=(U=kt.current)==null?void 0:U.getMessages().find(je=>{var Qe;return((Qe=je.toolCall)==null?void 0:Qe.id)===He});(_=We==null?void 0:We.agentMetadata)!=null&&_.awaitingLocalTool&&((H=kt.current)==null||H.markAskUserQuestionResolved(We),(le=kt.current)==null||le.resolveAskUserQuestion(We,"(dismissed)"));return}if(T==="pick"){let He=h.getAttribute("data-option-label");if(!He)return;let We=b.getAttribute("data-multi-select")==="true",je=yo(b);if(je&&We){let Qe=_o(b)[dr(b)],wt=new Set(Array.isArray(Qe)?Qe:[]);wt.has(He)?wt.delete(He):wt.add(He),vo(b,Array.from(wt)),Gn(b);return}if(je){vo(b,He),Gn(b),_r(b);return}if(We){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let wt=b.querySelector('[data-ask-user-action="submit-multi"]');wt&&(wt.disabled=Ki(b).length===0);return}sr(b,He,{source:"pick",values:[He]});return}if(T==="submit-multi"){let He=Ki(b);if(He.length===0)return;sr(b,He.join(", "),{source:"multi",values:He});return}if(T==="open-free-text"){let He=b.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let We=He.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus()}return}if(T==="focus-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(T==="submit-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]'),We=(ce=He==null?void 0:He.value)!=null?ce:"";if(!We.trim())return;if(yo(b)){vo(b,We.trim()),Gn(b),_r(b);return}sr(b,We,{source:"free-text"});return}if(T==="next"||T==="back"){if(!kt.current)return;let He=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",We=kt.current.getMessages().find(Fe=>{var De;return((De=Fe.toolCall)==null?void 0:De.id)===He});if(!We)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(Oe=(xe=je==null?void 0:je.value)==null?void 0:xe.trim())!=null?Oe:"";if(Qe){let Fe=_o(b)[dr(b)];(typeof Fe!="string"||Fe!==Qe)&&vo(b,Qe)}let wt=T==="next"?1:-1,W=dr(b)+wt;Va(b,We,r,W),Gn(b);return}if(T==="submit-all"){if(!kt.current)return;let He=(Ae=b.getAttribute("data-tool-call-id"))!=null?Ae:"",We=kt.current.getMessages().find(Fe=>{var De;return((De=Fe.toolCall)==null?void 0:De.id)===He});if(!We)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(ze=(tt=je==null?void 0:je.value)==null?void 0:tt.trim())!=null?ze:"";Qe&&vo(b,Qe);let wt=za(b,We);kt.current.persistAskUserQuestionProgress(We,{answers:wt,currentIndex:dr(b)});let W=no(wt);sr(b,W||"(submitted)",{source:"submit-all",structured:wt});return}if(T==="skip"){if(!kt.current)return;let He=(bt=b.getAttribute("data-tool-call-id"))!=null?bt:"",We=kt.current.getMessages().find(De=>{var ge;return((ge=De.toolCall)==null?void 0:ge.id)===He});if(!We)return;let je=yo(b),Qe=dr(b),wt=ps(b),W=Qe>=wt-1;if(!je){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),us(or,He),(ct=We.agentMetadata)!=null&&ct.awaitingLocalTool&&(kt.current.markAskUserQuestionResolved(We),kt.current.resolveAskUserQuestion(We,"(dismissed)"));return}vo(b,"");let Fe=b.querySelector('[data-ask-free-text-input="true"]');if(Fe&&(Fe.value=""),W){let De=za(b,We),ge=no(De);sr(b,ge||"(skipped)",{source:"submit-all",structured:De});return}Va(b,We,r,Qe+1),Gn(b);return}}),or.addEventListener("keydown",l=>{var D;if(l.key!=="Enter")return;let h=l.target;if(!((D=h.matches)!=null&&D.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let T=h.value;if(T.trim()){if(yo(b)){vo(b,T.trim()),Gn(b),_r(b);return}sr(b,T,{source:"free-text"})}});let ro=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=or.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),D=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];D&&(l.preventDefault(),D.click())};document.addEventListener("keydown",ro);let Qn=null,$t=null,Bn=null,ar=null,oo=()=>{};function Or(){ar==null||ar(),ar=null}let so=()=>{var U;if(!Qn||!$t)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((U=n.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){$t.style.removeProperty("position"),$t.style.removeProperty("left"),$t.style.removeProperty("top"),$t.style.removeProperty("bottom"),$t.style.removeProperty("width"),$t.style.removeProperty("z-index");return}let b=Qn.firstElementChild;if(!b||b===$t)return;let T=10;$t.style.position="absolute",$t.style.top="0",$t.style.bottom="0",$t.style.width=`${T}px`,$t.style.zIndex="5";let D=b.offsetWidth-T/2;$t.style.left=`${Math.max(0,D)}px`},Tr=()=>{},Xn=()=>{var h,b,T,D,U;if(!Tt||!pr(r))return;Li(n,r),Ii(n,r),Tr();let l=(D=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,p=he.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),Tt.update(Kn),Rn?(Tt.setMobileOpen(!1),Tt.element.classList.add("persona-hidden"),(U=Tt.backdrop)==null||U.classList.add("persona-hidden")):Kn.artifacts.length>0&&(Tt.element.classList.remove("persona-hidden"),Tt.setMobileOpen(!0)),oo()};if(pr(r)){he.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ue),Tt=Dm(r,{onSelect:h=>{var b;return(b=kt.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Rn=!0,Xn()}}),Tt.element.classList.add("persona-hidden"),Qn=p,p.appendChild(l),p.appendChild(Tt.element),Tt.backdrop&&he.appendChild(Tt.backdrop),he.appendChild(p),oo=()=>{var b,T,D,U;if(!Qn||!Tt)return;if(!(((D=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){Bn==null||Bn(),Bn=null,Or(),$t&&($t.remove(),$t=null),Tt.element.style.removeProperty("width"),Tt.element.style.removeProperty("maxWidth");return}if(!$t){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let H=n.ownerDocument,le=(U=H.defaultView)!=null?U:window,ce=Y=>{var bt,ct;if(!Tt||Y.button!==0||n.classList.contains("persona-artifact-narrow-host")||le.innerWidth<=640)return;Y.preventDefault(),Or();let xe=Y.clientX,Oe=Tt.element.getBoundingClientRect().width,Ae=(ct=(bt=r.features)==null?void 0:bt.artifacts)==null?void 0:ct.layout,tt=He=>{let We=Qn.getBoundingClientRect().width,je=n.classList.contains("persona-artifact-appearance-seamless"),Qe=je?0:Om(Qn,le),wt=je?0:_.getBoundingClientRect().width||6,W=Oe-(He.clientX-xe),Fe=$m(W,We,Qe,wt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);Tt.element.style.width=`${Fe}px`,Tt.element.style.maxWidth="none",so()},ze=()=>{H.removeEventListener("pointermove",tt),H.removeEventListener("pointerup",ze),H.removeEventListener("pointercancel",ze),ar=null;try{_.releasePointerCapture(Y.pointerId)}catch{}};ar=ze,H.addEventListener("pointermove",tt),H.addEventListener("pointerup",ze),H.addEventListener("pointercancel",ze);try{_.setPointerCapture(Y.pointerId)}catch{}};_.addEventListener("pointerdown",ce),$t=_,Qn.insertBefore(_,Tt.element),Bn=()=>{_.removeEventListener("pointerdown",ce)}}if($t){let _=Kn.artifacts.length>0&&!Rn;$t.classList.toggle("persona-hidden",!_),so()}},Tr=()=>{var le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct,He,We,je,Qe;if(!M||!Tt||((ce=(le=r.launcher)==null?void 0:le.sidebarMode)!=null?ce:!1)||An(r)&&vr(r).reveal==="emerge")return;let b=(Y=n.ownerDocument.defaultView)!=null?Y:window,T=(Oe=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?Oe:!0,D=(tt=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?tt:640;if(T&&b.innerWidth<=D||!_m(r,M))return;let U=(ct=(bt=(ze=r.launcher)==null?void 0:ze.width)!=null?bt:r.launcherWidth)!=null?ct:Xr,_=(Qe=(je=(We=(He=r.features)==null?void 0:He.artifacts)==null?void 0:We.layout)==null?void 0:je.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Kn.artifacts.length>0&&!Rn?(he.style.width=_,he.style.maxWidth=_):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{Xn()}),Vn.observe(he))}else he.appendChild(ue),N()&&Ge&&(J.peekBanner&&Ge.appendChild(J.peekBanner),Ge.appendChild(_e));n.appendChild(Me),Ge&&n.appendChild(Ge);let ye=()=>{var Fe,De,ge,jt,Ut,Jt,At,Qt,Zn,sn,Je,Rt,pn,cr,er,Io,Po,ss,as,Yt,Wo,go,fo,Kr,Ro,hr,Ze,fn;if(N()){he.style.width="100%",he.style.maxWidth="100%";let Kt=(De=(Fe=r.launcher)==null?void 0:Fe.composerBar)!=null?De:{},Vt=Me.dataset.state==="expanded",yt=(ge=Kt.expandedSize)!=null?ge:"anchored";if(!(Vt&&yt!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Et=(Ut=(jt=r.theme)==null?void 0:jt.components)==null?void 0:Ut.panel,Mn=ii(r),Hn=(Nn,Bo)=>{var $s;return Nn==null||Nn===""?Bo:($s=ys(Mn,Nn))!=null?$s:Nn},Hr="1px solid var(--persona-border)",xn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Dn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Hn(Et==null?void 0:Et.border,Hr),ue.style.borderRadius=Hn(Et==null?void 0:Et.borderRadius,Dn),ue.style.boxShadow=Hn(Et==null?void 0:Et.shadow,xn),ue.style.overflow="hidden";return}let l=An(r),p=(At=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?At:!1,h=l||p||((Zn=(Qt=r.launcher)==null?void 0:Qt.fullHeight)!=null?Zn:!1),b=((sn=r.launcher)==null?void 0:sn.enabled)===!1,T=(Rt=(Je=r.theme)==null?void 0:Je.components)==null?void 0:Rt.panel,D=ii(r),U=(Kt,Vt)=>{var yt;return Kt==null||Kt===""?Vt:(yt=ys(D,Kt))!=null?yt:Kt},_=(pn=n.ownerDocument.defaultView)!=null?pn:window,H=(er=(cr=r.launcher)==null?void 0:cr.mobileFullscreen)!=null?er:!0,le=(Po=(Io=r.launcher)==null?void 0:Io.mobileBreakpoint)!=null?Po:640,ce=_.innerWidth<=le,Y=H&&ce&&M,xe=(as=(ss=r.launcher)==null?void 0:ss.position)!=null?as:"bottom-left",Oe=xe==="bottom-left"||xe==="top-left",Ae=(Wo=(Yt=r.launcher)==null?void 0:Yt.zIndex)!=null?Wo:In,tt=p||Y?"none":"1px solid var(--persona-border)",ze=Y?"none":p?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&&(ze="none",tt="none");let bt=p||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=U(T==null?void 0:T.border,tt),He=U(T==null?void 0:T.shadow,ze),We=U(T==null?void 0:T.borderRadius,bt),je=Le.scrollTop;n.style.cssText="",Me.style.cssText="",he.style.cssText="",ue.style.cssText="",Le.style.cssText="",_e.style.cssText="";let Qe=()=>{var Vt;if(je<=0)return;((Vt=Le.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(Le.scrollTop===je)return;let yt=Le.scrollHeight-Le.clientHeight;yt<=0||(Le.scrollTop=Math.min(je,yt))})};if(Y){Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Me.style.cssText=`
33
33
  position: fixed !important;
34
34
  inset: 0 !important;
35
35
  width: 100% !important;
@@ -54,7 +54,7 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
54
54
  padding: 0 !important;
55
55
  box-shadow: none !important;
56
56
  border-radius: 0 !important;
57
- `,me.style.cssText=`
57
+ `,ue.style.cssText=`
58
58
  display: flex !important;
59
59
  flex-direction: column !important;
60
60
  flex: 1 1 0% !important;
@@ -65,11 +65,11 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
65
65
  overflow: hidden !important;
66
66
  border-radius: 0 !important;
67
67
  border: none !important;
68
- `,ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",_e.style.flexShrink="0",W=!0,Xe();return}let vt=(fo=(go=r==null?void 0:r.launcher)==null?void 0:go.width)!=null?fo:r==null?void 0:r.launcherWidth,P=vt!=null?vt:Xr;if(!p&&!l)y&&h?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=P,he.style.maxWidth=P);else if(l)if(xr(r).reveal==="emerge"){let qt=xr(r).width;he.style.width=qt,he.style.maxWidth=qt}else he.style.width="100%",he.style.maxWidth="100%";if(Mr(),he.style.boxShadow=Re,he.style.borderRadius=Pe,me.style.border=ct,me.style.borderRadius=Pe,l&&!Z&&(S==null?void 0:S.border)===void 0&&(me.style.border="none",xr(r).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),h&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",y&&(n.style.width="100%"),Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.height="100%",y&&(Ee.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",he.style.overflow="hidden",me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.overflowY="auto",_e.style.flexShrink="0"),Ee.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!y&&!l&&((Kr=wr[xe])!=null?Kr:wr["bottom-right"]).split(" ").forEach(qt=>Ee.classList.add(qt)),p){let Ut=(yr=(Ro=r.launcher)==null?void 0:Ro.sidebarWidth)!=null?yr:"420px";Ee.style.cssText=`
68
+ `,Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.overflowY="auto",_e.style.flexShrink="0",L=!0,Qe();return}let wt=(fo=(go=r==null?void 0:r.launcher)==null?void 0:go.width)!=null?fo:r==null?void 0:r.launcherWidth,W=wt!=null?wt:Xr;if(!p&&!l)b&&h?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=W,he.style.maxWidth=W);else if(l)if(vr(r).reveal==="emerge"){let Vt=vr(r).width;he.style.width=Vt,he.style.maxWidth=Vt}else he.style.width="100%",he.style.maxWidth="100%";if(Tr(),he.style.boxShadow=He,he.style.borderRadius=We,ue.style.border=ct,ue.style.borderRadius=We,l&&!Y&&(T==null?void 0:T.border)===void 0&&(ue.style.border="none",vr(r).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),h&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",b&&(n.style.width="100%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",b&&(Me.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",he.style.overflow="hidden",ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.overflowY="auto",_e.style.flexShrink="0"),Me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!b&&!l&&((Kr=xr[xe])!=null?Kr:xr["bottom-right"]).split(" ").forEach(Vt=>Me.classList.add(Vt)),p){let Kt=(hr=(Ro=r.launcher)==null?void 0:Ro.sidebarWidth)!=null?hr:"420px";Me.style.cssText=`
69
69
  position: fixed !important;
70
70
  top: 0 !important;
71
71
  bottom: 0 !important;
72
- width: ${Ut} !important;
72
+ width: ${Kt} !important;
73
73
  height: 100vh !important;
74
74
  max-height: 100vh !important;
75
75
  margin: 0 !important;
@@ -77,7 +77,7 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
77
77
  display: flex !important;
78
78
  flex-direction: column !important;
79
79
  z-index: ${Ae} !important;
80
- ${Ne?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
80
+ ${Oe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
81
81
  `,he.style.cssText=`
82
82
  position: relative !important;
83
83
  display: flex !important;
@@ -89,9 +89,9 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
89
89
  min-height: 0 !important;
90
90
  margin: 0 !important;
91
91
  padding: 0 !important;
92
- box-shadow: ${Re} !important;
93
- border-radius: ${Pe} !important;
94
- `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),me.style.cssText=`
92
+ box-shadow: ${He} !important;
93
+ border-radius: ${We} !important;
94
+ `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),ue.style.cssText=`
95
95
  display: flex !important;
96
96
  flex-direction: column !important;
97
97
  flex: 1 1 0% !important;
@@ -100,37 +100,37 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
100
100
  min-height: 0 !important;
101
101
  max-height: 100% !important;
102
102
  overflow: hidden !important;
103
- border-radius: ${Pe} !important;
103
+ border-radius: ${We} !important;
104
104
  border: ${ct} !important;
105
105
  `,_e.style.cssText=`
106
106
  flex-shrink: 0 !important;
107
107
  border-top: none !important;
108
108
  padding: 8px 16px 12px 16px !important;
109
- `}if(!y&&!l){let Ut="max-height: -moz-available !important; max-height: stretch !important;",qt=p?"":"padding-top: 1.25em !important;",ht=p?"":`z-index: ${(gn=(nt=r.launcher)==null?void 0:nt.zIndex)!=null?gn:En} !important;`;Ee.style.cssText+=Ut+qt+ht}Xe()};be(),xs(n,r),Ei(n,r),ki(n,r);let ut=[];ut.push(()=>{document.removeEventListener("keydown",ro)});let tn=null,un=null;ut.push(()=>{tn==null||tn(),tn=null,un==null||un(),un=null}),jn&&ut.push(()=>{jn==null||jn.disconnect(),jn=null}),ut.push(()=>{Wn==null||Wn(),Wn=null,$r(),Ft&&(Ft.remove(),Ft=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Be&&ut.push(()=>{We!==null&&(cancelAnimationFrame(We),We=null),K==null||K.destroy(),K=null,fe==null||fe.destroy(),fe=null,Q=null});let Er=null,Es=()=>{Er&&(Er(),Er=null),r.colorScheme==="auto"&&(Er=Ju(()=>{xs(n,r)}))};Es(),ut.push(()=>{Er&&(Er(),Er=null)});let qr=(Hc=r.features)==null?void 0:Hc.streamAnimation;if(qr!=null&&qr.type&&qr.type!=="none"){let l=la(qr.type,qr.plugins);l&&(sl(l,n),ut.push(()=>dm(n)))}let Mo=Mm(Ge),kr=null,_,Go=l=>{var y,S;if(!_)return;let p=l!=null?l:_.getMessages(),h=((S=(y=r.features)==null?void 0:y.suggestReplies)==null?void 0:S.enabled)!==!1?yu(p):null;h?Mo.render(h,_,Ie,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(B=>B.role==="user")?Mo.render([],_,Ie,p):Mo.render(r.suggestionChips,_,Ie,p,r.suggestionChipsConfig)},Lr=!1,Pr=tm(),Ur=new Map,Ir=new Map,gr=new Map,Qo=0,wa=cs()!==null,Xn=li(),Jn=0,fr=null,hr=!1,Eo=!1,zr=0,An=null,Wr=null,Xo=!1,ko=!1,Jo=null,Ca=4,Yo=24,Aa=80,Zo=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ks=(Dc=(Bc=r.voiceRecognition)==null?void 0:Bc.autoResume)!=null?Dc:!1,ar=l=>{s.emit("voice:state",{active:yt.active,source:l,timestamp:Date.now()})},$n=()=>{m(l=>({...l,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Sa=()=>{var y,S;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=Ml(d.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);yt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<cy&&setTimeout(()=>{var B,U;yt.active||(yt.manuallyDeactivated=!1,((U=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:U.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("restore"),_.isVoiceActive()&&os()}):Ha("restore"))},1e3)},Ta=()=>_?Qm(_.getMessages()).filter(l=>!l.__skipPersist):[];function es(l){if(!(i!=null&&i.save))return;let h={messages:l?Qm(l):_?Ta():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let jr=null,Ls=()=>Ee.querySelector("#persona-scroll-container")||ke,ao=()=>{jr!==null&&(cancelAnimationFrame(jr),jr=null),hr=!1},Ps=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),Eo=!1,ao()},Is=()=>{zr>0?(Pn.textContent=String(zr),Pn.style.display="",pt.setAttribute("aria-label",`${sn()||"Jump to latest"} (${zr} new)`)):(Pn.textContent="",Pn.style.display="none",pt.setAttribute("aria-label",sn()||"Jump to latest"))},Ws=()=>{zr!==0&&(zr=0,Is())},Rs=()=>rt()==="follow"?!Xn.isFollowing():!Uo(ke,Yo),qn=()=>{if(!Nt()||ie){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==me&&me.appendChild(pt),On();let p=Jr(ke)>0&&Rs();p||Ws(),pt.style.display=p?"":"none"},ts=()=>{Xn.pause()&&(Ps(),qn())},Rr=()=>{Xn.resume(),Ws(),qn()},Hr=(l=!1)=>{rt()==="follow"&&Xn.isFollowing()&&(!l&&!Lr||(fr!==null&&(cancelAnimationFrame(fr),fr=null),Eo=!0,fr=requestAnimationFrame(()=>{fr=null,Eo=!1,Xn.isFollowing()&&Ma(Ls(),l?220:140)})))},Hs=(l,p,h,y=()=>!0)=>{let S=l.scrollTop,B=p(),U=B-S;ao();let O=performance.now();hr=!0;let H=pe=>1-Math.pow(1-pe,3),de=pe=>{if(!y()){ao();return}let Z=p();Z!==B&&(B=Z,U=B-S);let xe=pe-O,Ne=Math.min(xe/h,1),Ae=H(Ne),ot=S+U*Ae;l.scrollTop=ot,Jn=l.scrollTop,Ne<1?jr=requestAnimationFrame(de):(l.scrollTop=B,Jn=l.scrollTop,jr=null,hr=!1)};jr=requestAnimationFrame(de)},Ma=(l,p=500)=>{let h=Jr(l)-l.scrollTop;if(Math.abs(h)<1){Jn=l.scrollTop;return}if(Math.abs(h)>=Aa){ao(),hr=!0,l.scrollTop=Jr(l),Jn=l.scrollTop,hr=!1;return}Hs(l,()=>Jr(l),p,()=>Xn.isFollowing())},Bs=()=>{let l=Ls();hr=!0,l.scrollTop=Jr(l),Jn=l.scrollTop,hr=!1,qn()},Ds=l=>{an.style.height=`${Math.max(0,Math.round(l))}px`,An&&(An.spacerHeight=Math.max(0,l))},Lo=()=>{Wr!==null&&(cancelAnimationFrame(Wr),Wr=null),ao(),An=null,an.style.height="0px"},Ea=l=>{Wr!==null&&cancelAnimationFrame(Wr),Wr=requestAnimationFrame(()=>{var de;Wr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=ke.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,S=h;for(;S&&S!==ke;)y+=S.offsetTop,S=S.offsetParent;let B=(de=An==null?void 0:An.spacerHeight)!=null?de:0,U=ke.scrollHeight-B,{targetScrollTop:O,spacerHeight:H}=am({anchorOffsetTop:y,topOffset:Dt(),viewportHeight:ke.clientHeight,contentHeight:U});An={initialSpacerHeight:H,contentHeightAtAnchor:U,spacerHeight:H},Ds(H),Hs(ke,()=>O,220)})},ka=()=>{if(rt()==="follow"){if(!Xn.isFollowing()||Uo(ke,1))return;Hr(!Lr);return}if(An&&An.initialSpacerHeight>0){let l=ke.scrollHeight-An.spacerHeight,p=im({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:l});p!==An.spacerHeight&&Ds(p)}qn()},La=l=>{let p=rt();p==="follow"?(Rr(),Hr(!0)):p==="anchor-top"&&Ea(l)},Pa=l=>{let p=new Map;l.forEach(h=>{let y=Zo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!ko&&rt()!=="anchor-top"&&Rs()&&(zr+=1,Is(),qn())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Zo.clear(),p.forEach((h,y)=>{Zo.set(y,h)})},Ia=(l,p,h)=>{var ct,Re,Pe,je,Xe,vt;let y=document.createElement("div"),B=(()=>{var De;let P=o.find(He=>He.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),U=(P,De)=>De==null?!1:typeof De=="string"?(P.textContent=De,!0):(P.appendChild(De),!0),O=new Set,H=new Set,de=o.some(P=>P.renderAskUserQuestion),pe=[],Z=[],xe=r.enableComponentStreaming!==!1,Ne=o.some(P=>P.renderApproval)&&r.approval!==!1,Ae=[];if(p.forEach(P=>{var Ze,It,dn,dr,Zn,Po,Io,as,is,Qt,Wo,go,fo,Kr,Ro,yr;O.add(P.id);let De=de&&Fo(P),He=Ne&&P.variant==="approval"&&!!P.approval,ge=!De&&P.role==="assistant"&&!P.variant&&xe&&jm(P);if(!He&&gr.has(P.id)){let nt=l.querySelector(`#wrapper-${P.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),gr.delete(P.id)}if(!ge&&Ir.has(P.id)){let nt=l.querySelector(`#wrapper-${P.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),Ir.delete(P.id)}let $t=Fo(P)?`:${(Ze=P.agentMetadata)!=null&&Ze.askUserQuestionAnswered?"a":"u"}:${(It=P.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=em(P,Qo)+$t,Gt=De||He||ge?null:nm(Pr,P.id,Ot);if(Gt){y.appendChild(Gt.cloneNode(!0)),Fo(P)&&((dn=P.toolCall)!=null&&dn.id)&&((dr=P.agentMetadata)==null?void 0:dr.awaitingLocalTool)===!0&&!((Zn=P.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(H.add(P.toolCall.id),za(P,r,Y.composerOverlay));return}let wt=null,jt=o.find(nt=>!!(P.variant==="reasoning"&&nt.renderReasoning||P.variant==="tool"&&nt.renderToolCall||!P.variant&&nt.renderMessage)),Yn=(Po=r.layout)==null?void 0:Po.messages;if(Fo(P)&&((Io=P.agentMetadata)==null?void 0:Io.askUserQuestionAnswered)===!0){Ur.delete(P.id);let nt=l.querySelector(`#wrapper-${P.id}`);nt==null||nt.removeAttribute("data-preserve-runtime");return}if(Ki(P)&&((is=(as=r.features)==null?void 0:as.suggestReplies)==null?void 0:is.enabled)!==!1)return;if(Fo(P)&&((Wo=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Wo.enabled)!==!1){let nt=o.find(gn=>typeof gn.renderAskUserQuestion=="function");if(nt&&Mt.current){let gn=Ur.get(P.id),Ut=gn!==Ot,qt=null;if(Ut){let{payload:St,complete:Sn}=ps(P),Hn=P.id,Dr=()=>{var bn;return(bn=Mt.current)==null?void 0:bn.getMessages().find(Bn=>Bn.id===Hn)};qt=nt.renderAskUserQuestion({message:P,payload:St,complete:Sn,resolve:bn=>{var Dn;let Bn=Dr();Bn&&((Dn=Mt.current)==null||Dn.resolveAskUserQuestion(Bn,bn))},dismiss:()=>{var Bn,Dn,Ho;let bn=Dr();(Bn=bn==null?void 0:bn.agentMetadata)!=null&&Bn.awaitingLocalTool&&((Dn=Mt.current)==null||Dn.markAskUserQuestionResolved(bn),(Ho=Mt.current)==null||Ho.resolveAskUserQuestion(bn,"(dismissed)"))},config:r})}let ht=gn!=null;if(Ut&&qt===null&&!ht){((go=P.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=P.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(H.add(P.toolCall.id),za(P,r,Y.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),y.appendChild(Xt),pe.push({messageId:P.id,fingerprint:Ot,bubble:qt});return}else{((Kr=P.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Ro=P.agentMetadata)!=null&&Ro.askUserQuestionAnswered)&&(H.add(P.toolCall.id),za(P,r,Y.composerOverlay));return}}else if(He){let nt=o.find(ht=>typeof ht.renderApproval=="function"),Ut=gr.get(P.id)!==Ot,qt=null;if(Ut&&(nt!=null&&nt.renderApproval)){let ht=P.id,Xt=(St,Sn)=>{var Dr,bn,Bn;let Hn=(Dr=Mt.current)==null?void 0:Dr.getMessages().find(Dn=>Dn.id===ht);Hn!=null&&Hn.approval&&(Hn.approval.toolType==="webmcp"?(bn=Mt.current)==null||bn.resolveWebMcpApproval(Hn.id,St):(Bn=Mt.current)==null||Bn.resolveApproval(Hn.approval,St,Sn))};qt=nt.renderApproval({message:P,defaultRenderer:()=>Ti(P,r),config:r,approve:St=>Xt("approved",St),deny:St=>Xt("denied",St)})}if(Ut&&qt===null){let ht=l.querySelector(`#wrapper-${P.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),gr.delete(P.id),wt=Ti(P,r)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${P.id}`,ht.setAttribute("data-wrapper-id",P.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),y.appendChild(ht),Ae.push({messageId:P.id,fingerprint:Ot,bubble:qt});return}}else if(jt)if(P.variant==="reasoning"&&P.reasoning&&jt.renderReasoning){if(!Ve)return;wt=jt.renderReasoning({message:P,defaultRenderer:()=>gl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&jt.renderToolCall){if(!ve)return;wt=jt.renderToolCall({message:P,defaultRenderer:()=>fl(P,r),config:r})}else jt.renderMessage&&(wt=jt.renderMessage({message:P,defaultRenderer:()=>{let nt=ml(P,h,Yn,r.messageActions,ee,{loadingIndicatorRenderer:B,widgetConfig:r});return P.role!=="user"&&vl(nt,P,r,_),nt},config:r}));if(!wt&&ge){let nt=Vm(P);if(nt){let gn=Ir.get(P.id),Ut=gn!==Ot,qt=r.wrapComponentDirectiveInBubble!==!1,ht=null;if(Ut){let Xt=Um(nt,{config:r,message:P,transform:h});if(Xt)if(qt){let St=document.createElement("div");if(St.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(" "),St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let Sn=document.createElement("div");Sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(Sn)}St.appendChild(Xt),ht=St}else{let St=document.createElement("div");if(St.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",St.id=`bubble-${P.id}`,St.setAttribute("data-message-id",P.id),St.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let Sn=document.createElement("div");Sn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),St.appendChild(Sn)}St.appendChild(Xt),ht=St}}if(ht||gn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${P.id}`,Xt.setAttribute("data-wrapper-id",P.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),qt||Xt.classList.add("persona-w-full"),y.appendChild(Xt),Z.push({messageId:P.id,fingerprint:Ot,bubble:ht});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ve)return;wt=gl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!ve)return;wt=fl(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=Ti(P,r)}else{let nt=(yr=r.layout)==null?void 0:yr.messages;nt!=null&&nt.renderUserMessage&&P.role==="user"?wt=nt.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):nt!=null&&nt.renderAssistantMessage&&P.role==="assistant"?wt=nt.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=ml(P,h,nt,r.messageActions,ee,{loadingIndicatorRenderer:B,widgetConfig:r}),P.role!=="user"&&wt&&vl(wt,P,r,_)}let rn=document.createElement("div");rn.className="persona-flex",rn.id=`wrapper-${P.id}`,rn.setAttribute("data-wrapper-id",P.id),P.role==="user"&&rn.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&rn.classList.add("persona-w-full"),rn.appendChild(wt),rm(Pr,P.id,Ot,rn),y.appendChild(rn)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let He=De.getAttribute("data-persona-ask-sheet-for");He&&!H.has(He)&&ms(Y.composerOverlay,He)}),(Re=(ct=r.features)==null?void 0:ct.toolCallDisplay)!=null&&Re.grouped){let P=[],De=[];p.forEach(He=>{if(He.variant==="tool"&&He.toolCall&&ve){De.push(He);return}De.length>1&&P.push(De),De=[]}),De.length>1&&P.push(De),P.forEach((He,ge)=>{var Ze,It;let $t=He.map(dn=>Array.from(y.children).find(dr=>dr instanceof HTMLElement&&dr.getAttribute("data-wrapper-id")===dn.id)).filter(dn=>!!dn);if($t.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${ge}-${He[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${ge}-${He[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 wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${He.length} tools`,Yn=(It=(Ze=r.toolCall)==null?void 0:Ze.renderGroupedSummary)==null?void 0:It.call(Ze,{messages:He,toolCalls:He.map(dn=>dn.toolCall).filter(dn=>!!dn),defaultSummary:jt,config:r});U(wt,Yn)||(wt.textContent=jt);let rn=document.createElement("div");rn.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(wt,rn),Ot.appendChild(Gt),$t[0].before(Ot),$t.forEach((dn,dr)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),dr<$t.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(dn),rn.appendChild(Zn)})})}om(Pr,O);let ot=p.some(P=>P.role==="assistant"&&P.streaming),ze=p[p.length-1],ft=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Lr&&p.some(P=>P.role==="user")&&!ot&&!ft){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:fa},De=o.find(ge=>ge.renderLoadingIndicator),He=null;if(De!=null&&De.renderLoadingIndicator&&(He=De.renderLoadingIndicator(P)),He===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(He=r.loadingIndicator.render(P)),He===null&&(He=fa()),He){let ge=document.createElement("div"),$t=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;ge.className=$t?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ge.setAttribute("data-typing-indicator","true"),ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ge.appendChild(He);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(ge),y.appendChild(Ot)}}if(!Lr&&p.length>0){let P=p[p.length-1],De={config:r,lastMessage:P,messageCount:p.length},He=o.find($t=>$t.renderIdleIndicator),ge=null;if(He!=null&&He.renderIdleIndicator&&(ge=He.renderIdleIndicator(De)),ge===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(ge=r.loadingIndicator.renderIdle(De)),ge){let $t=document.createElement("div"),Ot=((vt=r.loadingIndicator)==null?void 0:vt.showBubble)!==!1;$t.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$t.setAttribute("data-idle-indicator","true"),$t.appendChild(ge);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild($t),y.appendChild(Gt)}}if(ai(l,y),pe.length>0)for(let{messageId:P,fingerprint:De,bubble:He}of pe){let ge=l.querySelector(`#wrapper-${P}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),Ur.set(P,De))}if(Ur.size>0)for(let P of Ur.keys())O.has(P)||Ur.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:De,bubble:He}of Z){let ge=l.querySelector(`#wrapper-${P}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),Ir.set(P,De))}if(Ir.size>0)for(let P of Ir.keys())O.has(P)||Ir.delete(P);if(Ae.length>0)for(let{messageId:P,fingerprint:De,bubble:He}of Ae){let ge=l.querySelector(`#wrapper-${P}`);ge&&He!==null&&(ge.replaceChildren(He),ge.setAttribute("data-bubble-fp",De),gr.set(P,De))}if(gr.size>0)for(let P of gr.keys())O.has(P)||gr.delete(P)},io=(l,p,h)=>{Ia(l,p,h),to()},lo=null,Wa=()=>{var h;if(lo)return;let l=y=>{let S=y.composedPath();S.includes(Ee)||Je&&S.includes(Je)||T(!1,"user")};lo=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Ns=()=>{var p;if(!lo)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",lo,!0),lo=null};ut.push(()=>Ns());let co=null,Ra=()=>{var h;if(co)return;let l=y=>{y.key==="Escape"&&(y.isComposing||T(!1,"user"))};co=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Fs=()=>{var p;if(!co)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",co,!0),co=null};ut.push(()=>Fs());let po=!1,Os=new Set,ns=()=>{var p,h,y,S;let l=(y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return l||((S=r.features)==null?void 0:S.streamAnimation)},Ue=()=>{var ft,ct,Re,Pe;if(!D())return;let l=Y.peekBanner,p=Y.peekTextNode;if(!l||!p)return;if(M){l.classList.remove("persona-pill-peek--visible");return}let h=(ft=_==null?void 0:_.getMessages())!=null?ft:[],y;for(let je=h.length-1;je>=0;je--){let Xe=h[je];if(Xe.role==="assistant"&&Xe.content){y=Xe;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let S=y.content,B=!!y.streaming,U=ns(),O=pi(U),H=O.type!=="none"?la(O.type,U==null?void 0:U.plugins):null,de=((ct=H==null?void 0:H.isAnimating)==null?void 0:ct.call(H,y))===!0,pe=H!==null&&(B||de);pe&&H&&!Os.has(H.name)&&(sl(H,n),Os.add(H.name));let Z=pe&&(H!=null&&H.containerClass)?H.containerClass:null,xe=(Re=p.dataset.personaPeekStreamClass)!=null?Re:null;xe&&xe!==Z&&(p.classList.remove(xe),delete p.dataset.personaPeekStreamClass),Z&&xe!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),pe?(p.style.setProperty("--persona-stream-step",`${O.speed}ms`),p.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ne=pe?ui(S,O.buffer,H,y,B):S;if(pe&&O.placeholder==="skeleton"&&B&&(!Ne||!Ne.trim())){let je=document.createElement("div"),Xe=da();Xe.classList.add("persona-pill-peek__skeleton"),je.appendChild(Xe),ai(p,je)}else{let je=Math.max(0,Ne.length-100),Xe=Ne.length>100?Ne.slice(-100):Ne,vt=ho(Xe);if(!pe||!H){let P=Ne.length>100?`\u2026${Xe}`:Xe;p.textContent!==P&&(p.textContent=P)}else{let P=vt;(H.wrap==="char"||H.wrap==="word")&&(P=ca(vt,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:je}));let De=document.createElement("div");if(De.innerHTML=P,H.useCaret&&Xe.length>0){let He=mi(),ge=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),$t=ge[ge.length-1];$t!=null&&$t.parentNode?$t.parentNode.insertBefore(He,$t.nextSibling):De.appendChild(He)}ai(p,De),(Pe=H.onAfterRender)==null||Pe.call(H,{container:p,bubble:l,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let ze=Lr||po;l.classList.toggle("persona-pill-peek--visible",ze)};if(D()){let l=Y.peekBanner;if(l){let y=S=>{S.preventDefault(),S.stopPropagation(),T(!0,"user")};l.addEventListener("pointerdown",y),ut.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{po||(po=!0,Ue())},h=()=>{po&&(po=!1,Ue())};he.addEventListener("pointerenter",p),he.addEventListener("pointerleave",h),ut.push(()=>{he.removeEventListener("pointerenter",p),he.removeEventListener("pointerleave",h)}),Je&&(Je.addEventListener("pointerenter",p),Je.addEventListener("pointerleave",h),ut.push(()=>{Je.removeEventListener("pointerenter",p),Je.removeEventListener("pointerleave",h)}))}let C=l=>{var xe,Ne,Ae,ot,ze,ft,ct,Re;let p=(Ne=(xe=r.launcher)==null?void 0:xe.composerBar)!=null?Ne:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",y=(ot=p.bottomOffset)!=null?ot:"16px",S=p.collapsedMaxWidth,B=(ze=p.expandedMaxWidth)!=null?ze:"880px",U=(ft=p.expandedTopOffset)!=null?ft:"5vh",O=(ct=p.modalMaxWidth)!=null?ct:"880px",H=(Re=p.modalMaxHeight)!=null?Re:"min(90vh, 800px)",de="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",Z=Ee.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Je){let Pe=Je.style;Pe.bottom=y,Pe.width=S!=null?S:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=O,Z.maxWidth=de,Z.maxHeight=H,Z.height=H;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${pe})`,Z.top=U,Z.width=B,Z.maxWidth=de}},$=()=>{var H,de,pe,Z,xe,Ne,Ae,ot;if(!N())return;if(D()){let ft=(pe=((de=(H=r.launcher)==null?void 0:H.composerBar)!=null?de:{}).expandedSize)!=null?pe:"anchored",ct=M?"expanded":"collapsed";Ee.dataset.state=ct,Ee.dataset.expandedSize=ft,Je&&(Je.dataset.state=ct,Je.dataset.expandedSize=ft),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),C(M),me.style.display=M?"flex":"none",be(),M?(Wa(),Ra()):(Ns(),Fs()),Ue();return}let l=Cn(r),p=(Z=n.ownerDocument.defaultView)!=null?Z:window,h=(Ne=(xe=r.launcher)==null?void 0:xe.mobileBreakpoint)!=null?Ne:640,y=(ot=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?ot:!0,S=p.innerWidth<=h,B=y&&S&&k,U=xr(r).reveal;M?(Ee.style.removeProperty("display"),Ee.style.display=l?"flex":"",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),nn?nn.element.style.display="none":mn&&(mn.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!B?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.setProperty("display","none","important"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.display="",Ee.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),nn?nn.element.style.display=l?"none":"":mn&&(mn.style.display=l?"none":""))},T=(l,p="user")=>{var B,U;if(!N()||M===l)return;let h=M;M=l,$();let y=(()=>{var Ae,ot,ze,ft,ct,Re,Pe,je,Xe,vt;let O=(ot=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?ot:!1,H=(ze=n.ownerDocument.defaultView)!=null?ze:window,de=(ct=(ft=r.launcher)==null?void 0:ft.mobileFullscreen)!=null?ct:!0,pe=(Pe=(Re=r.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Pe:640,Z=H.innerWidth<=pe,xe=Cn(r)&&de&&Z,Ne=D()&&((vt=(Xe=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Xe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return O||de&&Z&&k||xe||Ne})();if(M&&y){if(!tn){let O=n.getRootNode(),H=O instanceof ShadowRoot?O.host:n.closest(".persona-host");H&&(tn=al(H,(U=(B=r.launcher)==null?void 0:B.zIndex)!=null?U:En))}un||(un=il(n.ownerDocument))}else M||(tn==null||tn(),tn=null,un==null||un(),un=null);M&&(_s(),rt()==="follow"?Hr(!0):Bs());let S={open:M,source:p,timestamp:Date.now()};M&&!h?s.emit("widget:opened",S):!M&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:M,launcherEnabled:k,voiceActive:yt.active,streaming:_.isStreaming()})},J=l=>{Ln(l?"stop":"send"),V&&(V.disabled=l),Mo.buttons.forEach(p=>{p.disabled=l}),_e.dataset.personaComposerStreaming=l?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},le=()=>{yt.active||Ie&&Ie.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>le(),200)});let X=()=>{var h,y,S,B,U,O,H,de,pe,Z,xe;Cr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",q.textContent=(B=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",Ie.placeholder=(O=(U=r.copy)==null?void 0:U.inputPlaceholder)!=null?O:"How can I help...";let l=ke.querySelector("[data-persona-intro-card]");if(l){let Ne=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;l.style.display=Ne?"":"none",Ne?(ke.classList.remove("persona-gap-3"),ke.classList.add("persona-gap-6")):(ke.classList.remove("persona-gap-6"),ke.classList.add("persona-gap-3"))}!((pe=(de=r.sendButton)==null?void 0:de.useIcon)!=null&&pe)&&!(_!=null&&_.isStreaming())&&(Ke.textContent=(xe=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?xe:"Send"),Ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(p=>({...p,sessionId:l}))}});let Me=null,$e=()=>{Me==null&&(Me=setInterval(()=>{let l=Ye.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Me),Me=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Va(p-y))})},100))};_=new ri(r,{onMessagesChanged(l){var y;io(Ye,l,Le),$e(),Go(l),Hr(!Lr),Pa(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&Lo(),!Xo||ko?(Xo=!0,Jo=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==Jo&&(Jo=p.id,La(p.id));let h=yt.lastUserMessageId;p&&p.id!==h&&(yt.lastUserMessageId=p.id,s.emit("user:message",p)),yt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),es(l),Ue()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};lt(pn,(S=>{var B,U,O,H;return S==="idle"?(B=p.idleText)!=null?B:Mn.idle:S==="connecting"?(U=p.connectingText)!=null?U:Mn.connecting:S==="connected"?(O=p.connectedText)!=null?O:Mn.connected:S==="error"?(H=p.errorText)!=null?H:Mn.error:Mn[S]})(l),p,l)},onStreamingChanged(l){Lr=l,J(l),_&&io(Ye,_.getMessages(),Le),l||Hr(!0),Ue()},onVoiceStatusChanged(l){var p,h;if(s.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Vr(),os();break;case"processing":Vr(),pg();break;case"speaking":Vr(),ug();break;default:l==="idle"&&_.isBargeInActive()?(Vr(),os(),V==null||V.setAttribute("aria-label","End voice session")):(yt.active=!1,Vr(),ar("system"),$n());break}},onArtifactsState(l){Vn=l,Qn(),es()}}),Mt.current=_;let at=null;if(_.onReadAloudChange((l,p)=>{var S;Zr=l,eo=p,to();let h=l!=null?l:at;l&&(at=l);let y=h&&(S=_.getMessages().find(B=>B.id===h))!=null?S:null;s.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(at=null)}),Xo=!0,((Fc=(Nc=r.voiceRecognition)==null?void 0:Nc.provider)==null?void 0:Fc.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(fe||r.onSSEEvent)&&_.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),ue==null||ue.processEvent(l,p),fe==null||fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),c&&c.then(l=>{var p,h,y;if(l){if(l.metadata&&(d=Ml(l.metadata),E.syncFromMetadata()),(p=l.messages)!=null&&p.length){ko=!0;try{_.hydrateMessages(l.messages)}finally{ko=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(y=l.selectedArtifactId)!=null?y:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let tt=()=>{var p,h,y;!D()||M||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||T(!0,"auto")},Bt=l=>{var S;if(l.preventDefault(),_.isStreaming()){_.cancel(),ue==null||ue.reset(),K==null||K.update();return}let p=Ie.value.trim(),h=(S=xt==null?void 0:xt.hasAttachments())!=null?S:!1;if(!p&&!h)return;tt();let y;h&&(y=[],y.push(...xt.getContentParts()),p&&y.push(Ji(p))),Ie.value="",Ie.style.height="auto",Et(),_.sendMessage(p,{contentParts:y}),h&&xt.clearAttachments()},zt=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},ln={...ii},At=!1,Et=()=>{ln={...ii}},yn=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Rn=l=>{if(!Ie)return;At=!0,Ie.value=l,Ie.dispatchEvent(new Event("input",{bubbles:!0})),At=!1;let p=Ie.value.length;Ie.setSelectionRange(p,p)},wn=()=>{At||Et()},Zt=l=>{if(Ie){if(zt()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Ie.selectionStart===0&&Ie.selectionEnd===0,h=Zu({direction:l.key==="ArrowUp"?"up":"down",history:yn(),currentValue:Ie.value,atStart:p,state:ln});if(ln=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Rn(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Et(),l.preventDefault(),Ke.click()}}},ir=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(me)&&(_.cancel(),ue==null||ue.reset(),K==null||K.update(),Et(),l.preventDefault(),l.stopImmediatePropagation())},Rl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!xt)return;let p=py(l.clipboardData);p.length!==0&&(l.preventDefault(),await xt.handleFiles(p))},lr=null,Br=!1,rs=null,gt=null,Hl=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ha=(l="user")=>{var B,U,O,H,de,pe,Z;if(Br||_.isStreaming())return;let p=Hl();if(!p)return;lr=new p;let y=(U=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?U:2e3;lr.continuous=!0,lr.interimResults=!0,lr.lang="en-US";let S=Ie.value;lr.onresult=xe=>{let Ne="",Ae="";for(let ze=0;ze<xe.results.length;ze++){let ft=xe.results[ze],ct=ft[0].transcript;ft.isFinal?Ne+=ct+" ":Ae=ct}let ot=S+Ne+Ae;Ie.value=ot,rs&&clearTimeout(rs),(Ne||Ae)&&(rs=window.setTimeout(()=>{let ze=Ie.value.trim();ze&&lr&&Br&&(uo(),Ie.value="",Ie.style.height="auto",_.sendMessage(ze,{viaVoice:!0}))},y))},lr.onerror=xe=>{xe.error!=="no-speech"&&uo()},lr.onend=()=>{if(Br){let xe=Ie.value.trim();xe&&xe!==S.trim()&&(Ie.value="",Ie.style.height="auto",_.sendMessage(xe,{viaVoice:!0})),uo()}};try{if(lr.start(),Br=!0,yt.active=!0,l!=="system"&&(yt.manuallyDeactivated=!1),ar(l),$n(),V){let xe=(O=r.voiceRecognition)!=null?O:{};gt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(H=xe.iconName)!=null?H:"mic",iconSize:parseFloat((Z=(pe=xe.iconSize)!=null?pe:(de=r.sendButton)==null?void 0:de.size)!=null?Z:"40")||24};let Ne=xe.recordingBackgroundColor,Ae=xe.recordingIconColor,ot=xe.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let ze=V.querySelector("svg");ze&&ze.setAttribute("stroke",Ae)}ot&&(V.style.borderColor=ot),V.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Br){if(Br=!1,rs&&(clearTimeout(rs),rs=null),lr){try{lr.stop()}catch{}lr=null}if(yt.active=!1,ar(l),$n(),V){if(V.classList.remove("persona-voice-recording"),gt){V.style.backgroundColor=gt.backgroundColor,V.style.color=gt.color,V.style.borderColor=gt.borderColor;let p=V.querySelector("svg");p&&p.setAttribute("stroke",gt.color||"currentColor"),gt=null}V.setAttribute("aria-label","Start voice recognition")}}},dg=(l,p)=>{var ct,Re,Pe,je,Xe,vt,P,De,He;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((ct=l==null?void 0:l.provider)==null?void 0:ct.type)==="runtype",S=((Re=l==null?void 0:l.provider)==null?void 0:Re.type)==="custom";if(!(h||y||S))return null;let U=b("div","persona-send-button-wrapper"),O=b("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=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",de=(je=p==null?void 0:p.size)!=null?je:"40px",pe=(Xe=l==null?void 0:l.iconSize)!=null?Xe:de,Z=parseFloat(pe)||24,xe=(vt=l==null?void 0:l.backgroundColor)!=null?vt:p==null?void 0:p.backgroundColor,Ne=(P=l==null?void 0:l.iconColor)!=null?P:p==null?void 0:p.textColor;O.style.width=pe,O.style.height=pe,O.style.minWidth=pe,O.style.minHeight=pe,O.style.fontSize="18px",O.style.lineHeight="1",Ne?O.style.color=Ne:O.style.color="var(--persona-text, #111827)";let ot=Se(H,Z,Ne||"currentColor",1.5);ot?O.appendChild(ot):O.textContent="\u{1F3A4}",xe?O.style.backgroundColor=xe: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),U.appendChild(O);let ze=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((He=l==null?void 0:l.showTooltip)!=null?He:!1)&&ze){let ge=b("div","persona-send-button-tooltip");ge.textContent=ze,U.appendChild(ge)}return{micButton:O,micButtonWrapper:U}},Ii=()=>{var p,h,y,S,B;if(!V||gt)return;let l=(p=r.voiceRecognition)!=null?p:{};gt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((B=(S=l.iconSize)!=null?S:(y=r.sendButton)==null?void 0:y.size)!=null?B:"40")||24}},Wi=(l,p)=>{var B,U,O,H,de;if(!V)return;let h=V.querySelector("svg");h&&h.remove();let y=(de=gt==null?void 0:gt.iconSize)!=null?de:parseFloat((H=(O=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?O:(U=r.sendButton)==null?void 0:U.size)!=null?H:"40")||24,S=Se(l,y,p,1.5);S&&V.appendChild(S)},Ba=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},os=()=>{var S;if(!V)return;Ii();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(Ba(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let B=V.querySelector("svg");B&&B.setAttribute("stroke",h)}y&&(V.style.borderColor=y),V.setAttribute("aria-label","Stop voice recognition")},pg=()=>{var O,H,de,pe,Z,xe,Ne,Ae;if(!V)return;Ii();let l=(O=r.voiceRecognition)!=null?O:{},p=_.getVoiceInterruptionMode(),h=(H=l.processingIconName)!=null?H:"loader",y=(pe=(de=l.processingIconColor)!=null?de:gt==null?void 0:gt.color)!=null?pe:"",S=(xe=(Z=l.processingBackgroundColor)!=null?Z:gt==null?void 0:gt.backgroundColor)!=null?xe:"",B=(Ae=(Ne=l.processingBorderColor)!=null?Ne:gt==null?void 0:gt.borderColor)!=null?Ae:"";Ba(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=S,V.style.borderColor=B;let U=y||"currentColor";V.style.color=U,Wi(h,U),V.setAttribute("aria-label","Processing voice input"),p==="none"&&(V.style.cursor="default")},ug=()=>{var de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct,Re,Pe;if(!V)return;Ii();let l=(de=r.voiceRecognition)!=null?de:{},p=_.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(pe=l.speakingIconName)!=null?pe:h,S=(Ae=l.speakingIconColor)!=null?Ae:p==="barge-in"?(xe=(Z=l.recordingIconColor)!=null?Z:gt==null?void 0:gt.color)!=null?xe:"":(Ne=gt==null?void 0:gt.color)!=null?Ne:"",B=(ft=l.speakingBackgroundColor)!=null?ft:p==="barge-in"?(ot=l.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(ze=gt==null?void 0:gt.backgroundColor)!=null?ze:"",U=(Pe=l.speakingBorderColor)!=null?Pe:p==="barge-in"?(ct=l.recordingBorderColor)!=null?ct:"":(Re=gt==null?void 0:gt.borderColor)!=null?Re:"";Ba(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=B,V.style.borderColor=U;let O=S||"currentColor";V.style.color=O,Wi(y,O);let H=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",H),p==="none"&&(V.style.cursor="default"),p==="barge-in"&&V.classList.add("persona-voice-recording")},Vr=()=>{var l,p,h;V&&(Ba(),gt&&(V.style.backgroundColor=(l=gt.backgroundColor)!=null?l:"",V.style.color=(p=gt.color)!=null?p:"",V.style.borderColor=(h=gt.borderColor)!=null?h:"",Wi(gt.iconName,gt.color||"currentColor"),gt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},Da=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=_.getVoiceStatus(),y=_.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),ar("user"),Vr()});return}_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),yt.manuallyDeactivated=!_.isVoiceActive(),$n(),ar("user"),_.isVoiceActive()?os():Vr()});return}if(Br){let h=Ie.value.trim();yt.manuallyDeactivated=!0,$n(),uo("user"),h&&(Ie.value="",Ie.style.height="auto",_.sendMessage(h))}else yt.manuallyDeactivated=!1,$n(),Ha("user")};zn=Da,V&&(V.addEventListener("click",Da),ut.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Vr()):uo("system"),V&&V.removeEventListener("click",Da)}));let mg=s.on("assistant:complete",()=>{ks&&(yt.active||yt.manuallyDeactivated||ks==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!yt.active&&!yt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("auto"),_.isVoiceActive()&&os()}):Ha("auto"))},600))});ut.push(mg);let gg=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ut.push(gg);let Bl=()=>{T(!M,"user")},nn=null,mn=null;if(k&&!D()){let{instance:l,element:p}=dl({config:r,plugins:o,onToggle:Bl});nn=l,l||(mn=p)}nn?n.appendChild(nn.element):mn&&n.appendChild(mn),$(),Go(),X(),J(_.isStreaming()),rt()==="follow"?Hr(!0):Bs(),Sa(),F&&(!k||D()?setTimeout(()=>le(),0):M&&setTimeout(()=>le(),200));let _s=()=>{var H,de,pe,Z,xe,Ne,Ae,ot,ze,ft,ct,Re,Pe,je,Xe,vt,P,De,He,ge,$t,Ot;if(D()){On(),$();return}let l=Cn(r),p=(de=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?de:!1,h=l||p||((Z=(pe=r.launcher)==null?void 0:pe.fullHeight)!=null?Z:!1),y=(xe=n.ownerDocument.defaultView)!=null?xe:window,S=(Ae=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ae:!0,B=(ze=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?ze:640,U=y.innerWidth<=B,O=S&&U&&k;try{if(O){be(),xs(n,r);return}if(W&&(W=!1,be(),xs(n,r)),!k&&!l){he.style.height="",he.style.width="";return}if(!p&&!l){let Gt=(ct=(ft=r==null?void 0:r.launcher)==null?void 0:ft.width)!=null?ct:r==null?void 0:r.launcherWidth,wt=Gt!=null?Gt:Xr;he.style.width=wt,he.style.maxWidth=wt}if(Mr(),!h){let Gt=y.innerHeight,wt=64,jt=(Pe=(Re=r.launcher)==null?void 0:Re.heightOffset)!=null?Pe:0,Yn=Math.max(200,Gt-wt),rn=Math.min(640,Yn),Ze=Math.max(200,rn-jt);he.style.height=`${Ze}px`}}finally{if(On(),$(),M&&k){let wt=((je=n.ownerDocument.defaultView)!=null?je:window).innerWidth<=((vt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?vt:640),jt=(De=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?De:!1,Yn=(ge=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?ge:!0,rn=Cn(r)&&Yn&&wt,Ze=jt||Yn&&wt&&k||rn;if(Ze&&!un){let It=n.getRootNode(),dn=It instanceof ShadowRoot?It.host:n.closest(".persona-host");dn&&!tn&&(tn=al(dn,(Ot=($t=r.launcher)==null?void 0:$t.zIndex)!=null?Ot:En)),un=il(n.ownerDocument)}else Ze||(tn==null||tn(),tn=null,un==null||un(),un=null)}}};_s();let Dl=(Oc=n.ownerDocument.defaultView)!=null?Oc:window;if(Dl.addEventListener("resize",_s),ut.push(()=>Dl.removeEventListener("resize",_s)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{On()});l.observe(_e),ut.push(()=>l.disconnect())}Jn=ke.scrollTop;let Nl=Jr(ke),fg=()=>{let l=ke.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:ke.ownerDocument.getSelection()},Ri=()=>sm(fg(),ke),Fl=()=>{let l=ke.scrollTop,p=Jr(ke),h=p<Nl;if(Nl=p,rt()!=="follow"){Jn=l,qn();return}let{action:y,nextLastScrollTop:S}=ci({following:Xn.isFollowing(),currentScrollTop:l,lastScrollTop:Jn,nearBottom:Uo(ke,Yo),userScrollThreshold:Ca,isAutoScrolling:hr||Eo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Jn=S,y==="resume"){Ri()||Rr();return}y==="pause"&&ts()};if(ke.addEventListener("scroll",Fl,{passive:!0}),ut.push(()=>ke.removeEventListener("scroll",Fl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{ka()});l.observe(Ye),l.observe(ke),ut.push(()=>l.disconnect())}let Ol=()=>{rt()==="follow"&&Xn.isFollowing()&&Ri()&&ts()},_l=ke.ownerDocument;_l.addEventListener("selectionchange",Ol),ut.push(()=>{_l.removeEventListener("selectionchange",Ol)});let $l=l=>{if(rt()!=="follow")return;let p=di({following:Xn.isFollowing(),deltaY:l.deltaY,nearBottom:Uo(ke,Yo),resumeWhenNearBottom:!0});p==="pause"?ts():p==="resume"&&!Ri()&&Rr()};ke.addEventListener("wheel",$l,{passive:!0}),ut.push(()=>ke.removeEventListener("wheel",$l)),pt.addEventListener("click",()=>{Lo(),ke.scrollTop=ke.scrollHeight,Jn=ke.scrollTop,Rr(),Hr(!0),qn()}),ut.push(()=>pt.remove()),ut.push(()=>{Ps(),Lo()});let ql=()=>{G&&(kr&&(G.removeEventListener("click",kr),kr=null),N()?(G.style.display="",kr=()=>{T(!1,"user")},G.addEventListener("click",kr)):G.style.display="none")};ql(),(()=>{let{clearChatButton:l}=Y;l&&l.addEventListener("click",()=>{_.clearMessages(),Pr.clear(),Rr(),ms(Y.composerOverlay);try{localStorage.removeItem(Ts),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),fe==null||fe.clear(),ue==null||ue.reset(),K==null||K.update()})})(),Rt&&Rt.addEventListener("submit",Bt),Ie==null||Ie.addEventListener("keydown",Zt),Ie==null||Ie.addEventListener("input",wn),Ie==null||Ie.addEventListener("paste",Rl);let Ul=(_c=n.ownerDocument)!=null?_c:document;Ul.addEventListener("keydown",ir,!0);let zl="persona-attachment-drop-active",$s=0,Hi=()=>{$s=0,me.classList.remove(zl)},ss=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&xt!==null},jl=l=>{!Li(l.dataTransfer)||!ss()||($s++,$s===1&&me.classList.add(zl))},Vl=l=>{!Li(l.dataTransfer)||!ss()||($s--,$s<=0&&Hi())},Kl=l=>{!Li(l.dataTransfer)||!ss()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Gl=l=>{var h;if(!Li(l.dataTransfer)||!ss())return;l.preventDefault(),l.stopPropagation(),Hi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&xt.handleFiles(p)},mo=!0;me.addEventListener("dragenter",jl,mo),me.addEventListener("dragleave",Vl,mo),n.addEventListener("dragover",Kl,mo),n.addEventListener("drop",Gl,mo);let Na=n.ownerDocument,Ql=l=>{ss()&&l.preventDefault()},Xl=l=>{ss()&&l.preventDefault()};Na.addEventListener("dragover",Ql),Na.addEventListener("drop",Xl),ut.push(()=>{Rt&&Rt.removeEventListener("submit",Bt),Ie==null||Ie.removeEventListener("keydown",Zt),Ie==null||Ie.removeEventListener("input",wn),Ie==null||Ie.removeEventListener("paste",Rl),Ul.removeEventListener("keydown",ir,!0)}),ut.push(()=>{me.removeEventListener("dragenter",jl,mo),me.removeEventListener("dragleave",Vl,mo),n.removeEventListener("dragover",Kl,mo),n.removeEventListener("drop",Gl,mo),Na.removeEventListener("dragover",Ql),Na.removeEventListener("drop",Xl),Hi()}),ut.push(()=>{_.cancel()}),nn?ut.push(()=>{nn==null||nn.destroy()}):mn&&ut.push(()=>{mn==null||mn.remove()});let cn={update(l){var Sn,Hn,Dr,bn,Bn,Dn,Ho,qs,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,qd,Ud,zd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Mp,Ep,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp,Op,_p,$p,qp,Up,zp,jp;let p=r.toolCall,h=r.messageActions,y=(Sn=r.layout)==null?void 0:Sn.messages,S=r.colorScheme,B=r.loadingIndicator,U=r.iterationDisplay,O=(Hn=r.features)==null?void 0:Hn.showReasoning,H=(Dr=r.features)==null?void 0:Dr.showToolCalls,de=(bn=r.features)==null?void 0:bn.toolCallDisplay,pe=(Bn=r.features)==null?void 0:Bn.reasoningDisplay;r={...r,...l},be(),xs(n,r),Ei(n,r),ki(n,r),Qn(),r.colorScheme!==S&&Es();let Z=wl.getForInstance(r.plugins);o.length=0,o.push(...Z),k=(Ho=(Dn=r.launcher)==null?void 0:Dn.enabled)!=null?Ho:!0,L=(Kc=(qs=r.launcher)==null?void 0:qs.autoExpand)!=null?Kc:!1,Ve=(Qc=(Gc=r.features)==null?void 0:Gc.showReasoning)!=null?Qc:!0,ve=(Jc=(Xc=r.features)==null?void 0:Xc.showToolCalls)!=null?Jc:!0,Oe=(Zc=(Yc=r.features)==null?void 0:Yc.scrollToBottom)!=null?Zc:{};let xe=rt();Te=(td=(ed=r.features)==null?void 0:ed.scrollBehavior)!=null?td:{},xe!==rt()&&(Lo(),Rr()),Ar(),qn();let Ne=Be;if(Be=(rd=(nd=r.features)==null?void 0:nd.showEventStreamToggle)!=null?rd:!1,Be&&!Ne){if(fe||(Q=new ya(se),fe=new ha(ae,Q),ue=ue!=null?ue:new ba,Q.open().then(()=>fe==null?void 0:fe.restore()).catch(()=>{}),_.setSSEEventCallback((ne,kt)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,ne,kt),ue==null||ue.processEvent(ne,kt),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(kt)})})),!bt&&qe){let ne=(sd=(od=r.features)==null?void 0:od.eventStream)==null?void 0:sd.classNames,kt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");bt=b("button",kt),bt.style.width="28px",bt.style.height="28px",bt.style.color=Fn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let Vt=Se("activity","18px","currentColor",1.5);Vt&&bt.appendChild(Vt);let dt=Y.clearChatButtonWrapper,Wt=Y.closeButtonWrapper,fn=dt||Wt;fn&&fn.parentNode===qe?qe.insertBefore(bt,fn):qe.appendChild(bt),bt.addEventListener("click",()=>{ie?mr():Fr()})}}else!Be&&Ne&&(mr(),bt&&(bt.remove(),bt=null),fe==null||fe.clear(),Q==null||Q.destroy(),fe=null,Q=null,ue==null||ue.reset(),ue=null);if(((ad=r.launcher)==null?void 0:ad.enabled)===!1&&nn&&(nn.destroy(),nn=null),((id=r.launcher)==null?void 0:id.enabled)===!1&&mn&&(mn.remove(),mn=null),((ld=r.launcher)==null?void 0:ld.enabled)!==!1&&!nn&&!mn){let{instance:ne,element:kt}=dl({config:r,plugins:o,onToggle:Bl});nn=ne,ne||(mn=kt),n.appendChild(kt)}nn&&nn.update(r),Qe&&((cd=r.launcher)==null?void 0:cd.title)!==void 0&&(Qe.textContent=r.launcher.title),et&&((dd=r.launcher)==null?void 0:dd.subtitle)!==void 0&&(et.textContent=r.launcher.subtitle);let Ae=(pd=r.layout)==null?void 0:pd.header;if((Ae==null?void 0:Ae.layout)!==A&&qe){let ne=Ae?hi(r,Ae,{showClose:N(),onClose:()=>T(!1,"user")}):zo({config:r,showClose:N(),onClose:()=>T(!1,"user")});st.replaceHeader(ne),qe=st.header.element,ye=st.header.iconHolder,Qe=st.header.headerTitle,et=st.header.headerSubtitle,G=st.header.closeButton,A=Ae==null?void 0:Ae.layout}else if(Ae&&(ye&&(ye.style.display=Ae.showIcon===!1?"none":""),Qe&&(Qe.style.display=Ae.showTitle===!1?"none":""),et&&(et.style.display=Ae.showSubtitle===!1?"none":""),G&&(G.style.display=Ae.showCloseButton===!1?"none":""),Y.clearChatButtonWrapper)){let ne=Ae.showClearChat;if(ne!==void 0){Y.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:kt}=Y;kt&&!kt.classList.contains("persona-absolute")&&(ne?kt.classList.remove("persona-ml-auto"):kt.classList.add("persona-ml-auto"))}}let ze=((ud=r.layout)==null?void 0:ud.showHeader)!==!1;qe&&(qe.style.display=ze?"":"none");let ft=((md=r.layout)==null?void 0:md.showFooter)!==!1;_e&&(_e.style.display=ft?"":"none"),On(),qn(),k!==R?k?T(L,"auto"):(M=!0,$()):L!==I&&T(L,"auto"),I=L,R=k,_s(),ql();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(p),je=JSON.stringify(r.messageActions)!==JSON.stringify(h),Xe=JSON.stringify((gd=r.layout)==null?void 0:gd.messages)!==JSON.stringify(y),vt=((fd=r.loadingIndicator)==null?void 0:fd.render)!==(B==null?void 0:B.render)||((hd=r.loadingIndicator)==null?void 0:hd.renderIdle)!==(B==null?void 0:B.renderIdle)||((yd=r.loadingIndicator)==null?void 0:yd.showBubble)!==(B==null?void 0:B.showBubble),P=r.iterationDisplay!==U,De=((vd=(bd=r.features)==null?void 0:bd.showReasoning)!=null?vd:!0)!==(O!=null?O:!0)||((wd=(xd=r.features)==null?void 0:xd.showToolCalls)!=null?wd:!0)!==(H!=null?H:!0)||JSON.stringify((Cd=r.features)==null?void 0:Cd.toolCallDisplay)!==JSON.stringify(de)||JSON.stringify((Ad=r.features)==null?void 0:Ad.reasoningDisplay)!==JSON.stringify(pe);(Pe||je||Xe||vt||P||De)&&_&&(Qo++,io(Ye,_.getMessages(),Le));let ge=(Sd=r.launcher)!=null?Sd:{},$t=(Td=ge.headerIconHidden)!=null?Td:!1,Ot=(Ed=(Md=r.layout)==null?void 0:Md.header)==null?void 0:Ed.showIcon,Gt=$t||Ot===!1,wt=ge.headerIconName,jt=(kd=ge.headerIconSize)!=null?kd:"48px";if(ye){let ne=me.querySelector(".persona-border-b-persona-divider"),kt=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Gt)ye.style.display="none",ne&&kt&&!ne.contains(kt)&&ne.insertBefore(kt,ne.firstChild);else{if(ye.style.display="",ye.style.height=jt,ye.style.width=jt,ne&&kt&&(ne.contains(ye)?ye.nextSibling!==kt&&(ye.remove(),ne.insertBefore(ye,kt)):ne.insertBefore(ye,kt)),wt){let dt=parseFloat(jt)||24,Wt=Se(wt,dt*.6,"currentColor",1);Wt?ye.replaceChildren(Wt):ye.textContent=(Ld=ge.agentIconText)!=null?Ld:"\u{1F4AC}"}else if(ge.iconUrl){let dt=ye.querySelector("img");if(dt)dt.src=ge.iconUrl,dt.style.height=jt,dt.style.width=jt;else{let Wt=document.createElement("img");Wt.src=ge.iconUrl,Wt.alt="",Wt.className="persona-rounded-xl persona-object-cover",Wt.style.height=jt,Wt.style.width=jt,ye.replaceChildren(Wt)}}else{let dt=ye.querySelector("svg"),Wt=ye.querySelector("img");(dt||Wt)&&ye.replaceChildren(),ye.textContent=(Pd=ge.agentIconText)!=null?Pd:"\u{1F4AC}"}let Vt=ye.querySelector("img");Vt&&(Vt.style.height=jt,Vt.style.width=jt)}}let Yn=(Wd=(Id=r.layout)==null?void 0:Id.header)==null?void 0:Wd.showTitle,rn=(Hd=(Rd=r.layout)==null?void 0:Rd.header)==null?void 0:Hd.showSubtitle;if(Qe&&(Qe.style.display=Yn===!1?"none":""),et&&(et.style.display=rn===!1?"none":""),G){((Dd=(Bd=r.layout)==null?void 0:Bd.header)==null?void 0:Dd.showCloseButton)===!1?G.style.display="none":G.style.display="";let kt=(Nd=ge.closeButtonSize)!=null?Nd:"32px",Vt=(Fd=ge.closeButtonPlacement)!=null?Fd:"inline";G.style.height=kt,G.style.width=kt;let{closeButtonWrapper:dt}=Y,Wt=Vt==="top-right",fn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Wt!==fn)if(dt.remove(),Wt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(dt);else{let mt=(_d=(Od=ge.clearChat)==null?void 0:Od.placement)!=null?_d:"inline",hn=(qd=($d=ge.clearChat)==null?void 0:$d.enabled)!=null?qd:!0;dt.className=hn&&mt==="inline"?"":"persona-ml-auto";let Un=me.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(dt)}if(G.style.color=ge.closeButtonColor||Fn.actionIconColor,ge.closeButtonBackgroundColor?(G.style.backgroundColor=ge.closeButtonBackgroundColor,G.classList.remove("hover:persona-bg-gray-100")):(G.style.backgroundColor="",G.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let mt=ge.closeButtonBorderWidth||"0px",hn=ge.closeButtonBorderColor||"transparent";G.style.border=`${mt} solid ${hn}`,G.classList.remove("persona-border-none")}else G.style.border="",G.classList.add("persona-border-none");ge.closeButtonBorderRadius?(G.style.borderRadius=ge.closeButtonBorderRadius,G.classList.remove("persona-rounded-full")):(G.style.borderRadius="",G.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(G.style.paddingLeft=ge.closeButtonPaddingX,G.style.paddingRight=ge.closeButtonPaddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ge.closeButtonPaddingY?(G.style.paddingTop=ge.closeButtonPaddingY,G.style.paddingBottom=ge.closeButtonPaddingY):(G.style.paddingTop="",G.style.paddingBottom="");let Tn=(Ud=ge.closeButtonIconName)!=null?Ud:"x",br=(zd=ge.closeButtonIconText)!=null?zd:"\xD7";G.innerHTML="";let Nn=Se(Tn,"28px","currentColor",1);Nn?G.appendChild(Nn):G.textContent=br;let en=(jd=ge.closeButtonTooltipText)!=null?jd:"Close chat",er=(Vd=ge.closeButtonShowTooltip)!=null?Vd:!0;if(G.setAttribute("aria-label",en),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),er&&en)){let mt=null,hn=()=>{if(mt||!G)return;let Bo=G.ownerDocument,Us=Bo.body;if(!Us)return;mt=Nr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=en;let zs=Nr(Bo,"div");zs.className="persona-clear-chat-tooltip-arrow",mt.appendChild(zs);let Do=G.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(xo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",Us.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};dt.addEventListener("mouseenter",hn),dt.addEventListener("mouseleave",Un),G.addEventListener("focus",hn),G.addEventListener("blur",Un),dt._cleanupTooltip=()=>{Un(),dt&&(dt.removeEventListener("mouseenter",hn),dt.removeEventListener("mouseleave",Un)),G&&(G.removeEventListener("focus",hn),G.removeEventListener("blur",Un))}}}let{clearChatButton:Ze,clearChatButtonWrapper:It}=Y;if(Ze){let ne=(Kd=ge.clearChat)!=null?Kd:{},kt=(Gd=ne.enabled)!=null?Gd:!0,Vt=(Xd=(Qd=r.layout)==null?void 0:Qd.header)==null?void 0:Xd.showClearChat,dt=Vt!==void 0?Vt:kt,Wt=(Jd=ne.placement)!=null?Jd:"inline";if(It){It.style.display=dt?"":"none";let{closeButtonWrapper:fn}=Y;!D()&&fn&&!fn.classList.contains("persona-absolute")&&(dt?fn.classList.remove("persona-ml-auto"):fn.classList.add("persona-ml-auto"));let Tn=Wt==="top-right",br=It.classList.contains("persona-absolute");if(!D()&&Tn!==br&&dt){if(It.remove(),Tn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",me.style.position="relative",me.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let en=me.querySelector(".persona-border-b-persona-divider"),er=Y.closeButtonWrapper;en&&er&&er.parentElement===en?en.insertBefore(It,er):en&&en.appendChild(It)}let Nn=Y.closeButtonWrapper;Nn&&!Nn.classList.contains("persona-absolute")&&(Tn?Nn.classList.add("persona-ml-auto"):Nn.classList.remove("persona-ml-auto"))}}if(dt){if(!D()){let mt=(Yd=ne.size)!=null?Yd:"32px";Ze.style.height=mt,Ze.style.width=mt}let fn=(Zd=ne.iconName)!=null?Zd:"refresh-cw",Tn=(ep=ne.iconColor)!=null?ep:"";Ze.style.color=Tn||Fn.actionIconColor,Ze.innerHTML="";let br=D()?"14px":"20px",Nn=Se(fn,br,"currentColor",2);if(Nn&&Ze.appendChild(Nn),ne.backgroundColor?(Ze.style.backgroundColor=ne.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let mt=ne.borderWidth||"0px",hn=ne.borderColor||"transparent";Ze.style.border=`${mt} solid ${hn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");ne.borderRadius?(Ze.style.borderRadius=ne.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),ne.paddingX?(Ze.style.paddingLeft=ne.paddingX,Ze.style.paddingRight=ne.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),ne.paddingY?(Ze.style.paddingTop=ne.paddingY,Ze.style.paddingBottom=ne.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let en=(tp=ne.tooltipText)!=null?tp:"Clear chat",er=(np=ne.showTooltip)!=null?np:!0;if(Ze.setAttribute("aria-label",en),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),er&&en)){let mt=null,hn=()=>{if(mt||!Ze)return;let Bo=Ze.ownerDocument,Us=Bo.body;if(!Us)return;mt=Nr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=en;let zs=Nr(Bo,"div");zs.className="persona-clear-chat-tooltip-arrow",mt.appendChild(zs);let Do=Ze.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(xo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",Us.appendChild(mt)},Un=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};It.addEventListener("mouseenter",hn),It.addEventListener("mouseleave",Un),Ze.addEventListener("focus",hn),Ze.addEventListener("blur",Un),It._cleanupTooltip=()=>{Un(),It&&(It.removeEventListener("mouseenter",hn),It.removeEventListener("mouseleave",Un)),Ze&&(Ze.removeEventListener("focus",hn),Ze.removeEventListener("blur",Un))}}}}let dn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Al],dr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[va.message,va.messageAndClick];E=Sl({parsers:dn,handlers:dr,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Le=Xm(r,E,oe),_.updateConfig(r),io(Ye,_.getMessages(),Le),Go(),X(),J(_.isStreaming());let Zn=((rp=r.voiceRecognition)==null?void 0:rp.enabled)===!0,Po=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Io=((sp=(op=r.voiceRecognition)==null?void 0:op.provider)==null?void 0:sp.type)==="runtype";if(Zn&&(Po||Io))if(!V||!Ht){let ne=dg(r.voiceRecognition,r.sendButton);ne&&(V=ne.micButton,Ht=ne.micButtonWrapper,Jt.insertBefore(Ht,vn),V.addEventListener("click",Da),V.disabled=_.isStreaming())}else{let ne=(ap=r.voiceRecognition)!=null?ap:{},kt=(ip=r.sendButton)!=null?ip:{},Vt=(lp=ne.iconName)!=null?lp:"mic",dt=(cp=kt.size)!=null?cp:"40px",Wt=(dp=ne.iconSize)!=null?dp:dt,fn=parseFloat(Wt)||24;V.style.width=Wt,V.style.height=Wt,V.style.minWidth=Wt,V.style.minHeight=Wt;let Tn=(up=(pp=ne.iconColor)!=null?pp:kt.textColor)!=null?up:"currentColor";V.innerHTML="";let br=Se(Vt,fn,Tn,2);br?V.appendChild(br):V.textContent="\u{1F3A4}";let Nn=(mp=ne.backgroundColor)!=null?mp:kt.backgroundColor;Nn?V.style.backgroundColor=Nn:V.style.backgroundColor="",Tn?V.style.color=Tn:V.style.color="var(--persona-text, #111827)",ne.borderWidth?(V.style.borderWidth=ne.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ne.borderColor?V.style.borderColor=ne.borderColor:V.style.borderColor="",ne.paddingX?(V.style.paddingLeft=ne.paddingX,V.style.paddingRight=ne.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ne.paddingY?(V.style.paddingTop=ne.paddingY,V.style.paddingBottom=ne.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let en=Ht==null?void 0:Ht.querySelector(".persona-send-button-tooltip"),er=(gp=ne.tooltipText)!=null?gp:"Start voice recognition";if(((fp=ne.showTooltip)!=null?fp:!1)&&er)if(en)en.textContent=er,en.style.display="";else{let hn=document.createElement("div");hn.className="persona-send-button-tooltip",hn.textContent=er,Ht==null||Ht.insertBefore(hn,V)}else en&&(en.style.display="none");Ht.style.display="",V.disabled=_.isStreaming()}else V&&Ht&&(Ht.style.display="none",((yp=(hp=r.voiceRecognition)==null?void 0:hp.provider)==null?void 0:yp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Br&&uo());if(((bp=r.attachments)==null?void 0:bp.enabled)===!0)if(!Ce||!ce){let ne=(vp=r.attachments)!=null?vp:{},Vt=(wp=((xp=r.sendButton)!=null?xp:{}).size)!=null?wp:"40px";Tt||(Tt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Tt.style.display="none",Rt.insertBefore(Tt,Ie)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=((Cp=ne.allowedTypes)!=null?Cp:Qr).join(","),Fe.multiple=((Ap=ne.maxFiles)!=null?Ap:4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),Rt.insertBefore(Fe,Ie)),Ce=b("div","persona-send-button-wrapper"),ce=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ce.type="button",ce.setAttribute("aria-label",(Sp=ne.buttonTooltipText)!=null?Sp:"Attach file");let dt=(Tp=ne.buttonIconName)!=null?Tp:"paperclip",Wt=Vt,fn=parseFloat(Wt)||40,Tn=Math.round(fn*.6);ce.style.width=Wt,ce.style.height=Wt,ce.style.minWidth=Wt,ce.style.minHeight=Wt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.style.backgroundColor="transparent",ce.style.color="var(--persona-primary, #111827)",ce.style.border="none",ce.style.borderRadius="6px",ce.style.transition="background-color 0.15s ease",ce.addEventListener("mouseenter",()=>{ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ce.addEventListener("mouseleave",()=>{ce.style.backgroundColor="transparent"});let br=Se(dt,Tn,"currentColor",1.5);br?ce.appendChild(br):ce.textContent="\u{1F4CE}",ce.addEventListener("click",er=>{er.preventDefault(),Fe==null||Fe.click()}),Ce.appendChild(ce);let Nn=(Mp=ne.buttonTooltipText)!=null?Mp:"Attach file",en=b("div","persona-send-button-tooltip");en.textContent=Nn,Ce.appendChild(en),Kt.append(Ce),!xt&&Fe&&Tt&&(xt=sa.fromConfig(ne),xt.setPreviewsContainer(Tt),Fe.addEventListener("change",async()=>{xt&&(Fe!=null&&Fe.files)&&(await xt.handleFileSelect(Fe.files),Fe.value="")})),me.querySelector(".persona-attachment-drop-overlay")||me.appendChild(Jm(ne.dropOverlay))}else{Ce.style.display="";let ne=(Ep=r.attachments)!=null?Ep:{};Fe&&(Fe.accept=((kp=ne.allowedTypes)!=null?kp:Qr).join(","),Fe.multiple=((Lp=ne.maxFiles)!=null?Lp:4)>1),xt&&xt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else Ce&&(Ce.style.display="none"),xt&&xt.clearAttachments(),(Pp=me.querySelector(".persona-attachment-drop-overlay"))==null||Pp.remove();let Qt=(Ip=r.sendButton)!=null?Ip:{},Wo=(Wp=Qt.useIcon)!=null?Wp:!1,go=(Rp=Qt.iconText)!=null?Rp:"\u2191",fo=Qt.iconName,Kr=(Hp=Qt.tooltipText)!=null?Hp:"Send message",Ro=(Bp=Qt.showTooltip)!=null?Bp:!1,yr=(Dp=Qt.size)!=null?Dp:"40px",nt=Qt.backgroundColor,gn=Qt.textColor;if(Wo){if(Ke.style.width=yr,Ke.style.height=yr,Ke.style.minWidth=yr,Ke.style.minHeight=yr,Ke.style.fontSize="18px",Ke.style.lineHeight="1",Ke.innerHTML="",gn?Ke.style.color=gn:Ke.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let ne=parseFloat(yr)||24,kt=(gn==null?void 0:gn.trim())||"currentColor",Vt=Se(fo,ne,kt,2);Vt?Ke.appendChild(Vt):Ke.textContent=go}else Ke.textContent=go;Ke.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nt?(Ke.style.backgroundColor=nt,Ke.classList.remove("persona-bg-persona-primary")):(Ke.style.backgroundColor="",Ke.classList.add("persona-bg-persona-primary"))}else Ke.textContent=(Fp=(Np=r.copy)==null?void 0:Np.sendButtonLabel)!=null?Fp:"Send",Ke.style.width="",Ke.style.height="",Ke.style.minWidth="",Ke.style.minHeight="",Ke.style.fontSize="",Ke.style.lineHeight="",Ke.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",nt?(Ke.style.backgroundColor=nt,Ke.classList.remove("persona-bg-persona-accent")):Ke.classList.add("persona-bg-persona-accent"),gn?Ke.style.color=gn:Ke.classList.add("persona-text-white");Qt.borderWidth?(Ke.style.borderWidth=Qt.borderWidth,Ke.style.borderStyle="solid"):(Ke.style.borderWidth="",Ke.style.borderStyle=""),Qt.borderColor?Ke.style.borderColor=Qt.borderColor:Ke.style.borderColor="",Qt.paddingX?(Ke.style.paddingLeft=Qt.paddingX,Ke.style.paddingRight=Qt.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),Qt.paddingY?(Ke.style.paddingTop=Qt.paddingY,Ke.style.paddingBottom=Qt.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Ut=vn==null?void 0:vn.querySelector(".persona-send-button-tooltip");if(Ro&&Kr)if(Ut)Ut.textContent=Kr,Ut.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Kr,vn==null||vn.insertBefore(ne,Ke)}else Ut&&(Ut.style.display="none");let qt=(Up=(Op=r.layout)==null?void 0:Op.contentMaxWidth)!=null?Up:D()?(qp=($p=(_p=r.launcher)==null?void 0:_p.composerBar)==null?void 0:$p.contentMaxWidth)!=null?qp:"720px":void 0;qt?(Ye.style.maxWidth=qt,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%",Rt&&(Rt.style.maxWidth=qt,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),Ge&&(Ge.style.maxWidth=qt,Ge.style.marginLeft="auto",Ge.style.marginRight="auto")):(Ye.style.maxWidth="",Ye.style.marginLeft="",Ye.style.marginRight="",Ye.style.width="",Rt&&(Rt.style.maxWidth="",Rt.style.marginLeft="",Rt.style.marginRight=""),Ge&&(Ge.style.maxWidth="",Ge.style.marginLeft="",Ge.style.marginRight=""));let ht=(zp=r.statusIndicator)!=null?zp:{},Xt=(jp=ht.visible)!=null?jp:!0;if(pn.style.display=Xt?"":"none",_){let ne=_.getStatus();lt(pn,(Vt=>{var dt,Wt,fn,Tn;return Vt==="idle"?(dt=ht.idleText)!=null?dt:Mn.idle:Vt==="connecting"?(Wt=ht.connectingText)!=null?Wt:Mn.connecting:Vt==="connected"?(fn=ht.connectedText)!=null?fn:Mn.connected:Vt==="error"?(Tn=ht.errorText)!=null?Tn:Mn.error:Mn[Vt]})(ne),ht,ne)}pn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let St=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";pn.classList.add(St)},open(){N()&&T(!0,"api")},close(){N()&&T(!1,"api")},toggle(){N()&&T(!M,"api")},clearChat(){In=!1,_.clearMessages(),Pr.clear(),Rr();try{localStorage.removeItem(Ts),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},E.syncFromMetadata(),fe==null||fe.clear(),ue==null||ue.reset(),K==null||K.update()},setMessage(l){return!Ie||_.isStreaming()?!1:(!M&&N()&&T(!0,"system"),Ie.value=l,Ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Ie.value.trim();return p?(!M&&N()&&T(!0,"system"),Ie.value="",Ie.style.height="auto",_.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return _.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!M&&N()&&T(!0,"system"),yt.manuallyDeactivated=!1,$n(),_.toggleVoice().then(()=>{yt.active=_.isVoiceActive(),ar("user"),_.isVoiceActive()&&os()})),!0):Br?!0:Hl()?(!M&&N()&&T(!0,"system"),yt.manuallyDeactivated=!1,$n(),Ha("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{yt.active=!1,yt.manuallyDeactivated=!0,$n(),ar("user"),Vr()}),!0):!1:Br?(yt.manuallyDeactivated=!0,$n(),uo("user"),!0):!1},injectMessage(l){return!M&&N()&&T(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!M&&N()&&T(!0,"system");let p=_.injectAssistantMessage(l);return z&&(z=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(l){return!M&&N()&&T(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!M&&N()&&T(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!M&&N()&&T(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!M&&N()&&T(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!M&&N()&&T(!0,"system"),_.injectTestEvent(l)},async connectStream(l,p){return _.connectStream(l,p)},__pushEventStreamEvent(l){fe&&(ue==null||ue.processEvent(l.type,l.payload),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Be||!fe||Fr()},hideEventStream(){ie&&mr()},isEventStreamVisible(){return ie},showArtifacts(){ur(r)&&(In=!1,Qn(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){ur(r)&&(In=!0,Qn())},upsertArtifact(l){return ur(r)?(In=!1,_.upsertArtifact(l)):null},selectArtifact(l){ur(r)&&_.selectArtifact(l)},clearArtifacts(){ur(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return k&&!M&&!D()||!Ie?!1:(Ie.focus(),!0)},async resolveApproval(l,p,h){let S=_.getMessages().find(B=>{var U;return B.variant==="approval"&&((U=B.approval)==null?void 0:U.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){_.resolveWebMcpApproval(S.id,p);return}return _.resolveApproval(S.approval,p,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){m(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return N()&&M},isVoiceActive(){return yt.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:N()&&M,launcherEnabled:k,voiceActive:yt.active,streaming:_.isStreaming()}},showCSATFeedback(l){!M&&N()&&T(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let h=Km({onSubmit:async(y,S)=>{var B;_.isClientTokenMode()&&await _.submitCSATFeedback(y,S),(B=l==null?void 0:l.onSubmit)==null||B.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!M&&N()&&T(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let h=Gm({onSubmit:async(y,S)=>{var B;_.isClientTokenMode()&&await _.submitNPSFeedback(y,S),(B=l==null?void 0:l.onSubmit)==null||B.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return _.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return _.submitNPSFeedback(l,p)},destroy(){Me!=null&&(clearInterval(Me),Me=null),ut.forEach(l=>l()),Ee.remove(),Je==null||Je.remove(),nn==null||nn.destroy(),mn==null||mn.remove(),kr&&G.removeEventListener("click",kr)}};if(((($c=t==null?void 0:t.debugTools)!=null?$c:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:cn,getMessages:cn.getMessages,getStatus:cn.getStatus,getMetadata:cn.getPersistentMetadata,updateMetadata:cn.updatePersistentMetadata,clearHistory:()=>cn.clearChat(),setVoiceActive:h=>h?cn.startVoiceRecognition():cn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ut.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&cn.focusInput()};if(window.addEventListener("persona:focusInput",p),ut.push(()=>{window.removeEventListener("persona:focusInput",p)}),Be){let O=de=>{let pe=de.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===l)&&cn.showEventStream()},H=de=>{let pe=de.detail;(!(pe!=null&&pe.instanceId)||pe.instanceId===l)&&cn.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",H),ut.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)&&cn.showArtifacts()},y=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&cn.hideArtifacts()},S=O=>{let H=O.detail;H!=null&&H.instanceId&&H.instanceId!==l||H!=null&&H.artifact&&cn.upsertArtifact(H.artifact)},B=O=>{let H=O.detail;H!=null&&H.instanceId&&H.instanceId!==l||typeof(H==null?void 0:H.id)=="string"&&cn.selectArtifact(H.id)},U=O=>{let H=O.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&cn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",U),ut.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",U)})}let cr=uy(r.persistState);if(cr&&N()){let l=my(cr.storage),p=`${cr.keyPrefix}widget-open`,h=`${cr.keyPrefix}widget-voice`,y=`${cr.keyPrefix}widget-voice-mode`;if(l){let S=((qc=cr.persist)==null?void 0:qc.openState)&&l.getItem(p)==="true",B=((Uc=cr.persist)==null?void 0:Uc.voiceState)&&l.getItem(h)==="true",U=((zc=cr.persist)==null?void 0:zc.voiceState)&&l.getItem(y)==="true";if(S&&setTimeout(()=>{cn.open(),setTimeout(()=>{var O;if(B||U)cn.startVoiceRecognition();else if((O=cr.persist)!=null&&O.focusInput){let H=n.querySelector("textarea");H&&H.focus()}},100)},0),(jc=cr.persist)!=null&&jc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Vc=cr.persist)!=null&&Vc.voiceState&&(s.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),s.on("user:message",O=>{l.setItem(y,O.viaVoice?"true":"false")})),cr.clearOnChatClear){let O=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},H=()=>O();window.addEventListener("persona:clear-chat",H),ut.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return g&&N()&&setTimeout(()=>{cn.open()},0),Ue(),wa||Zp().then(()=>{_&&(Qo++,Pr.clear(),io(Ye,_.getMessages(),Le))}).catch(()=>{}),cn};var gy=(n,e)=>{let t=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},fy=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},hy=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},yy=(n,e)=>{let t=n.parentElement;if(!t)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Zm=(n,e)=>{var r,o;let t=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=t?"":"100%",n.style.display=t?"":"flex",n.style.flexDirection=t?"":"column",n.style.flex=t?"":"1 1 auto",n.style.minHeight=t?"":"0"},Pl=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},eg=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",Pl(n)},El=n=>{n.style.transition=""},kl=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},Ll=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},Pi=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},by=(n,e,t,r,o)=>{o?t.parentElement!==e&&(n.replaceChildren(),e.replaceChildren(t,r),n.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),n.appendChild(t),n.appendChild(r))},vy=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},tg=(n,e,t,r,o,s,a)=>{var v,x,E,k,L,F;let i=xr(s),d=i.reveal==="push";by(n,e,t,r,d),vy(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,g=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(k=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?k:640,u=c!=null?c.innerWidth<=f:!1;if(g&&u&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),kl(e),El(r),eg(r),Ll(t),Pi(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((F=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?F:En),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),eg(r),fy(r,i.maxHeight),i.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",kl(e),El(r),Ll(t),Pi(o,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":R;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=I,r.style.transform=A,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",El(r),Pl(r),Pi(o,r);let I=gy(i.width,n.clientWidth),R=Math.max(0,n.clientWidth),A=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-I:0:a?0:-I;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${R+I}px`,e.style.transition=A,e.style.marginLeft=`${W}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${R}px`,t.style.maxWidth=`${R}px`,t.style.minWidth=`${R}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",kl(e),Pl(r),Ll(t),Pi(o,r);let I=i.reveal==="emerge";I?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",A=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 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",hy(r,i.maxHeight),r.style.overflow=I||W?"hidden":"visible",r.style.transition=A,I&&(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")}},xy=(n,e)=>{let t=n.ownerDocument.createElement("div");return Zm(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Zm(t,r)},destroy(){t.remove()}}},wy=(n,e)=>{var F,I,R,A;let{ownerDocument:t}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=n.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),g=t.createElement("div"),f=(I=(F=e==null?void 0:e.launcher)==null?void 0:F.enabled)==null||I?(A=(R=e==null?void 0:e.launcher)==null?void 0:R.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",c.appendChild(g),r.insertBefore(a,n),d.appendChild(n);let u=null,m=()=>{u==null||u.disconnect(),u=null},v=()=>{m(),xr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{tg(a,i,d,c,g,e,f)}),u.observe(a))},x=!1,E=()=>{tg(a,i,d,c,g,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,yy(a,xr(e)))},k=a.ownerDocument.defaultView,L=()=>{E()};return k==null||k.addEventListener("resize",L),xr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),E(),{mode:"docked",host:g,shell:a,syncWidgetState(W){let D=W.launcherEnabled?W.open:!0;f!==D&&(f=D,E())},updateConfig(W){var D,N;e=W,((N=(D=e==null?void 0:e.launcher)==null?void 0:D.enabled)!=null?N:!0)===!1&&(f=!0),E()},destroy(){k==null||k.removeEventListener("resize",L),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},ng=(n,e)=>Cn(e)?wy(n,e):xy(n,e);var xa={desktop:{w:1280,h:800},mobile:{w:390,h:844}},rg=.15,og=1.5,Il="persona-preview-shell-theme",Cy={load:()=>null,save:()=>{},clear:()=>{}},Ay=["How do I get started?","Pricing & plans","Talk to support"];function Wl(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Sy(n){return n==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function sg(n){let e=Sy(n);return`* { box-sizing: border-box; }
109
+ `}if(!b&&!l){let Kt="max-height: -moz-available !important; max-height: stretch !important;",Vt=p?"":"padding-top: 1.25em !important;",yt=p?"":`z-index: ${(fn=(Ze=r.launcher)==null?void 0:Ze.zIndex)!=null?fn:In} !important;`;Me.style.cssText+=Kt+Vt+yt}Qe()};ye(),vs(n,r),Li(n,r),Ii(n,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",ro)});let rn=null,un=null;gt.push(()=>{rn==null||rn(),rn=null,un==null||un(),un=null}),Vn&&gt.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),gt.push(()=>{Bn==null||Bn(),Bn=null,Or(),$t&&($t.remove(),$t=null),Tt==null||Tt.element.style.removeProperty("width"),Tt==null||Tt.element.style.removeProperty("maxWidth")}),Ne&&gt.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),K==null||K.destroy(),K=null,fe==null||fe.destroy(),fe=null,X=null});let Er=null,Es=()=>{Er&&(Er(),Er=null),r.colorScheme==="auto"&&(Er=em(()=>{vs(n,r)}))};Es(),gt.push(()=>{Er&&(Er(),Er=null)});let $r=(Hc=r.features)==null?void 0:Hc.streamAnimation;if($r!=null&&$r.type&&$r.type!=="none"){let l=ia($r.type,$r.plugins);l&&(il(l,n),gt.push(()=>mm(n)))}let Eo=Lm(Gt),Mr=null,O,Go=l=>{var b,T;if(!O)return;let p=l!=null?l:O.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?yu(p):null;h?Eo.render(h,O,Pe,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(D=>D.role==="user")?Eo.render([],O,Pe,p):Eo.render(r.suggestionChips,O,Pe,p,r.suggestionChipsConfig)},kr=!1,Lr=om(),qr=new Map,Ir=new Map,mr=new Map,Qo=0,xa=ls()!==null,Jn=di(),Yn=0,gr=null,fr=!1,Mo=!1,Ur=0,Tn=null,Pr=null,Xo=!1,ko=!1,Jo=null,wa=4,Yo=24,Ca=80,Zo=new Map,vt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ms=(Nc=(Dc=r.voiceRecognition)==null?void 0:Dc.autoResume)!=null?Nc:!1,ir=l=>{s.emit("voice:state",{active:vt.active,source:l,timestamp:Date.now()})},qn=()=>{m(l=>({...l,voiceState:{active:vt.active,timestamp:Date.now(),manuallyDeactivated:vt.manuallyDeactivated}}))},Aa=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=kl(d.voiceState),p=!!l.active,h=Number((T=l.timestamp)!=null?T:0);vt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<ub&&setTimeout(()=>{var D,U;vt.active||(vt.manuallyDeactivated=!1,((U=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:U.type)==="runtype"?O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),ir("restore"),O.isVoiceActive()&&rs()}):Ha("restore"))},1e3)},Sa=()=>O?Ym(O.getMessages()).filter(l=>!l.__skipPersist):[];function es(l){if(!(i!=null&&i.save))return;let h={messages:l?Ym(l):O?Sa():[],metadata:d,artifacts:Kn.artifacts,selectedArtifactId:Kn.selectedId};try{let b=i.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let zr=null,ks=()=>Me.querySelector("#persona-scroll-container")||Le,ao=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),fr=!1},Ls=()=>{gr!==null&&(cancelAnimationFrame(gr),gr=null),Mo=!1,ao()},Is=()=>{Ur>0?(Wn.textContent=String(Ur),Wn.style.display="",mt.setAttribute("aria-label",`${an()||"Jump to latest"} (${Ur} new)`)):(Wn.textContent="",Wn.style.display="none",mt.setAttribute("aria-label",an()||"Jump to latest"))},Ps=()=>{Ur!==0&&(Ur=0,Is())},Ws=()=>et()==="follow"?!Jn.isFollowing():!Uo(Le,Yo),Un=()=>{if(!Ot()||ae){mt.parentNode&&mt.remove(),mt.style.display="none";return}mt.parentNode!==ue&&ue.appendChild(mt),On();let p=Jr(Le)>0&&Ws();p||Ps(),mt.style.display=p?"":"none"},ts=()=>{Jn.pause()&&(Ls(),Un())},Wr=()=>{Jn.resume(),Ps(),Un()},Rr=(l=!1)=>{et()==="follow"&&Jn.isFollowing()&&(!l&&!kr||(gr!==null&&(cancelAnimationFrame(gr),gr=null),Mo=!0,gr=requestAnimationFrame(()=>{gr=null,Mo=!1,Jn.isFollowing()&&Ta(ks(),l?220:140)})))},Rs=(l,p,h,b=()=>!0)=>{let T=l.scrollTop,D=p(),U=D-T;ao();let _=performance.now();fr=!0;let H=ce=>1-Math.pow(1-ce,3),le=ce=>{if(!b()){ao();return}let Y=p();Y!==D&&(D=Y,U=D-T);let xe=ce-_,Oe=Math.min(xe/h,1),Ae=H(Oe),tt=T+U*Ae;l.scrollTop=tt,Yn=l.scrollTop,Oe<1?zr=requestAnimationFrame(le):(l.scrollTop=D,Yn=l.scrollTop,zr=null,fr=!1)};zr=requestAnimationFrame(le)},Ta=(l,p=500)=>{let h=Jr(l)-l.scrollTop;if(Math.abs(h)<1){Yn=l.scrollTop;return}if(Math.abs(h)>=Ca){ao(),fr=!0,l.scrollTop=Jr(l),Yn=l.scrollTop,fr=!1;return}Rs(l,()=>Jr(l),p,()=>Jn.isFollowing())},Bs=()=>{let l=ks();fr=!0,l.scrollTop=Jr(l),Yn=l.scrollTop,fr=!1,Un()},Hs=l=>{ln.style.height=`${Math.max(0,Math.round(l))}px`,Tn&&(Tn.spacerHeight=Math.max(0,l))},Lo=()=>{Pr!==null&&(cancelAnimationFrame(Pr),Pr=null),ao(),Tn=null,ln.style.height="0px"},Ea=l=>{Pr!==null&&cancelAnimationFrame(Pr),Pr=requestAnimationFrame(()=>{var le;Pr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Le.querySelector(`[data-message-id="${p}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==Le;)b+=T.offsetTop,T=T.offsetParent;let D=(le=Tn==null?void 0:Tn.spacerHeight)!=null?le:0,U=Le.scrollHeight-D,{targetScrollTop:_,spacerHeight:H}=cm({anchorOffsetTop:b,topOffset:_t(),viewportHeight:Le.clientHeight,contentHeight:U});Tn={initialSpacerHeight:H,contentHeightAtAnchor:U,spacerHeight:H},Hs(H),Rs(Le,()=>_,220)})},Ma=()=>{if(et()==="follow"){if(!Jn.isFollowing()||Uo(Le,1))return;Rr(!kr);return}if(Tn&&Tn.initialSpacerHeight>0){let l=Le.scrollHeight-Tn.spacerHeight,p=dm({initialSpacerHeight:Tn.initialSpacerHeight,contentHeightAtAnchor:Tn.contentHeightAtAnchor,currentContentHeight:l});p!==Tn.spacerHeight&&Hs(p)}Un()},ka=l=>{let p=et();p==="follow"?(Wr(),Rr(!0)):p==="anchor-top"&&Ea(l)},La=l=>{let p=new Map;l.forEach(h=>{let b=Zo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(s.emit("assistant:message",h),!ko&&et()!=="anchor-top"&&Ws()&&(Ur+=1,Is(),Un())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Zo.clear(),p.forEach((h,b)=>{Zo.set(b,h)})},Ia=(l,p,h)=>{var ct,He,We,je,Qe,wt;let b=document.createElement("div"),D=(()=>{var Fe;let W=o.find(De=>De.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Fe=r.loadingIndicator)!=null&&Fe.render)return r.loadingIndicator.render})(),U=(W,Fe)=>Fe==null?!1:typeof Fe=="string"?(W.textContent=Fe,!0):(W.appendChild(Fe),!0),_=new Set,H=new Set,le=o.some(W=>W.renderAskUserQuestion),ce=[],Y=[],xe=r.enableComponentStreaming!==!1,Oe=o.some(W=>W.renderApproval)&&r.approval!==!1,Ae=[];if(p.forEach(W=>{var Je,Rt,pn,cr,er,Io,Po,ss,as,Yt,Wo,go,fo,Kr,Ro,hr;_.add(W.id);let Fe=le&&Fo(W),De=Oe&&W.variant==="approval"&&!!W.approval,ge=!Fe&&W.role==="assistant"&&!W.variant&&xe&&Gm(W);if(!De&&mr.has(W.id)){let Ze=l.querySelector(`#wrapper-${W.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),mr.delete(W.id)}if(!ge&&Ir.has(W.id)){let Ze=l.querySelector(`#wrapper-${W.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Ir.delete(W.id)}let jt=Fo(W)?`:${(Je=W.agentMetadata)!=null&&Je.askUserQuestionAnswered?"a":"u"}:${(Rt=W.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ut=rm(W,Qo)+jt,Jt=Fe||De||ge?null:sm(Lr,W.id,Ut);if(Jt){b.appendChild(Jt.cloneNode(!0)),Fo(W)&&((pn=W.toolCall)!=null&&pn.id)&&((cr=W.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((er=W.agentMetadata)!=null&&er.askUserQuestionAnswered)&&(H.add(W.toolCall.id),ja(W,r,J.composerOverlay));return}let At=null,Qt=o.find(Ze=>!!(W.variant==="reasoning"&&Ze.renderReasoning||W.variant==="tool"&&Ze.renderToolCall||!W.variant&&Ze.renderMessage)),Zn=(Io=r.layout)==null?void 0:Io.messages;if(Fo(W)&&((Po=W.agentMetadata)==null?void 0:Po.askUserQuestionAnswered)===!0){qr.delete(W.id);let Ze=l.querySelector(`#wrapper-${W.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(Qi(W)&&((as=(ss=r.features)==null?void 0:ss.suggestReplies)==null?void 0:as.enabled)!==!1)return;if(Fo(W)&&((Wo=(Yt=r.features)==null?void 0:Yt.askUserQuestion)==null?void 0:Wo.enabled)!==!1){let Ze=o.find(fn=>typeof fn.renderAskUserQuestion=="function");if(Ze&&kt.current){let fn=qr.get(W.id),Kt=fn!==Ut,Vt=null;if(Kt){let{payload:Et,complete:Mn}=ds(W),Hn=W.id,Hr=()=>{var xn;return(xn=kt.current)==null?void 0:xn.getMessages().find(Dn=>Dn.id===Hn)};Vt=Ze.renderAskUserQuestion({message:W,payload:Et,complete:Mn,resolve:xn=>{var Nn;let Dn=Hr();Dn&&((Nn=kt.current)==null||Nn.resolveAskUserQuestion(Dn,xn))},dismiss:()=>{var Dn,Nn,Bo;let xn=Hr();(Dn=xn==null?void 0:xn.agentMetadata)!=null&&Dn.awaitingLocalTool&&((Nn=kt.current)==null||Nn.markAskUserQuestionResolved(xn),(Bo=kt.current)==null||Bo.resolveAskUserQuestion(xn,"(dismissed)"))},config:r})}let yt=fn!=null;if(Kt&&Vt===null&&!yt){((go=W.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=W.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(H.add(W.toolCall.id),ja(W,r,J.composerOverlay));return}let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${W.id}`,Zt.setAttribute("data-wrapper-id",W.id),Zt.setAttribute("data-ask-plugin-stub","true"),Zt.setAttribute("data-preserve-runtime","true"),b.appendChild(Zt),ce.push({messageId:W.id,fingerprint:Ut,bubble:Vt});return}else{((Kr=W.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Ro=W.agentMetadata)!=null&&Ro.askUserQuestionAnswered)&&(H.add(W.toolCall.id),ja(W,r,J.composerOverlay));return}}else if(De){let Ze=o.find(yt=>typeof yt.renderApproval=="function"),Kt=mr.get(W.id)!==Ut,Vt=null;if(Kt&&(Ze!=null&&Ze.renderApproval)){let yt=W.id,Zt=(Et,Mn)=>{var Hr,xn,Dn;let Hn=(Hr=kt.current)==null?void 0:Hr.getMessages().find(Nn=>Nn.id===yt);Hn!=null&&Hn.approval&&(Hn.approval.toolType==="webmcp"?(xn=kt.current)==null||xn.resolveWebMcpApproval(Hn.id,Et):(Dn=kt.current)==null||Dn.resolveApproval(Hn.approval,Et,Mn))};Vt=Ze.renderApproval({message:W,defaultRenderer:()=>Mi(W,r),config:r,approve:Et=>Zt("approved",Et),deny:Et=>Zt("denied",Et)})}if(Kt&&Vt===null){let yt=l.querySelector(`#wrapper-${W.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),mr.delete(W.id),At=Mi(W,r)}else{let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${W.id}`,yt.setAttribute("data-wrapper-id",W.id),yt.setAttribute("data-approval-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),b.appendChild(yt),Ae.push({messageId:W.id,fingerprint:Ut,bubble:Vt});return}}else if(Qt)if(W.variant==="reasoning"&&W.reasoning&&Qt.renderReasoning){if(!Ve)return;At=Qt.renderReasoning({message:W,defaultRenderer:()=>hl(W,r),config:r})}else if(W.variant==="tool"&&W.toolCall&&Qt.renderToolCall){if(!ve)return;At=Qt.renderToolCall({message:W,defaultRenderer:()=>bl(W,r),config:r})}else Qt.renderMessage&&(At=Qt.renderMessage({message:W,defaultRenderer:()=>{let Ze=fl(W,h,Zn,r.messageActions,Z,{loadingIndicatorRenderer:D,widgetConfig:r});return W.role!=="user"&&wl(Ze,W,r,O),Ze},config:r}));if(!At&&ge){let Ze=Qm(W);if(Ze){let fn=Ir.get(W.id),Kt=fn!==Ut,Vt=r.wrapComponentDirectiveInBubble!==!1,yt=null;if(Kt){let Zt=Vm(Ze,{config:r,message:W,transform:h});if(Zt)if(Vt){let Et=document.createElement("div");if(Et.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(" "),Et.id=`bubble-${W.id}`,Et.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Mn=document.createElement("div");Mn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Mn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Et.appendChild(Mn)}Et.appendChild(Zt),yt=Et}else{let Et=document.createElement("div");if(Et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Et.id=`bubble-${W.id}`,Et.setAttribute("data-message-id",W.id),Et.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Mn=document.createElement("div");Mn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Mn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Et.appendChild(Mn)}Et.appendChild(Zt),yt=Et}}if(yt||fn!=null){let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${W.id}`,Zt.setAttribute("data-wrapper-id",W.id),Zt.setAttribute("data-component-directive-stub","true"),Zt.setAttribute("data-preserve-runtime","true"),Vt||Zt.classList.add("persona-w-full"),b.appendChild(Zt),Y.push({messageId:W.id,fingerprint:Ut,bubble:yt});return}}}if(!At)if(W.variant==="reasoning"&&W.reasoning){if(!Ve)return;At=hl(W,r)}else if(W.variant==="tool"&&W.toolCall){if(!ve)return;At=bl(W,r)}else if(W.variant==="approval"&&W.approval){if(r.approval===!1)return;At=Mi(W,r)}else{let Ze=(hr=r.layout)==null?void 0:hr.messages;Ze!=null&&Ze.renderUserMessage&&W.role==="user"?At=Ze.renderUserMessage({message:W,config:r,streaming:!!W.streaming}):Ze!=null&&Ze.renderAssistantMessage&&W.role==="assistant"?At=Ze.renderAssistantMessage({message:W,config:r,streaming:!!W.streaming}):At=fl(W,h,Ze,r.messageActions,Z,{loadingIndicatorRenderer:D,widgetConfig:r}),W.role!=="user"&&At&&wl(At,W,r,O)}let sn=document.createElement("div");sn.className="persona-flex",sn.id=`wrapper-${W.id}`,sn.setAttribute("data-wrapper-id",W.id),W.role==="user"&&sn.classList.add("persona-justify-end"),(At==null?void 0:At.getAttribute("data-persona-component-directive"))==="true"&&sn.classList.add("persona-w-full"),sn.appendChild(At),am(Lr,W.id,Ut,sn),b.appendChild(sn)}),J.composerOverlay&&J.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let De=Fe.getAttribute("data-persona-ask-sheet-for");De&&!H.has(De)&&us(J.composerOverlay,De)}),(He=(ct=r.features)==null?void 0:ct.toolCallDisplay)!=null&&He.grouped){let W=[],Fe=[];p.forEach(De=>{if(De.variant==="tool"&&De.toolCall&&ve){Fe.push(De);return}Fe.length>1&&W.push(Fe),Fe=[]}),Fe.length>1&&W.push(Fe),W.forEach((De,ge)=>{var Je,Rt;let jt=De.map(pn=>Array.from(b.children).find(cr=>cr instanceof HTMLElement&&cr.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if(jt.length<2)return;let Ut=document.createElement("div");Ut.className="persona-flex",Ut.id=`wrapper-tool-group-${ge}-${De[0].id}`,Ut.setAttribute("data-wrapper-id",`tool-group-${ge}-${De[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let At=document.createElement("div");At.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Qt=`Called ${De.length} tools`,Zn=(Rt=(Je=r.toolCall)==null?void 0:Je.renderGroupedSummary)==null?void 0:Rt.call(Je,{messages:De,toolCalls:De.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:Qt,config:r});U(At,Zn)||(At.textContent=Qt);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(At,sn),Ut.appendChild(Jt),jt[0].before(Ut),jt.forEach((pn,cr)=>{let er=document.createElement("div");er.className="persona-tool-group-item persona-relative",er.setAttribute("data-persona-tool-group-item","true"),cr<jt.length-1&&er.setAttribute("data-persona-tool-group-connector","true"),er.appendChild(pn),sn.appendChild(er)})})}im(Lr,_);let tt=p.some(W=>W.role==="assistant"&&W.streaming),ze=p[p.length-1],bt=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(kr&&p.some(W=>W.role==="user")&&!tt&&!bt){let W={config:r,streaming:!0,location:"standalone",defaultRenderer:ga},Fe=o.find(ge=>ge.renderLoadingIndicator),De=null;if(Fe!=null&&Fe.renderLoadingIndicator&&(De=Fe.renderLoadingIndicator(W)),De===null&&((We=r.loadingIndicator)!=null&&We.render)&&(De=r.loadingIndicator.render(W)),De===null&&(De=ga()),De){let ge=document.createElement("div"),jt=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;ge.className=jt?["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(De);let Ut=document.createElement("div");Ut.className="persona-flex",Ut.id="wrapper-typing-indicator",Ut.setAttribute("data-wrapper-id","typing-indicator"),Ut.appendChild(ge),b.appendChild(Ut)}}if(!kr&&p.length>0){let W=p[p.length-1],Fe={config:r,lastMessage:W,messageCount:p.length},De=o.find(jt=>jt.renderIdleIndicator),ge=null;if(De!=null&&De.renderIdleIndicator&&(ge=De.renderIdleIndicator(Fe)),ge===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(ge=r.loadingIndicator.renderIdle(Fe)),ge){let jt=document.createElement("div"),Ut=((wt=r.loadingIndicator)==null?void 0:wt.showBubble)!==!1;jt.className=Ut?["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(" "),jt.setAttribute("data-idle-indicator","true"),jt.appendChild(ge);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(jt),b.appendChild(Jt)}}if(li(l,b),ce.length>0)for(let{messageId:W,fingerprint:Fe,bubble:De}of ce){let ge=l.querySelector(`#wrapper-${W}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Fe),qr.set(W,Fe))}if(qr.size>0)for(let W of qr.keys())_.has(W)||qr.delete(W);if(Y.length>0)for(let{messageId:W,fingerprint:Fe,bubble:De}of Y){let ge=l.querySelector(`#wrapper-${W}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Fe),Ir.set(W,Fe))}if(Ir.size>0)for(let W of Ir.keys())_.has(W)||Ir.delete(W);if(Ae.length>0)for(let{messageId:W,fingerprint:Fe,bubble:De}of Ae){let ge=l.querySelector(`#wrapper-${W}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Fe),mr.set(W,Fe))}if(mr.size>0)for(let W of mr.keys())_.has(W)||mr.delete(W)},io=(l,p,h)=>{Ia(l,p,h),to()},lo=null,Pa=()=>{var h;if(lo)return;let l=b=>{let T=b.composedPath();T.includes(Me)||Ge&&T.includes(Ge)||be(!1,"user")};lo=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Ds=()=>{var p;if(!lo)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",lo,!0),lo=null};gt.push(()=>Ds());let co=null,Wa=()=>{var h;if(co)return;let l=b=>{b.key==="Escape"&&(b.isComposing||be(!1,"user"))};co=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Ns=()=>{var p;if(!co)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",co,!0),co=null};gt.push(()=>Ns());let po=!1,Fs=new Set,Ra=()=>{var p,h,b,T;let l=(b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((T=r.features)==null?void 0:T.streamAnimation)},jr=()=>{var bt,ct,He,We;if(!N())return;let l=J.peekBanner,p=J.peekTextNode;if(!l||!p)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(bt=O==null?void 0:O.getMessages())!=null?bt:[],b;for(let je=h.length-1;je>=0;je--){let Qe=h[je];if(Qe.role==="assistant"&&Qe.content){b=Qe;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let T=b.content,D=!!b.streaming,U=Ra(),_=mi(U),H=_.type!=="none"?ia(_.type,U==null?void 0:U.plugins):null,le=((ct=H==null?void 0:H.isAnimating)==null?void 0:ct.call(H,b))===!0,ce=H!==null&&(D||le);ce&&H&&!Fs.has(H.name)&&(il(H,n),Fs.add(H.name));let Y=ce&&(H!=null&&H.containerClass)?H.containerClass:null,xe=(He=p.dataset.personaPeekStreamClass)!=null?He:null;xe&&xe!==Y&&(p.classList.remove(xe),delete p.dataset.personaPeekStreamClass),Y&&xe!==Y&&(p.classList.add(Y),p.dataset.personaPeekStreamClass=Y),ce?(p.style.setProperty("--persona-stream-step",`${_.speed}ms`),p.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Oe=ce?gi(T,_.buffer,H,b,D):T;if(ce&&_.placeholder==="skeleton"&&D&&(!Oe||!Oe.trim())){let je=document.createElement("div"),Qe=ca();Qe.classList.add("persona-pill-peek__skeleton"),je.appendChild(Qe),li(p,je)}else{let je=Math.max(0,Oe.length-100),Qe=Oe.length>100?Oe.slice(-100):Oe,wt=ho(Qe);if(!ce||!H){let W=Oe.length>100?`\u2026${Qe}`:Qe;p.textContent!==W&&(p.textContent=W)}else{let W=wt;(H.wrap==="char"||H.wrap==="word")&&(W=la(wt,H.wrap,`peek-${b.id}`,{skipTags:H.skipTags,startIndex:je}));let Fe=document.createElement("div");if(Fe.innerHTML=W,H.useCaret&&Qe.length>0){let De=fi(),ge=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),jt=ge[ge.length-1];jt!=null&&jt.parentNode?jt.parentNode.insertBefore(De,jt.nextSibling):Fe.appendChild(De)}li(p,Fe),(We=H.onAfterRender)==null||We.call(H,{container:p,bubble:l,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let ze=kr||po;l.classList.toggle("persona-pill-peek--visible",ze)};if(N()){let l=J.peekBanner;if(l){let b=T=>{T.preventDefault(),T.stopPropagation(),be(!0,"user")};l.addEventListener("pointerdown",b),gt.push(()=>{l.removeEventListener("pointerdown",b)})}let p=()=>{po||(po=!0,jr())},h=()=>{po&&(po=!1,jr())};he.addEventListener("pointerenter",p),he.addEventListener("pointerleave",h),gt.push(()=>{he.removeEventListener("pointerenter",p),he.removeEventListener("pointerleave",h)}),Ge&&(Ge.addEventListener("pointerenter",p),Ge.addEventListener("pointerleave",h),gt.push(()=>{Ge.removeEventListener("pointerenter",p),Ge.removeEventListener("pointerleave",h)}))}let Ba=l=>{var xe,Oe,Ae,tt,ze,bt,ct,He;let p=(Oe=(xe=r.launcher)==null?void 0:xe.composerBar)!=null?Oe:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",b=(tt=p.bottomOffset)!=null?tt:"16px",T=p.collapsedMaxWidth,D=(ze=p.expandedMaxWidth)!=null?ze:"880px",U=(bt=p.expandedTopOffset)!=null?bt:"5vh",_=(ct=p.modalMaxWidth)!=null?ct:"880px",H=(He=p.modalMaxHeight)!=null?He:"min(90vh, 800px)",le="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",Y=Me.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",Ge){let We=Ge.style;We.bottom=b,We.width=T!=null?T:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=_,Y.maxWidth=le,Y.maxHeight=H,Y.height=H;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${ce})`,Y.top=U,Y.width=D,Y.maxWidth=le}},Br=()=>{var H,le,ce,Y,xe,Oe,Ae,tt;if(!F())return;if(N()){let bt=(ce=((le=(H=r.launcher)==null?void 0:H.composerBar)!=null?le:{}).expandedSize)!=null?ce:"anchored",ct=k?"expanded":"collapsed";Me.dataset.state=ct,Me.dataset.expandedSize=bt,Ge&&(Ge.dataset.state=ct,Ge.dataset.expandedSize=bt),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ba(k),ue.style.display=k?"flex":"none",ye(),k?(Pa(),Wa()):(Ds(),Ns()),jr();return}let l=An(r),p=(Y=n.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(xe=r.launcher)==null?void 0:xe.mobileBreakpoint)!=null?Oe:640,b=(tt=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?tt:!0,T=p.innerWidth<=h,D=b&&T&&M,U=vr(r).reveal;k?(Me.style.removeProperty("display"),Me.style.display=l?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),on?on.element.style.display="none":gn&&(gn.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!D?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),on?on.element.style.display=l?"none":"":gn&&(gn.style.display=l?"none":""))},be=(l,p="user")=>{var D,U;if(!F()||k===l)return;let h=k;k=l,Br();let b=(()=>{var Ae,tt,ze,bt,ct,He,We,je,Qe,wt;let _=(tt=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?tt:!1,H=(ze=n.ownerDocument.defaultView)!=null?ze:window,le=(ct=(bt=r.launcher)==null?void 0:bt.mobileFullscreen)!=null?ct:!0,ce=(We=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?We:640,Y=H.innerWidth<=ce,xe=An(r)&&le&&Y,Oe=N()&&((wt=(Qe=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Qe.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return _||le&&Y&&M||xe||Oe})();if(k&&b){if(!rn){let _=n.getRootNode(),H=_ instanceof ShadowRoot?_.host:n.closest(".persona-host");H&&(rn=ll(H,(U=(D=r.launcher)==null?void 0:D.zIndex)!=null?U:In))}un||(un=cl(n.ownerDocument))}else k||(rn==null||rn(),rn=null,un==null||un(),un=null);k&&(_s(),et()==="follow"?Rr(!0):Bs());let T={open:k,source:p,timestamp:Date.now()};k&&!h?s.emit("widget:opened",T):!k&&h&&s.emit("widget:closed",T),s.emit("widget:state",{open:k,launcherEnabled:M,voiceActive:vt.active,streaming:O.isStreaming()})},w=l=>{Mt(l?"stop":"send"),V&&(V.disabled=l),Eo.buttons.forEach(p=>{p.disabled=l}),_e.dataset.personaComposerStreaming=l?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},$=()=>{vt.active||Pe&&Pe.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>$(),200)});let P=()=>{var h,b,T,D,U,_,H,le,ce,Y,xe;wr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",Sn.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",Pe.placeholder=(_=(U=r.copy)==null?void 0:U.inputPlaceholder)!=null?_:"How can I help...";let l=Le.querySelector("[data-persona-intro-card]");if(l){let Oe=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(Le.classList.remove("persona-gap-3"),Le.classList.add("persona-gap-6")):(Le.classList.remove("persona-gap-6"),Le.classList.add("persona-gap-3"))}!((ce=(le=r.sendButton)==null?void 0:le.useIcon)!=null&&ce)&&!(O!=null&&O.isStreaming())&&(Ue.textContent=(xe=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?xe:"Send"),Pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{m(p=>({...p,sessionId:l}))}});let G=null,ie=()=>{G==null&&(G=setInterval(()=>{let l=Xe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(G),G=null;return}let p=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Ka(p-b))})},100))};O=new si(r,{onMessagesChanged(l){var b;io(Xe,l,Ie),ie(),Go(l),Rr(!kr),La(l);let p=[...l].reverse().find(T=>T.role==="user");l.length===0&&Lo(),!Xo||ko?(Xo=!0,Jo=(b=p==null?void 0:p.id)!=null?b:null):p&&p.id!==Jo&&(Jo=p.id,ka(p.id));let h=vt.lastUserMessageId;p&&p.id!==h&&(vt.lastUserMessageId=p.id,s.emit("user:message",p)),vt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),es(l),jr()},onStatusChanged(l){var b;let p=(b=r.statusIndicator)!=null?b:{};at(yn,(T=>{var D,U,_,H;return T==="idle"?(D=p.idleText)!=null?D:Ln.idle:T==="connecting"?(U=p.connectingText)!=null?U:Ln.connecting:T==="connected"?(_=p.connectedText)!=null?_:Ln.connected:T==="error"?(H=p.errorText)!=null?H:Ln.error:Ln[T]})(l),p,l)},onStreamingChanged(l){kr=l,w(l),O&&io(Xe,O.getMessages(),Ie),l||Rr(!0),jr()},onVoiceStatusChanged(l){var p,h;if(s.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Vr(),rs();break;case"processing":Vr(),gg();break;case"speaking":Vr(),fg();break;default:l==="idle"&&O.isBargeInActive()?(Vr(),rs(),V==null||V.setAttribute("aria-label","End voice session")):(vt.active=!1,Vr(),ir("system"),qn());break}},onArtifactsState(l){Kn=l,Xn(),es()}}),kt.current=O;let Q=null;if(O.onReadAloudChange((l,p)=>{var T;Zr=l,eo=p,to();let h=l!=null?l:Q;l&&(Q=l);let b=h&&(T=O.getMessages().find(D=>D.id===h))!=null?T:null;s.emit("message:read-aloud",{messageId:h,message:b,state:p,timestamp:Date.now()}),p==="idle"&&(Q=null)}),Xo=!0,((_c=(Fc=r.voiceRecognition)==null?void 0:Fc.provider)==null?void 0:_c.type)==="runtype")try{O.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&O.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(fe||r.onSSEEvent)&&O.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),pe==null||pe.processEvent(l,p),fe==null||fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),c&&c.then(l=>{var p,h,b;if(l){if(l.metadata&&(d=kl(l.metadata),E.syncFromMetadata()),(p=l.messages)!=null&&p.length){ko=!0;try{O.hydrateMessages(l.messages)}finally{ko=!1}}(h=l.artifacts)!=null&&h.length&&O.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Re=()=>{var p,h,b;!N()||k||!((b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||be(!0,"auto")},$e=l=>{var T;if(l.preventDefault(),O.isStreaming()){O.cancel(),pe==null||pe.reset(),K==null||K.update();return}let p=Pe.value.trim(),h=(T=Ct==null?void 0:Ct.hasAttachments())!=null?T:!1;if(!p&&!h)return;Re();let b;h&&(b=[],b.push(...Ct.getContentParts()),p&&b.push(Zi(p))),Pe.value="",Pe.style.height="auto",qt(),O.sendMessage(p,{contentParts:b}),h&&Ct.clearAttachments()},lt=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},Ye={...ci},Pt=!1,qt=()=>{Ye={...ci}},vn=()=>O.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Wt=l=>{if(!Pe)return;Pt=!0,Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),Pt=!1;let p=Pe.value.length;Pe.setSelectionRange(p,p)},Ht=()=>{Pt||qt()},mn=l=>{if(Pe){if(lt()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Pe.selectionStart===0&&Pe.selectionEnd===0,h=nm({direction:l.key==="ArrowUp"?"up":"down",history:vn(),currentValue:Pe.value,atStart:p,state:Ye});if(Ye=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Wt(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(O.isStreaming()){l.preventDefault();return}qt(),l.preventDefault(),Ue.click()}}},En=l=>{l.key!=="Escape"||l.isComposing||O.isStreaming()&&l.composedPath().includes(ue)&&(O.cancel(),pe==null||pe.reset(),K==null||K.update(),qt(),l.preventDefault(),l.stopImmediatePropagation())},Cn=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Ct)return;let p=gb(l.clipboardData);p.length!==0&&(l.preventDefault(),await Ct.handleFiles(p))},Dt=null,cn=!1,ns=null,ht=null,Hl=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ha=(l="user")=>{var D,U,_,H,le,ce,Y;if(cn||O.isStreaming())return;let p=Hl();if(!p)return;Dt=new p;let b=(U=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?U:2e3;Dt.continuous=!0,Dt.interimResults=!0,Dt.lang="en-US";let T=Pe.value;Dt.onresult=xe=>{let Oe="",Ae="";for(let ze=0;ze<xe.results.length;ze++){let bt=xe.results[ze],ct=bt[0].transcript;bt.isFinal?Oe+=ct+" ":Ae=ct}let tt=T+Oe+Ae;Pe.value=tt,ns&&clearTimeout(ns),(Oe||Ae)&&(ns=window.setTimeout(()=>{let ze=Pe.value.trim();ze&&Dt&&cn&&(uo(),Pe.value="",Pe.style.height="auto",O.sendMessage(ze,{viaVoice:!0}))},b))},Dt.onerror=xe=>{xe.error!=="no-speech"&&uo()},Dt.onend=()=>{if(cn){let xe=Pe.value.trim();xe&&xe!==T.trim()&&(Pe.value="",Pe.style.height="auto",O.sendMessage(xe,{viaVoice:!0})),uo()}};try{if(Dt.start(),cn=!0,vt.active=!0,l!=="system"&&(vt.manuallyDeactivated=!1),ir(l),qn(),V){let xe=(_=r.voiceRecognition)!=null?_:{};ht={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(H=xe.iconName)!=null?H:"mic",iconSize:parseFloat((Y=(ce=xe.iconSize)!=null?ce:(le=r.sendButton)==null?void 0:le.size)!=null?Y:"40")||24};let Oe=xe.recordingBackgroundColor,Ae=xe.recordingIconColor,tt=xe.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let ze=V.querySelector("svg");ze&&ze.setAttribute("stroke",Ae)}tt&&(V.style.borderColor=tt),V.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(cn){if(cn=!1,ns&&(clearTimeout(ns),ns=null),Dt){try{Dt.stop()}catch{}Dt=null}if(vt.active=!1,ir(l),qn(),V){if(V.classList.remove("persona-voice-recording"),ht){V.style.backgroundColor=ht.backgroundColor,V.style.color=ht.color,V.style.borderColor=ht.borderColor;let p=V.querySelector("svg");p&&p.setAttribute("stroke",ht.color||"currentColor"),ht=null}V.setAttribute("aria-label","Start voice recognition")}}},mg=(l,p)=>{var ct,He,We,je,Qe,wt,W,Fe,De;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ct=l==null?void 0:l.provider)==null?void 0:ct.type)==="runtype",T=((He=l==null?void 0:l.provider)==null?void 0:He.type)==="custom";if(!(h||b||T))return null;let U=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 H=(We=l==null?void 0:l.iconName)!=null?We:"mic",le=(je=p==null?void 0:p.size)!=null?je:"40px",ce=(Qe=l==null?void 0:l.iconSize)!=null?Qe:le,Y=parseFloat(ce)||24,xe=(wt=l==null?void 0:l.backgroundColor)!=null?wt:p==null?void 0:p.backgroundColor,Oe=(W=l==null?void 0:l.iconColor)!=null?W:p==null?void 0:p.textColor;_.style.width=ce,_.style.height=ce,_.style.minWidth=ce,_.style.minHeight=ce,_.style.fontSize="18px",_.style.lineHeight="1",Oe?_.style.color=Oe:_.style.color="var(--persona-text, #111827)";let tt=Se(H,Y,Oe||"currentColor",1.5);tt?_.appendChild(tt):_.textContent="\u{1F3A4}",xe?_.style.backgroundColor=xe:_.style.backgroundColor="",l!=null&&l.borderWidth&&(_.style.borderWidth=l.borderWidth,_.style.borderStyle="solid"),l!=null&&l.borderColor&&(_.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(_.style.paddingLeft=l.paddingX,_.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(_.style.paddingTop=l.paddingY,_.style.paddingBottom=l.paddingY),U.appendChild(_);let ze=(Fe=l==null?void 0:l.tooltipText)!=null?Fe:"Start voice recognition";if(((De=l==null?void 0:l.showTooltip)!=null?De:!1)&&ze){let ge=y("div","persona-send-button-tooltip");ge.textContent=ze,U.appendChild(ge)}return{micButton:_,micButtonWrapper:U}},Ri=()=>{var p,h,b,T,D;if(!V||ht)return;let l=(p=r.voiceRecognition)!=null?p:{};ht={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((D=(T=l.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},Bi=(l,p)=>{var D,U,_,H,le;if(!V)return;let h=V.querySelector("svg");h&&h.remove();let b=(le=ht==null?void 0:ht.iconSize)!=null?le:parseFloat((H=(_=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?_:(U=r.sendButton)==null?void 0:U.size)!=null?H:"40")||24,T=Se(l,b,p,1.5);T&&V.appendChild(T)},Da=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},rs=()=>{var T;if(!V)return;Ri();let l=(T=r.voiceRecognition)!=null?T:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(Da(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=V.querySelector("svg");D&&D.setAttribute("stroke",h)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},gg=()=>{var _,H,le,ce,Y,xe,Oe,Ae;if(!V)return;Ri();let l=(_=r.voiceRecognition)!=null?_:{},p=O.getVoiceInterruptionMode(),h=(H=l.processingIconName)!=null?H:"loader",b=(ce=(le=l.processingIconColor)!=null?le:ht==null?void 0:ht.color)!=null?ce:"",T=(xe=(Y=l.processingBackgroundColor)!=null?Y:ht==null?void 0:ht.backgroundColor)!=null?xe:"",D=(Ae=(Oe=l.processingBorderColor)!=null?Oe:ht==null?void 0:ht.borderColor)!=null?Ae:"";Da(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=T,V.style.borderColor=D;let U=b||"currentColor";V.style.color=U,Bi(h,U),V.setAttribute("aria-label","Processing voice input"),p==="none"&&(V.style.cursor="default")},fg=()=>{var le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct,He,We;if(!V)return;Ri();let l=(le=r.voiceRecognition)!=null?le:{},p=O.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",b=(ce=l.speakingIconName)!=null?ce:h,T=(Ae=l.speakingIconColor)!=null?Ae:p==="barge-in"?(xe=(Y=l.recordingIconColor)!=null?Y:ht==null?void 0:ht.color)!=null?xe:"":(Oe=ht==null?void 0:ht.color)!=null?Oe:"",D=(bt=l.speakingBackgroundColor)!=null?bt:p==="barge-in"?(tt=l.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(ze=ht==null?void 0:ht.backgroundColor)!=null?ze:"",U=(We=l.speakingBorderColor)!=null?We:p==="barge-in"?(ct=l.recordingBorderColor)!=null?ct:"":(He=ht==null?void 0:ht.borderColor)!=null?He:"";Da(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=D,V.style.borderColor=U;let _=T||"currentColor";V.style.color=_,Bi(b,_);let H=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",H),p==="none"&&(V.style.cursor="default"),p==="barge-in"&&V.classList.add("persona-voice-recording")},Vr=()=>{var l,p,h;V&&(Da(),ht&&(V.style.backgroundColor=(l=ht.backgroundColor)!=null?l:"",V.style.color=(p=ht.color)!=null?p:"",V.style.borderColor=(h=ht.borderColor)!=null?h:"",Bi(ht.iconName,ht.color||"currentColor"),ht=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},Na=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=O.getVoiceStatus(),b=O.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,qn(),ir("user"),Vr()});return}O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),vt.manuallyDeactivated=!O.isVoiceActive(),qn(),ir("user"),O.isVoiceActive()?rs():Vr()});return}if(cn){let h=Pe.value.trim();vt.manuallyDeactivated=!0,qn(),uo("user"),h&&(Pe.value="",Pe.style.height="auto",O.sendMessage(h))}else vt.manuallyDeactivated=!1,qn(),Ha("user")};jn=Na,V&&(V.addEventListener("click",Na),gt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Vr()):uo("system"),V&&V.removeEventListener("click",Na)}));let hg=s.on("assistant:complete",()=>{Ms&&(vt.active||vt.manuallyDeactivated||Ms==="assistant"&&!vt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!vt.active&&!vt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),ir("auto"),O.isVoiceActive()&&rs()}):Ha("auto"))},600))});gt.push(hg);let bg=s.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});gt.push(bg);let Dl=()=>{be(!k,"user")},on=null,gn=null;if(M&&!N()){let{instance:l,element:p}=ul({config:r,plugins:o,onToggle:Dl});on=l,l||(gn=p)}on?n.appendChild(on.element):gn&&n.appendChild(gn),Br(),Go(),P(),w(O.isStreaming()),et()==="follow"?Rr(!0):Bs(),Aa(),B&&(!M||N()?setTimeout(()=>$(),0):k&&setTimeout(()=>$(),200));let _s=()=>{var H,le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct,He,We,je,Qe,wt,W,Fe,De,ge,jt,Ut;if(N()){On(),Br();return}let l=An(r),p=(le=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?le:!1,h=l||p||((Y=(ce=r.launcher)==null?void 0:ce.fullHeight)!=null?Y:!1),b=(xe=n.ownerDocument.defaultView)!=null?xe:window,T=(Ae=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ae:!0,D=(ze=(tt=r.launcher)==null?void 0:tt.mobileBreakpoint)!=null?ze:640,U=b.innerWidth<=D,_=T&&U&&M;try{if(_){ye(),vs(n,r);return}if(L&&(L=!1,ye(),vs(n,r)),!M&&!l){he.style.height="",he.style.width="";return}if(!p&&!l){let Jt=(ct=(bt=r==null?void 0:r.launcher)==null?void 0:bt.width)!=null?ct:r==null?void 0:r.launcherWidth,At=Jt!=null?Jt:Xr;he.style.width=At,he.style.maxWidth=At}if(Tr(),!h){let Jt=b.innerHeight,At=64,Qt=(We=(He=r.launcher)==null?void 0:He.heightOffset)!=null?We:0,Zn=Math.max(200,Jt-At),sn=Math.min(640,Zn),Je=Math.max(200,sn-Qt);he.style.height=`${Je}px`}}finally{if(On(),Br(),k&&M){let At=((je=n.ownerDocument.defaultView)!=null?je:window).innerWidth<=((wt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?wt:640),Qt=(Fe=(W=r.launcher)==null?void 0:W.sidebarMode)!=null?Fe:!1,Zn=(ge=(De=r.launcher)==null?void 0:De.mobileFullscreen)!=null?ge:!0,sn=An(r)&&Zn&&At,Je=Qt||Zn&&At&&M||sn;if(Je&&!un){let Rt=n.getRootNode(),pn=Rt instanceof ShadowRoot?Rt.host:n.closest(".persona-host");pn&&!rn&&(rn=ll(pn,(Ut=(jt=r.launcher)==null?void 0:jt.zIndex)!=null?Ut:In)),un=cl(n.ownerDocument)}else Je||(rn==null||rn(),rn=null,un==null||un(),un=null)}}};_s();let Nl=(Oc=n.ownerDocument.defaultView)!=null?Oc:window;if(Nl.addEventListener("resize",_s),gt.push(()=>Nl.removeEventListener("resize",_s)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{On()});l.observe(_e),gt.push(()=>l.disconnect())}Yn=Le.scrollTop;let Fl=Jr(Le),yg=()=>{let l=Le.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:Le.ownerDocument.getSelection()},Hi=()=>lm(yg(),Le),_l=()=>{let l=Le.scrollTop,p=Jr(Le),h=p<Fl;if(Fl=p,et()!=="follow"){Yn=l,Un();return}let{action:b,nextLastScrollTop:T}=pi({following:Jn.isFollowing(),currentScrollTop:l,lastScrollTop:Yn,nearBottom:Uo(Le,Yo),userScrollThreshold:wa,isAutoScrolling:fr||Mo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Yn=T,b==="resume"){Hi()||Wr();return}b==="pause"&&ts()};if(Le.addEventListener("scroll",_l,{passive:!0}),gt.push(()=>Le.removeEventListener("scroll",_l)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ma()});l.observe(Xe),l.observe(Le),gt.push(()=>l.disconnect())}let Ol=()=>{et()==="follow"&&Jn.isFollowing()&&Hi()&&ts()},$l=Le.ownerDocument;$l.addEventListener("selectionchange",Ol),gt.push(()=>{$l.removeEventListener("selectionchange",Ol)});let ql=l=>{if(et()!=="follow")return;let p=ui({following:Jn.isFollowing(),deltaY:l.deltaY,nearBottom:Uo(Le,Yo),resumeWhenNearBottom:!0});p==="pause"?ts():p==="resume"&&!Hi()&&Wr()};Le.addEventListener("wheel",ql,{passive:!0}),gt.push(()=>Le.removeEventListener("wheel",ql)),mt.addEventListener("click",()=>{Lo(),Le.scrollTop=Le.scrollHeight,Yn=Le.scrollTop,Wr(),Rr(!0),Un()}),gt.push(()=>mt.remove()),gt.push(()=>{Ls(),Lo()});let Ul=()=>{Ke&&(Mr&&(Ke.removeEventListener("click",Mr),Mr=null),F()?(Ke.style.display="",Mr=()=>{be(!1,"user")},Ke.addEventListener("click",Mr)):Ke.style.display="none")};Ul(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{O.clearMessages(),Lr.clear(),Wr(),us(J.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 p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),fe==null||fe.clear(),pe==null||pe.reset(),K==null||K.update()})})(),Nt&&Nt.addEventListener("submit",$e),Pe==null||Pe.addEventListener("keydown",mn),Pe==null||Pe.addEventListener("input",Ht),Pe==null||Pe.addEventListener("paste",Cn);let zl=($c=n.ownerDocument)!=null?$c:document;zl.addEventListener("keydown",En,!0);let jl="persona-attachment-drop-active",Os=0,Di=()=>{Os=0,ue.classList.remove(jl)},os=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&Ct!==null},Vl=l=>{!Pi(l.dataTransfer)||!os()||(Os++,Os===1&&ue.classList.add(jl))},Kl=l=>{!Pi(l.dataTransfer)||!os()||(Os--,Os<=0&&Di())},Gl=l=>{!Pi(l.dataTransfer)||!os()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Ql=l=>{var h;if(!Pi(l.dataTransfer)||!os())return;l.preventDefault(),l.stopPropagation(),Di();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&Ct.handleFiles(p)},mo=!0;ue.addEventListener("dragenter",Vl,mo),ue.addEventListener("dragleave",Kl,mo),n.addEventListener("dragover",Gl,mo),n.addEventListener("drop",Ql,mo);let Fa=n.ownerDocument,Xl=l=>{os()&&l.preventDefault()},Jl=l=>{os()&&l.preventDefault()};Fa.addEventListener("dragover",Xl),Fa.addEventListener("drop",Jl),gt.push(()=>{Nt&&Nt.removeEventListener("submit",$e),Pe==null||Pe.removeEventListener("keydown",mn),Pe==null||Pe.removeEventListener("input",Ht),Pe==null||Pe.removeEventListener("paste",Cn),zl.removeEventListener("keydown",En,!0)}),gt.push(()=>{ue.removeEventListener("dragenter",Vl,mo),ue.removeEventListener("dragleave",Kl,mo),n.removeEventListener("dragover",Gl,mo),n.removeEventListener("drop",Ql,mo),Fa.removeEventListener("dragover",Xl),Fa.removeEventListener("drop",Jl),Di()}),gt.push(()=>{O.cancel()}),on?gt.push(()=>{on==null||on.destroy()}):gn&&gt.push(()=>{gn==null||gn.remove()});let dn={update(l){var Mn,Hn,Hr,xn,Dn,Nn,Bo,$s,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Id,Pd,Wd,Rd,Bd,Hd,Dd,Nd,Fd,_d,Od,$d,qd,Ud,zd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,vp,xp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Ip,Pp,Wp,Rp,Bp,Hp,Dp,Np,Fp,_p,Op,$p,qp,Up,zp,jp,Vp;let p=r.toolCall,h=r.messageActions,b=(Mn=r.layout)==null?void 0:Mn.messages,T=r.colorScheme,D=r.loadingIndicator,U=r.iterationDisplay,_=(Hn=r.features)==null?void 0:Hn.showReasoning,H=(Hr=r.features)==null?void 0:Hr.showToolCalls,le=(xn=r.features)==null?void 0:xn.toolCallDisplay,ce=(Dn=r.features)==null?void 0:Dn.reasoningDisplay;r={...r,...l},ye(),vs(n,r),Li(n,r),Ii(n,r),Xn(),r.colorScheme!==T&&Es();let Y=Al.getForInstance(r.plugins);o.length=0,o.push(...Y),M=(Bo=(Nn=r.launcher)==null?void 0:Nn.enabled)!=null?Bo:!0,S=(Gc=($s=r.launcher)==null?void 0:$s.autoExpand)!=null?Gc:!1,Ve=(Xc=(Qc=r.features)==null?void 0:Qc.showReasoning)!=null?Xc:!0,ve=(Yc=(Jc=r.features)==null?void 0:Jc.showToolCalls)!=null?Yc:!0,qe=(ed=(Zc=r.features)==null?void 0:Zc.scrollToBottom)!=null?ed:{};let xe=et();Te=(nd=(td=r.features)==null?void 0:td.scrollBehavior)!=null?nd:{},xe!==et()&&(Lo(),Wr()),Cr(),Un();let Oe=Ne;if(Ne=(od=(rd=r.features)==null?void 0:rd.showEventStreamToggle)!=null?od:!1,Ne&&!Oe){if(fe||(X=new ha(oe),fe=new fa(se,X),pe=pe!=null?pe:new ba,X.open().then(()=>fe==null?void 0:fe.restore()).catch(()=>{}),O.setSSEEventCallback((te,Lt)=>{var Xt;(Xt=r.onSSEEvent)==null||Xt.call(r,te,Lt),pe==null||pe.processEvent(te,Lt),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Lt)})})),!xt&&Ce){let te=(ad=(sd=r.features)==null?void 0:sd.eventStream)==null?void 0:ad.classNames,Lt="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:"");xt=y("button",Lt),xt.style.width="28px",xt.style.height="28px",xt.style.color=_n.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Xt=Se("activity","18px","currentColor",1.5);Xt&&xt.appendChild(Xt);let dt=J.clearChatButtonWrapper,Bt=J.closeButtonWrapper,hn=dt||Bt;hn&&hn.parentNode===Ce?Ce.insertBefore(xt,hn):Ce.appendChild(xt),xt.addEventListener("click",()=>{ae?ur():Nr()})}}else!Ne&&Oe&&(ur(),xt&&(xt.remove(),xt=null),fe==null||fe.clear(),X==null||X.destroy(),fe=null,X=null,pe==null||pe.reset(),pe=null);if(((id=r.launcher)==null?void 0:id.enabled)===!1&&on&&(on.destroy(),on=null),((ld=r.launcher)==null?void 0:ld.enabled)===!1&&gn&&(gn.remove(),gn=null),((cd=r.launcher)==null?void 0:cd.enabled)!==!1&&!on&&!gn){let{instance:te,element:Lt}=ul({config:r,plugins:o,onToggle:Dl});on=te,te||(gn=Lt),n.appendChild(Lt)}on&&on.update(r),q&&((dd=r.launcher)==null?void 0:dd.title)!==void 0&&(q.textContent=r.launcher.title),ke&&((pd=r.launcher)==null?void 0:pd.subtitle)!==void 0&&(ke.textContent=r.launcher.subtitle);let Ae=(ud=r.layout)==null?void 0:ud.header;if((Ae==null?void 0:Ae.layout)!==A&&Ce){let te=Ae?yi(r,Ae,{showClose:F(),onClose:()=>be(!1,"user")}):zo({config:r,showClose:F(),onClose:()=>be(!1,"user")});nt.replaceHeader(te),Ce=nt.header.element,Ft=nt.header.iconHolder,q=nt.header.headerTitle,ke=nt.header.headerSubtitle,Ke=nt.header.closeButton,A=Ae==null?void 0:Ae.layout}else if(Ae&&(Ft&&(Ft.style.display=Ae.showIcon===!1?"none":""),q&&(q.style.display=Ae.showTitle===!1?"none":""),ke&&(ke.style.display=Ae.showSubtitle===!1?"none":""),Ke&&(Ke.style.display=Ae.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let te=Ae.showClearChat;if(te!==void 0){J.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Lt}=J;Lt&&!Lt.classList.contains("persona-absolute")&&(te?Lt.classList.remove("persona-ml-auto"):Lt.classList.add("persona-ml-auto"))}}let ze=((md=r.layout)==null?void 0:md.showHeader)!==!1;Ce&&(Ce.style.display=ze?"":"none");let bt=((gd=r.layout)==null?void 0:gd.showFooter)!==!1;_e&&(_e.style.display=bt?"":"none"),On(),Un(),M!==R?M?be(S,"auto"):(k=!0,Br()):S!==I&&be(S,"auto"),I=S,R=M,_s(),Ul();let We=JSON.stringify(l.toolCall)!==JSON.stringify(p),je=JSON.stringify(r.messageActions)!==JSON.stringify(h),Qe=JSON.stringify((fd=r.layout)==null?void 0:fd.messages)!==JSON.stringify(b),wt=((hd=r.loadingIndicator)==null?void 0:hd.render)!==(D==null?void 0:D.render)||((bd=r.loadingIndicator)==null?void 0:bd.renderIdle)!==(D==null?void 0:D.renderIdle)||((yd=r.loadingIndicator)==null?void 0:yd.showBubble)!==(D==null?void 0:D.showBubble),W=r.iterationDisplay!==U,Fe=((xd=(vd=r.features)==null?void 0:vd.showReasoning)!=null?xd:!0)!==(_!=null?_:!0)||((Cd=(wd=r.features)==null?void 0:wd.showToolCalls)!=null?Cd:!0)!==(H!=null?H:!0)||JSON.stringify((Ad=r.features)==null?void 0:Ad.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify((Sd=r.features)==null?void 0:Sd.reasoningDisplay)!==JSON.stringify(ce);(We||je||Qe||wt||W||Fe)&&O&&(Qo++,io(Xe,O.getMessages(),Ie));let ge=(Td=r.launcher)!=null?Td:{},jt=(Ed=ge.headerIconHidden)!=null?Ed:!1,Ut=(kd=(Md=r.layout)==null?void 0:Md.header)==null?void 0:kd.showIcon,Jt=jt||Ut===!1,At=ge.headerIconName,Qt=(Ld=ge.headerIconSize)!=null?Ld:"48px";if(Ft){let te=ue.querySelector(".persona-border-b-persona-divider"),Lt=te==null?void 0:te.querySelector(".persona-flex-col");if(Jt)Ft.style.display="none",te&&Lt&&!te.contains(Lt)&&te.insertBefore(Lt,te.firstChild);else{if(Ft.style.display="",Ft.style.height=Qt,Ft.style.width=Qt,te&&Lt&&(te.contains(Ft)?Ft.nextSibling!==Lt&&(Ft.remove(),te.insertBefore(Ft,Lt)):te.insertBefore(Ft,Lt)),At){let dt=parseFloat(Qt)||24,Bt=Se(At,dt*.6,"currentColor",1);Bt?Ft.replaceChildren(Bt):Ft.textContent=(Id=ge.agentIconText)!=null?Id:"\u{1F4AC}"}else if(ge.iconUrl){let dt=Ft.querySelector("img");if(dt)dt.src=ge.iconUrl,dt.style.height=Qt,dt.style.width=Qt;else{let Bt=document.createElement("img");Bt.src=ge.iconUrl,Bt.alt="",Bt.className="persona-rounded-xl persona-object-cover",Bt.style.height=Qt,Bt.style.width=Qt,Ft.replaceChildren(Bt)}}else{let dt=Ft.querySelector("svg"),Bt=Ft.querySelector("img");(dt||Bt)&&Ft.replaceChildren(),Ft.textContent=(Pd=ge.agentIconText)!=null?Pd:"\u{1F4AC}"}let Xt=Ft.querySelector("img");Xt&&(Xt.style.height=Qt,Xt.style.width=Qt)}}let Zn=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showTitle,sn=(Hd=(Bd=r.layout)==null?void 0:Bd.header)==null?void 0:Hd.showSubtitle;if(q&&(q.style.display=Zn===!1?"none":""),ke&&(ke.style.display=sn===!1?"none":""),Ke){((Nd=(Dd=r.layout)==null?void 0:Dd.header)==null?void 0:Nd.showCloseButton)===!1?Ke.style.display="none":Ke.style.display="";let Lt=(Fd=ge.closeButtonSize)!=null?Fd:"32px",Xt=(_d=ge.closeButtonPlacement)!=null?_d:"inline";Ke.style.height=Lt,Ke.style.width=Lt;let{closeButtonWrapper:dt}=J,Bt=Xt==="top-right",hn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Bt!==hn)if(dt.remove(),Bt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(dt);else{let ft=($d=(Od=ge.clearChat)==null?void 0:Od.placement)!=null?$d:"inline",bn=(Ud=(qd=ge.clearChat)==null?void 0:qd.enabled)!=null?Ud:!0;dt.className=bn&&ft==="inline"?"":"persona-ml-auto";let zn=ue.querySelector(".persona-border-b-persona-divider");zn&&zn.appendChild(dt)}if(Ke.style.color=ge.closeButtonColor||_n.actionIconColor,ge.closeButtonBackgroundColor?(Ke.style.backgroundColor=ge.closeButtonBackgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let ft=ge.closeButtonBorderWidth||"0px",bn=ge.closeButtonBorderColor||"transparent";Ke.style.border=`${ft} solid ${bn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");ge.closeButtonBorderRadius?(Ke.style.borderRadius=ge.closeButtonBorderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(Ke.style.paddingLeft=ge.closeButtonPaddingX,Ke.style.paddingRight=ge.closeButtonPaddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),ge.closeButtonPaddingY?(Ke.style.paddingTop=ge.closeButtonPaddingY,Ke.style.paddingBottom=ge.closeButtonPaddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let kn=(zd=ge.closeButtonIconName)!=null?zd:"x",br=(jd=ge.closeButtonIconText)!=null?jd:"\xD7";Ke.innerHTML="";let Fn=Se(kn,"28px","currentColor",1);Fn?Ke.appendChild(Fn):Ke.textContent=br;let nn=(Vd=ge.closeButtonTooltipText)!=null?Vd:"Close chat",tr=(Kd=ge.closeButtonShowTooltip)!=null?Kd:!0;if(Ke.setAttribute("aria-label",nn),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),tr&&nn)){let ft=null,bn=()=>{if(ft||!Ke)return;let Ho=Ke.ownerDocument,qs=Ho.body;if(!qs)return;ft=Dr(Ho,"div","persona-clear-chat-tooltip"),ft.textContent=nn;let Us=Dr(Ho,"div");Us.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Us);let Do=Ke.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(xo),ft.style.left=`${Do.left+Do.width/2}px`,ft.style.top=`${Do.top-8}px`,ft.style.transform="translate(-50%, -100%)",qs.appendChild(ft)},zn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};dt.addEventListener("mouseenter",bn),dt.addEventListener("mouseleave",zn),Ke.addEventListener("focus",bn),Ke.addEventListener("blur",zn),dt._cleanupTooltip=()=>{zn(),dt&&(dt.removeEventListener("mouseenter",bn),dt.removeEventListener("mouseleave",zn)),Ke&&(Ke.removeEventListener("focus",bn),Ke.removeEventListener("blur",zn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Rt}=J;if(Je){let te=(Gd=ge.clearChat)!=null?Gd:{},Lt=(Qd=te.enabled)!=null?Qd:!0,Xt=(Jd=(Xd=r.layout)==null?void 0:Xd.header)==null?void 0:Jd.showClearChat,dt=Xt!==void 0?Xt:Lt,Bt=(Yd=te.placement)!=null?Yd:"inline";if(Rt){Rt.style.display=dt?"":"none";let{closeButtonWrapper:hn}=J;!N()&&hn&&!hn.classList.contains("persona-absolute")&&(dt?hn.classList.remove("persona-ml-auto"):hn.classList.add("persona-ml-auto"));let kn=Bt==="top-right",br=Rt.classList.contains("persona-absolute");if(!N()&&kn!==br&&dt){if(Rt.remove(),kn)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",ue.style.position="relative",ue.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let nn=ue.querySelector(".persona-border-b-persona-divider"),tr=J.closeButtonWrapper;nn&&tr&&tr.parentElement===nn?nn.insertBefore(Rt,tr):nn&&nn.appendChild(Rt)}let Fn=J.closeButtonWrapper;Fn&&!Fn.classList.contains("persona-absolute")&&(kn?Fn.classList.add("persona-ml-auto"):Fn.classList.remove("persona-ml-auto"))}}if(dt){if(!N()){let ft=(Zd=te.size)!=null?Zd:"32px";Je.style.height=ft,Je.style.width=ft}let hn=(ep=te.iconName)!=null?ep:"refresh-cw",kn=(tp=te.iconColor)!=null?tp:"";Je.style.color=kn||_n.actionIconColor,Je.innerHTML="";let br=N()?"14px":"20px",Fn=Se(hn,br,"currentColor",2);if(Fn&&Je.appendChild(Fn),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 ft=te.borderWidth||"0px",bn=te.borderColor||"transparent";Je.style.border=`${ft} solid ${bn}`,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 nn=(np=te.tooltipText)!=null?np:"Clear chat",tr=(rp=te.showTooltip)!=null?rp:!0;if(Je.setAttribute("aria-label",nn),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),tr&&nn)){let ft=null,bn=()=>{if(ft||!Je)return;let Ho=Je.ownerDocument,qs=Ho.body;if(!qs)return;ft=Dr(Ho,"div","persona-clear-chat-tooltip"),ft.textContent=nn;let Us=Dr(Ho,"div");Us.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Us);let Do=Je.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(xo),ft.style.left=`${Do.left+Do.width/2}px`,ft.style.top=`${Do.top-8}px`,ft.style.transform="translate(-50%, -100%)",qs.appendChild(ft)},zn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};Rt.addEventListener("mouseenter",bn),Rt.addEventListener("mouseleave",zn),Je.addEventListener("focus",bn),Je.addEventListener("blur",zn),Rt._cleanupTooltip=()=>{zn(),Rt&&(Rt.removeEventListener("mouseenter",bn),Rt.removeEventListener("mouseleave",zn)),Je&&(Je.removeEventListener("focus",bn),Je.removeEventListener("blur",zn))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Tl],cr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ya.message,ya.messageAndClick];E=El({parsers:pn,handlers:cr,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Zm(r,E,re),O.updateConfig(r),io(Xe,O.getMessages(),Ie),Go(),P(),w(O.isStreaming());let er=((op=r.voiceRecognition)==null?void 0:op.enabled)===!0,Io=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Po=((ap=(sp=r.voiceRecognition)==null?void 0:sp.provider)==null?void 0:ap.type)==="runtype";if(er&&(Io||Po))if(!V||!St){let te=mg(r.voiceRecognition,r.sendButton);te&&(V=te.micButton,St=te.micButtonWrapper,ot.insertBefore(St,rt),V.addEventListener("click",Na),V.disabled=O.isStreaming())}else{let te=(ip=r.voiceRecognition)!=null?ip:{},Lt=(lp=r.sendButton)!=null?lp:{},Xt=(cp=te.iconName)!=null?cp:"mic",dt=(dp=Lt.size)!=null?dp:"40px",Bt=(pp=te.iconSize)!=null?pp:dt,hn=parseFloat(Bt)||24;V.style.width=Bt,V.style.height=Bt,V.style.minWidth=Bt,V.style.minHeight=Bt;let kn=(mp=(up=te.iconColor)!=null?up:Lt.textColor)!=null?mp:"currentColor";V.innerHTML="";let br=Se(Xt,hn,kn,2);br?V.appendChild(br):V.textContent="\u{1F3A4}";let Fn=(gp=te.backgroundColor)!=null?gp:Lt.backgroundColor;Fn?V.style.backgroundColor=Fn:V.style.backgroundColor="",kn?V.style.color=kn:V.style.color="var(--persona-text, #111827)",te.borderWidth?(V.style.borderWidth=te.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),te.borderColor?V.style.borderColor=te.borderColor:V.style.borderColor="",te.paddingX?(V.style.paddingLeft=te.paddingX,V.style.paddingRight=te.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),te.paddingY?(V.style.paddingTop=te.paddingY,V.style.paddingBottom=te.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let nn=St==null?void 0:St.querySelector(".persona-send-button-tooltip"),tr=(fp=te.tooltipText)!=null?fp:"Start voice recognition";if(((hp=te.showTooltip)!=null?hp:!1)&&tr)if(nn)nn.textContent=tr,nn.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=tr,St==null||St.insertBefore(bn,V)}else nn&&(nn.style.display="none");St.style.display="",V.disabled=O.isStreaming()}else V&&St&&(St.style.display="none",((yp=(bp=r.voiceRecognition)==null?void 0:bp.provider)==null?void 0:yp.type)==="runtype"?O.isVoiceActive()&&O.toggleVoice():cn&&uo());if(((vp=r.attachments)==null?void 0:vp.enabled)===!0)if(!me||!de){let te=(xp=r.attachments)!=null?xp:{},Xt=(Cp=((wp=r.sendButton)!=null?wp:{}).size)!=null?Cp:"40px";ut||(ut=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ut.style.display="none",Nt.insertBefore(ut,Pe)),Ee||(Ee=document.createElement("input"),Ee.type="file",Ee.accept=((Ap=te.allowedTypes)!=null?Ap:Qr).join(","),Ee.multiple=((Sp=te.maxFiles)!=null?Sp:4)>1,Ee.style.display="none",Ee.setAttribute("aria-label","Attach files"),Nt.insertBefore(Ee,Pe)),me=y("div","persona-send-button-wrapper"),de=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),de.type="button",de.setAttribute("aria-label",(Tp=te.buttonTooltipText)!=null?Tp:"Attach file");let dt=(Ep=te.buttonIconName)!=null?Ep:"paperclip",Bt=Xt,hn=parseFloat(Bt)||40,kn=Math.round(hn*.6);de.style.width=Bt,de.style.height=Bt,de.style.minWidth=Bt,de.style.minHeight=Bt,de.style.fontSize="18px",de.style.lineHeight="1",de.style.backgroundColor="transparent",de.style.color="var(--persona-primary, #111827)",de.style.border="none",de.style.borderRadius="6px",de.style.transition="background-color 0.15s ease",de.addEventListener("mouseenter",()=>{de.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),de.addEventListener("mouseleave",()=>{de.style.backgroundColor="transparent"});let br=Se(dt,kn,"currentColor",1.5);br?de.appendChild(br):de.textContent="\u{1F4CE}",de.addEventListener("click",tr=>{tr.preventDefault(),Ee==null||Ee.click()}),me.appendChild(de);let Fn=(Mp=te.buttonTooltipText)!=null?Mp:"Attach file",nn=y("div","persona-send-button-tooltip");nn.textContent=Fn,me.appendChild(nn),pt.append(me),!Ct&&Ee&&ut&&(Ct=oa.fromConfig(te),Ct.setPreviewsContainer(ut),Ee.addEventListener("change",async()=>{Ct&&(Ee!=null&&Ee.files)&&(await Ct.handleFileSelect(Ee.files),Ee.value="")})),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(eg(te.dropOverlay))}else{me.style.display="";let te=(kp=r.attachments)!=null?kp:{};Ee&&(Ee.accept=((Lp=te.allowedTypes)!=null?Lp:Qr).join(","),Ee.multiple=((Ip=te.maxFiles)!=null?Ip:4)>1),Ct&&Ct.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else me&&(me.style.display="none"),Ct&&Ct.clearAttachments(),(Pp=ue.querySelector(".persona-attachment-drop-overlay"))==null||Pp.remove();let Yt=(Wp=r.sendButton)!=null?Wp:{},Wo=(Rp=Yt.useIcon)!=null?Rp:!1,go=(Bp=Yt.iconText)!=null?Bp:"\u2191",fo=Yt.iconName,Kr=(Hp=Yt.tooltipText)!=null?Hp:"Send message",Ro=(Dp=Yt.showTooltip)!=null?Dp:!1,hr=(Np=Yt.size)!=null?Np:"40px",Ze=Yt.backgroundColor,fn=Yt.textColor;if(Wo){if(Ue.style.width=hr,Ue.style.height=hr,Ue.style.minWidth=hr,Ue.style.minHeight=hr,Ue.style.fontSize="18px",Ue.style.lineHeight="1",Ue.innerHTML="",fn?Ue.style.color=fn:Ue.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let te=parseFloat(hr)||24,Lt=(fn==null?void 0:fn.trim())||"currentColor",Xt=Se(fo,te,Lt,2);Xt?Ue.appendChild(Xt):Ue.textContent=go}else Ue.textContent=go;Ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ze?(Ue.style.backgroundColor=Ze,Ue.classList.remove("persona-bg-persona-primary")):(Ue.style.backgroundColor="",Ue.classList.add("persona-bg-persona-primary"))}else Ue.textContent=(_p=(Fp=r.copy)==null?void 0:Fp.sendButtonLabel)!=null?_p:"Send",Ue.style.width="",Ue.style.height="",Ue.style.minWidth="",Ue.style.minHeight="",Ue.style.fontSize="",Ue.style.lineHeight="",Ue.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Ze?(Ue.style.backgroundColor=Ze,Ue.classList.remove("persona-bg-persona-accent")):Ue.classList.add("persona-bg-persona-accent"),fn?Ue.style.color=fn:Ue.classList.add("persona-text-white");Yt.borderWidth?(Ue.style.borderWidth=Yt.borderWidth,Ue.style.borderStyle="solid"):(Ue.style.borderWidth="",Ue.style.borderStyle=""),Yt.borderColor?Ue.style.borderColor=Yt.borderColor:Ue.style.borderColor="",Yt.paddingX?(Ue.style.paddingLeft=Yt.paddingX,Ue.style.paddingRight=Yt.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Yt.paddingY?(Ue.style.paddingTop=Yt.paddingY,Ue.style.paddingBottom=Yt.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let Kt=rt==null?void 0:rt.querySelector(".persona-send-button-tooltip");if(Ro&&Kr)if(Kt)Kt.textContent=Kr,Kt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Kr,rt==null||rt.insertBefore(te,Ue)}else Kt&&(Kt.style.display="none");let Vt=(zp=(Op=r.layout)==null?void 0:Op.contentMaxWidth)!=null?zp:N()?(Up=(qp=($p=r.launcher)==null?void 0:$p.composerBar)==null?void 0:qp.contentMaxWidth)!=null?Up:"720px":void 0;Vt?(Xe.style.maxWidth=Vt,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%",Nt&&(Nt.style.maxWidth=Vt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Gt&&(Gt.style.maxWidth=Vt,Gt.style.marginLeft="auto",Gt.style.marginRight="auto")):(Xe.style.maxWidth="",Xe.style.marginLeft="",Xe.style.marginRight="",Xe.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Gt&&(Gt.style.maxWidth="",Gt.style.marginLeft="",Gt.style.marginRight=""));let yt=(jp=r.statusIndicator)!=null?jp:{},Zt=(Vp=yt.visible)!=null?Vp:!0;if(yn.style.display=Zt?"":"none",O){let te=O.getStatus();at(yn,(Xt=>{var dt,Bt,hn,kn;return Xt==="idle"?(dt=yt.idleText)!=null?dt:Ln.idle:Xt==="connecting"?(Bt=yt.connectingText)!=null?Bt:Ln.connecting:Xt==="connected"?(hn=yt.connectedText)!=null?hn:Ln.connected:Xt==="error"?(kn=yt.errorText)!=null?kn:Ln.error:Ln[Xt]})(te),yt,te)}yn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=yt.align==="left"?"persona-text-left":yt.align==="center"?"persona-text-center":"persona-text-right";yn.classList.add(Et)},open(){F()&&be(!0,"api")},close(){F()&&be(!1,"api")},toggle(){F()&&be(!k,"api")},clearChat(){Rn=!1,O.clearMessages(),Lr.clear(),Wr();try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},E.syncFromMetadata(),fe==null||fe.clear(),pe==null||pe.reset(),K==null||K.update()},setMessage(l){return!Pe||O.isStreaming()?!1:(!k&&F()&&be(!0,"system"),Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Pe.value.trim();return p?(!k&&F()&&be(!0,"system"),Pe.value="",Pe.style.height="auto",O.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return O.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(O.isVoiceActive()||(!k&&F()&&be(!0,"system"),vt.manuallyDeactivated=!1,qn(),O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),ir("user"),O.isVoiceActive()&&rs()})),!0):cn?!0:Hl()?(!k&&F()&&be(!0,"system"),vt.manuallyDeactivated=!1,qn(),Ha("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,qn(),ir("user"),Vr()}),!0):!1:cn?(vt.manuallyDeactivated=!0,qn(),uo("user"),!0):!1},injectMessage(l){return!k&&F()&&be(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!k&&F()&&be(!0,"system");let p=O.injectAssistantMessage(l);return z&&(z=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),p},injectUserMessage(l){return!k&&F()&&be(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!k&&F()&&be(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!k&&F()&&be(!0,"system"),O.injectMessageBatch(l)},injectComponentDirective(l){return!k&&F()&&be(!0,"system"),O.injectComponentDirective(l)},injectTestMessage(l){!k&&F()&&be(!0,"system"),O.injectTestEvent(l)},async connectStream(l,p){return O.connectStream(l,p)},__pushEventStreamEvent(l){fe&&(pe==null||pe.processEvent(l.type,l.payload),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ne||!fe||Nr()},hideEventStream(){ae&&ur()},isEventStreamVisible(){return ae},showArtifacts(){pr(r)&&(Rn=!1,Xn(),Tt==null||Tt.setMobileOpen(!0))},hideArtifacts(){pr(r)&&(Rn=!0,Xn())},upsertArtifact(l){return pr(r)?(Rn=!1,O.upsertArtifact(l)):null},selectArtifact(l){pr(r)&&O.selectArtifact(l)},clearArtifacts(){pr(r)&&O.clearArtifacts()},getArtifacts(){var l;return(l=O==null?void 0:O.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=O==null?void 0:O.getSelectedArtifactId())!=null?l:null},focusInput(){return M&&!k&&!N()||!Pe?!1:(Pe.focus(),!0)},async resolveApproval(l,p,h){let T=O.getMessages().find(D=>{var U;return D.variant==="approval"&&((U=D.approval)==null?void 0:U.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){O.resolveWebMcpApproval(T.id,p);return}return O.resolveApproval(T.approval,p,h)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){m(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return F()&&k},isVoiceActive(){return vt.active},toggleReadAloud(l){O.toggleReadAloud(l)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(l){return O.getReadAloudState(l)},onReadAloudChange(l){return O.onReadAloudChange(l)},getState(){return{open:F()&&k,launcherEnabled:M,voiceActive:vt.active,streaming:O.isStreaming()}},showCSATFeedback(l){!k&&F()&&be(!0,"system");let p=Xe.querySelector(".persona-feedback-container");p&&p.remove();let h=Xm({onSubmit:async(b,T)=>{var D;O.isClientTokenMode()&&await O.submitCSATFeedback(b,T),(D=l==null?void 0:l.onSubmit)==null||D.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&F()&&be(!0,"system");let p=Xe.querySelector(".persona-feedback-container");p&&p.remove();let h=Jm({onSubmit:async(b,T)=>{var D;O.isClientTokenMode()&&await O.submitNPSFeedback(b,T),(D=l==null?void 0:l.onSubmit)==null||D.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return O.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return O.submitNPSFeedback(l,p)},destroy(){G!=null&&(clearInterval(G),G=null),gt.forEach(l=>l()),Me.remove(),Ge==null||Ge.remove(),on==null||on.destroy(),gn==null||gn.remove(),Mr&&Ke.removeEventListener("click",Mr)}};if((((qc=e==null?void 0:e.debugTools)!=null?qc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:h=>h?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,gt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",p),gt.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ne){let _=le=>{let ce=le.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===l)&&dn.showEventStream()},H=le=>{let ce=le.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===l)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",H),gt.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",H)})}let h=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.showArtifacts()},b=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.hideArtifacts()},T=_=>{let H=_.detail;H!=null&&H.instanceId&&H.instanceId!==l||H!=null&&H.artifact&&dn.upsertArtifact(H.artifact)},D=_=>{let H=_.detail;H!=null&&H.instanceId&&H.instanceId!==l||typeof(H==null?void 0:H.id)=="string"&&dn.selectArtifact(H.id)},U=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",U),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",U)})}let lr=fb(r.persistState);if(lr&&F()){let l=hb(lr.storage),p=`${lr.keyPrefix}widget-open`,h=`${lr.keyPrefix}widget-voice`,b=`${lr.keyPrefix}widget-voice-mode`;if(l){let T=((Uc=lr.persist)==null?void 0:Uc.openState)&&l.getItem(p)==="true",D=((zc=lr.persist)==null?void 0:zc.voiceState)&&l.getItem(h)==="true",U=((jc=lr.persist)==null?void 0:jc.voiceState)&&l.getItem(b)==="true";if(T&&setTimeout(()=>{dn.open(),setTimeout(()=>{var _;if(D||U)dn.startVoiceRecognition();else if((_=lr.persist)!=null&&_.focusInput){let H=n.querySelector("textarea");H&&H.focus()}},100)},0),(Vc=lr.persist)!=null&&Vc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Kc=lr.persist)!=null&&Kc.voiceState&&(s.on("voice:state",_=>{l.setItem(h,_.active?"true":"false")}),s.on("user:message",_=>{l.setItem(b,_.viaVoice?"true":"false")})),lr.clearOnChatClear){let _=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(b)},H=()=>_();window.addEventListener("persona:clear-chat",H),gt.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return g&&F()&&setTimeout(()=>{dn.open()},0),jr(),xa||eu().then(()=>{O&&(Qo++,Lr.clear(),io(Xe,O.getMessages(),Ie))}).catch(()=>{}),dn};var bb=(n,t)=>{let e=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(e);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(e);return o?Math.max(0,t*parseFloat(o[1])/100):420},yb=(n,t)=>{if(t===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=t},vb=(n,t)=>{t===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},xb=(n,t)=>{let e=n.parentElement;if(!e)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",e.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},ng=(n,t)=>{var r,o;let e=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=e?"":"100%",n.style.display=e?"":"flex",n.style.flexDirection=e?"":"column",n.style.flex=e?"":"1 1 auto",n.style.minHeight=e?"":"0"},Wl=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},rg=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",Wl(n)},Ll=n=>{n.style.transition=""},Il=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},Pl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},Wi=(n,t)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",t.style.alignItems=""},wb=(n,t,e,r,o)=>{o?e.parentElement!==t&&(n.replaceChildren(),t.replaceChildren(e,r),n.appendChild(t)):e.parentElement===t&&(t.replaceChildren(),n.appendChild(e),n.appendChild(r))},Cb=(n,t,e,r,o,s)=>{let a=s?t:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,e):a.lastElementChild!==r&&a.replaceChildren(e,r)},og=(n,t,e,r,o,s,a)=>{var v,x,E,M,S,B;let i=vr(s),d=i.reveal==="push";wb(n,t,e,r,d),Cb(n,t,e,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",e.style.display="flex",e.style.flexDirection="column",e.style.minHeight="0",e.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,g=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(M=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?M:640,u=c!=null?c.innerWidth<=f:!1;if(g&&u&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),Il(t),Ll(r),rg(r),Pl(e),Wi(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",e.style.flex="1 1 auto",e.style.width="100%",e.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((B=(S=s==null?void 0:s.launcher)==null?void 0:S.zIndex)!=null?B:In),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",e.style.flex="1 1 auto",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),rg(r),yb(r,i.maxHeight),i.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",Il(t),Ll(r),Pl(e),Wi(o,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":R;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=I,r.style.transform=A,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",Ll(r),Wl(r),Wi(o,r);let I=bb(i.width,n.clientWidth),R=Math.max(0,n.clientWidth),A=i.animate?"margin-left 180ms ease":"none",L=i.side==="right"?a?-I:0:a?0:-I;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=`${R+I}px`,t.style.transition=A,t.style.marginLeft=`${L}px`,t.style.transform="",e.style.flex="0 0 auto",e.style.flexGrow="0",e.style.flexShrink="0",e.style.width=`${R}px`,e.style.maxWidth=`${R}px`,e.style.minWidth=`${R}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",Il(t),Wl(r),Pl(e),Wi(o,r);let I=i.reveal==="emerge";I?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",L=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",vb(r,i.maxHeight),r.style.overflow=I||L?"hidden":"visible",r.style.transition=A,I&&(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")}},Ab=(n,t)=>{let e=n.ownerDocument.createElement("div");return ng(e,t),n.appendChild(e),{mode:"direct",host:e,shell:null,syncWidgetState:()=>{},updateConfig(r){ng(e,r)},destroy(){e.remove()}}},Sb=(n,t)=>{var B,I,R,A;let{ownerDocument:e}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=n.nextSibling,a=e.createElement("div"),i=e.createElement("div"),d=e.createElement("div"),c=e.createElement("aside"),g=e.createElement("div"),f=(I=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||I?(A=(R=t==null?void 0:t.launcher)==null?void 0:R.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",c.appendChild(g),r.insertBefore(a,n),d.appendChild(n);let u=null,m=()=>{u==null||u.disconnect(),u=null},v=()=>{m(),vr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{og(a,i,d,c,g,t,f)}),u.observe(a))},x=!1,E=()=>{og(a,i,d,c,g,t,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,xb(a,vr(t)))},M=a.ownerDocument.defaultView,S=()=>{E()};return M==null||M.addEventListener("resize",S),vr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),E(),{mode:"docked",host:g,shell:a,syncWidgetState(L){let N=L.launcherEnabled?L.open:!0;f!==N&&(f=N,E())},updateConfig(L){var N,F;t=L,((F=(N=t==null?void 0:t.launcher)==null?void 0:N.enabled)!=null?F:!0)===!1&&(f=!0),E()},destroy(){M==null||M.removeEventListener("resize",S),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},sg=(n,t)=>An(t)?Sb(n,t):Ab(n,t);var va={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ag=.15,ig=1.5,Rl="persona-preview-shell-theme",Tb={load:()=>null,save:()=>{},clear:()=>{}},Eb=["How do I get started?","Pricing & plans","Talk to support"];function Bl(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Mb(n){return n==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function lg(n){let t=Mb(n);return`* { box-sizing: border-box; }
110
110
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
111
111
  html { color-scheme: ${n}; }
112
- body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
112
+ body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
113
113
  .preview-iframe-mock { min-height: 100%; }
114
- .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
115
- .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${e.dot}; }
114
+ .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
115
+ .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${t.dot}; }
116
116
  .preview-iframe-copy { padding: 32px; }
117
- .preview-iframe-line { border-radius: 999px; background: ${e.skeleton}; margin-bottom: 12px; }
117
+ .preview-iframe-line { border-radius: 999px; background: ${t.skeleton}; margin-bottom: 12px; }
118
118
  .preview-iframe-line.hero { width: 48%; height: 16px; }
119
119
  .preview-iframe-line.body { width: 72%; height: 10px; }
120
120
  .preview-iframe-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 24px 0; }
121
- .preview-iframe-card { height: 84px; border-radius: 14px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
121
+ .preview-iframe-card { height: 84px; border-radius: 14px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
122
122
  .preview-workspace-shell { height: 100%; min-height: 100%; display: flex; flex-direction: column; }
123
- .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
123
+ .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
124
124
  .preview-workspace-topbar-left { display: flex; align-items: center; gap: 12px; }
125
- .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
126
- .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${e.skeleton}; }
127
- .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
125
+ .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
126
+ .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${t.skeleton}; }
127
+ .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
128
128
  .preview-workspace-body { flex: 1; min-height: 0; display: flex; padding: 20px; }
129
- .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
129
+ .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
130
130
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
131
131
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
132
- .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
133
- .preview-workspace-card.short { height: 96px; }`}function ag(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(Il);r||(r=t.createElement("style"),r.id=Il,t.head.appendChild(r)),r.textContent=sg(e)}var Ty=`
132
+ .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
133
+ .preview-workspace-card.short { height: 96px; }`}function cg(n,t){let e=n.contentDocument;if(!(e!=null&&e.documentElement))return;let r=e.getElementById(Rl);r||(r=e.createElement("style"),r.id=Rl,e.head.appendChild(r)),r.textContent=lg(t)}var kb=`
134
134
  <div class="preview-iframe-mock" aria-hidden="true">
135
135
  <div class="preview-iframe-chrome">
136
136
  <span class="preview-iframe-dot"></span>
@@ -149,7 +149,7 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
149
149
  <div class="preview-iframe-line body"></div>
150
150
  <div class="preview-iframe-line body"></div>
151
151
  </div>
152
- </div>`,My=`
152
+ </div>`,Lb=`
153
153
  <div class="preview-workspace-content-shell" aria-hidden="true">
154
154
  <div class="preview-iframe-line hero"></div>
155
155
  <div class="preview-iframe-line body"></div>
@@ -162,8 +162,8 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
162
162
  <div class="preview-workspace-card short"></div>
163
163
  <div class="preview-workspace-card short"></div>
164
164
  </div>
165
- </div>`;function ig(n,e,t,r){let o=`
166
- ${Ty}
165
+ </div>`;function dg(n,t,e,r){let o=`
166
+ ${kb}
167
167
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
168
168
  <div class="preview-workspace-shell">
169
169
  <div class="preview-workspace-topbar">
@@ -175,7 +175,7 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
175
175
  </div>
176
176
  <div class="preview-workspace-body">
177
177
  <div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
178
- ${My}
178
+ ${Lb}
179
179
  </div>
180
180
  </div>
181
181
  </div>`;return`<!DOCTYPE html>
@@ -183,16 +183,16 @@ _Details: ${t.message}_`:r}var oa=n=>({isError:!0,content:[{type:"text",text:n}]
183
183
  <head>
184
184
  <meta charset="UTF-8">
185
185
  <meta name="viewport" content="width=device-width, initial-scale=1">
186
- <link rel="stylesheet" href="${Wl(r)}">
187
- <style id="${Il}">${sg(e)}</style>
186
+ <link rel="stylesheet" href="${Bl(r)}">
187
+ <style id="${Rl}">${lg(t)}</style>
188
188
  </head>
189
189
  <body>
190
- ${t?s:o}
190
+ ${e?s:o}
191
191
  </body>
192
- </html>`}var Ey=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],ky=n=>{var e,t,r,o,s,a,i,d;return!!((t=(e=n==null?void 0:n.features)==null?void 0:e.toolCallDisplay)!=null&&t.activePreview||(o=(r=n==null?void 0:n.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=n==null?void 0:n.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&n.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=n==null?void 0:n.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Ly(n,e,t=[]){return n==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:n==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:n==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:n==="conversation"&&ky(e)?[...Ey(),...t]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...t]}function Py(n,e,t=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:e!=="minimized"},o={...n,launcher:r,suggestionChips:e==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:Ay:n.suggestionChips,initialMessages:Ly(e,n,t),storageAdapter:Cy};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Iy(n,e){var r,o;let t=n.theme?qo(n.theme,{validate:!1}):qo();return{..._t,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function Ms(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Py(Iy(n,e),t,(o=n.appendedMessages)!=null?o:[])}function lg(n){var r,o,s,a,i;let e=(r=n.compareMode)!=null?r:"off",t=(o=n.shellMode)!=null?o:"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Ms(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ms(n,"dark"),shellMode:"dark"}];if(e==="baseline"&&(n.baselineConfig||n.baselineTheme)){let d={...n,config:(s=n.baselineConfig)!=null?s:n.config,theme:(a=n.baselineTheme)!=null?a:n.theme,darkTheme:(i=n.baselineDarkTheme)!=null?i:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Ms(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:Ms(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:Ms(n,t),shellMode:t}]}function cg(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function g(){var L;return(L=t.device)!=null?L:"desktop"}function f(){var L;return(L=t.zoom)!=null?L:i}function u(){var M,z;let L=getComputedStyle(n),F=parseFloat(L.paddingLeft)+parseFloat(L.paddingRight),I=parseFloat(L.paddingTop)+parseFloat(L.paddingBottom),R=40,A=((M=t.compareMode)!=null?M:"off")!=="off",W=(n.clientWidth-F-R)/(A?2:1),D=n.clientHeight-I-R;if(W<=0||D<=0)return 1;let N=(z=xa[g()])!=null?z:xa.desktop;return Math.min(W/N.w,D/N.h,1)}function m(){var I,R,A;i=u();let L=Math.max(rg,Math.min(og,f()));d=L;let F=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let W of F){let D=(I=W.dataset.device)!=null?I:"desktop",N=(R=xa[D])!=null?R:xa.desktop;W.style.width=`${N.w*L}px`,W.style.height=`${N.h*L}px`,D==="mobile"&&(W.style.borderRadius=`${32*L}px`);let M=W.querySelector("iframe");M&&(M.style.width=`${N.w}px`,M.style.height=`${N.h}px`,M.style.transformOrigin="top left",M.style.transition="none",M.style.transform=`scale(${L})`)}(A=t.onScaleChange)==null||A.call(t,L)}function v(){var L;(L=t.onBeforeDestroy)==null||L.call(t);for(let F of r)F.destroy();for(let F of o)F();r=[],o=[]}function x(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function E(){var ve,Be,Oe,Te;if(a)return;v();let L=++c,F=lg(t),I=g(),R=((ve=t.compareMode)!=null?ve:"off")!=="off",A=((Be=t.scene)!=null?Be:"conversation")==="minimized",W=(Oe=t.widgetCssPath)!=null?Oe:"/widget-dist/widget.css",D=(Te=t.buildSrcdoc)!=null?Te:ig,N=I==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",M=we=>`<div class="${N}" data-mount-id="${we.mountId}" data-device="${I}" data-shell-mode="${we.shellMode}">
193
- ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${Wl(we.label)}</span></div>`:""}
192
+ </html>`}var Ib=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Pb=n=>{var t,e,r,o,s,a,i,d;return!!((e=(t=n==null?void 0:n.features)==null?void 0:t.toolCallDisplay)!=null&&e.activePreview||(o=(r=n==null?void 0:n.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=n==null?void 0:n.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&n.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=n==null?void 0:n.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Wb(n,t,e=[]){return n==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:n==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:n==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:n==="conversation"&&Pb(t)?[...Ib(),...e]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...e]}function Rb(n,t,e=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:t!=="minimized"},o={...n,launcher:r,suggestionChips:t==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:Eb:n.suggestionChips,initialMessages:Wb(t,n,e),storageAdapter:Tb};return t==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Bb(n,t){var r,o;let e=n.theme?qo(n.theme,{validate:!1}):qo();return{...zt,...n.config,theme:e,darkTheme:n.darkTheme,colorScheme:(o=t!=null?t:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function Ts(n,t){var r,o;let e=(r=n.scene)!=null?r:"conversation";return Rb(Bb(n,t),e,(o=n.appendedMessages)!=null?o:[])}function pg(n){var r,o,s,a,i;let t=(r=n.compareMode)!=null?r:"off",e=(o=n.shellMode)!=null?o:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Ts(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ts(n,"dark"),shellMode:"dark"}];if(t==="baseline"&&(n.baselineConfig||n.baselineTheme)){let d={...n,config:(s=n.baselineConfig)!=null?s:n.config,theme:(a=n.baselineTheme)!=null?a:n.theme,darkTheme:(i=n.baselineDarkTheme)!=null?i:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Ts(d,e),shellMode:e},{mountId:"preview-current",label:"Current",config:Ts(n,e),shellMode:e}]}return[{mountId:"preview-current",label:"Current",config:Ts(n,e),shellMode:e}]}function ug(n,t){let e={...t},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function g(){var S;return(S=e.device)!=null?S:"desktop"}function f(){var S;return(S=e.zoom)!=null?S:i}function u(){var k,z;let S=getComputedStyle(n),B=parseFloat(S.paddingLeft)+parseFloat(S.paddingRight),I=parseFloat(S.paddingTop)+parseFloat(S.paddingBottom),R=40,A=((k=e.compareMode)!=null?k:"off")!=="off",L=(n.clientWidth-B-R)/(A?2:1),N=n.clientHeight-I-R;if(L<=0||N<=0)return 1;let F=(z=va[g()])!=null?z:va.desktop;return Math.min(L/F.w,N/F.h,1)}function m(){var I,R,A;i=u();let S=Math.max(ag,Math.min(ig,f()));d=S;let B=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let L of B){let N=(I=L.dataset.device)!=null?I:"desktop",F=(R=va[N])!=null?R:va.desktop;L.style.width=`${F.w*S}px`,L.style.height=`${F.h*S}px`,N==="mobile"&&(L.style.borderRadius=`${32*S}px`);let k=L.querySelector("iframe");k&&(k.style.width=`${F.w}px`,k.style.height=`${F.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${S})`)}(A=e.onScaleChange)==null||A.call(e,S)}function v(){var S;(S=e.onBeforeDestroy)==null||S.call(e);for(let B of r)B.destroy();for(let B of o)B();r=[],o=[]}function x(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function E(){var ve,Ne,qe,Te;if(a)return;v();let S=++c,B=pg(e),I=g(),R=((ve=e.compareMode)!=null?ve:"off")!=="off",A=((Ne=e.scene)!=null?Ne:"conversation")==="minimized",L=(qe=e.widgetCssPath)!=null?qe:"/widget-dist/widget.css",N=(Te=e.buildSrcdoc)!=null?Te:dg,F=I==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=we=>`<div class="${F}" data-mount-id="${we.mountId}" data-device="${I}" data-shell-mode="${we.shellMode}">
193
+ ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${Bl(we.label)}</span></div>`:""}
194
194
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${we.mountId}"></iframe>
195
- </div>`,z=R?`<div class="preview-compare-grid">${F.map(we=>`<div class="preview-compare-cell">${M(we)}</div>`).join("")}</div>`:`<div class="preview-single">${M(F[0])}</div>`;t.morphContainer?t.morphContainer(n,z):n.innerHTML=z,m();let j=x(),oe=0,Le=j.length,Ve=()=>{var se,Q,ae,fe,ue;if(a||L!==c)return;for(let K of j){let ie=K.dataset.mountId;if(!ie||!K.contentDocument)continue;let We=F.find(lt=>lt.mountId===ie);if(!We)continue;let te=()=>{},ee=Cn(We.config),re=ee?(()=>{var Y;let lt=(Y=K.contentDocument)==null?void 0:Y.getElementById(`preview-content-${ie}`);if(!lt)return null;let st=ng(lt,We.config),Ee=K.contentDocument.createElement("div");Ee.id=ie,Ee.style.height="100%",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1",Ee.style.minHeight="0",st.host.appendChild(Ee);let he=()=>st.syncWidgetState(it.getState()),Je=te;return te=()=>{st.destroy(),Je()},Ee.__syncDock=he,Ee.__hostLayout=st,Ee})():K.contentDocument.getElementById(ie);if(!re)continue;let it=Ym(re,We.config);if(r.push(it),ee&&re.__syncDock){let lt=re.__syncDock,st=it.on("widget:opened",lt),Ee=it.on("widget:closed",lt),he=te;te=()=>{st(),Ee(),he()},lt()}o.push(te),A&&it.close()}if(((se=t.scene)!=null?se:"conversation")==="artifact"||(fe=(ae=(Q=t.config)==null?void 0:Q.features)==null?void 0:ae.artifacts)!=null&&fe.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
195
+ </div>`,z=R?`<div class="preview-compare-grid">${B.map(we=>`<div class="preview-compare-cell">${k(we)}</div>`).join("")}</div>`:`<div class="preview-single">${k(B[0])}</div>`;e.morphContainer?e.morphContainer(n,z):n.innerHTML=z,m();let j=x(),re=0,Ie=j.length,Ve=()=>{var oe,X,se,fe,pe;if(a||S!==c)return;for(let K of j){let ae=K.dataset.mountId;if(!ae||!K.contentDocument)continue;let Be=B.find(at=>at.mountId===ae);if(!Be)continue;let ee=()=>{},Z=An(Be.config),ne=Z?(()=>{var J;let at=(J=K.contentDocument)==null?void 0:J.getElementById(`preview-content-${ae}`);if(!at)return null;let nt=sg(at,Be.config),Me=K.contentDocument.createElement("div");Me.id=ae,Me.style.height="100%",Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1",Me.style.minHeight="0",nt.host.appendChild(Me);let he=()=>nt.syncWidgetState(st.getState()),Ge=ee;return ee=()=>{nt.destroy(),Ge()},Me.__syncDock=he,Me.__hostLayout=nt,Me})():K.contentDocument.getElementById(ae);if(!ne)continue;let st=tg(ne,Be.config);if(r.push(st),Z&&ne.__syncDock){let at=ne.__syncDock,nt=st.on("widget:opened",at),Me=st.on("widget:closed",at),he=ee;ee=()=>{nt(),Me(),he()},at()}o.push(ee),A&&st.close()}if(((oe=e.scene)!=null?oe:"conversation")==="artifact"||(fe=(se=(X=e.config)==null?void 0:X.features)==null?void 0:se.artifacts)!=null&&fe.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
196
196
 
197
197
  This is a preview of the artifact sidebar.
198
198
 
@@ -200,4 +200,4 @@ This is a preview of the artifact sidebar.
200
200
 
201
201
  - Markdown rendering
202
202
  - Document toolbar
203
- - Resizable panes`});(ue=t.onAfterMount)==null||ue.call(t,{iframes:j,controllers:[...r]})};for(let we of j){let se=we.dataset.mountId;if(!se)continue;let Q=F.find(ae=>ae.mountId===se);Q&&(we.addEventListener("load",()=>{oe++,oe>=Le&&Ve()},{once:!0}),we.srcdoc=D(se,Q.shellMode,Cn(Q.config),W))}Le===0&&Ve()}function k(){var I;if(a)return;let L=lg(t);if(r.length!==L.length){E();return}if(L.some(R=>{let A=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!A||A.dataset.shellMode!==R.shellMode})){E();return}r.forEach((R,A)=>{var W;R.update(L[A].config),((W=t.scene)!=null?W:"conversation")==="minimized"&&R.close()});for(let R of L){let A=n.querySelector(`iframe[data-mount-id="${R.mountId}"]`);A&&ag(A,R.shellMode)}(I=t.onAfterUpdate)==null||I.call(t,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),E(),{update(L){if(a)return;let F=L.device!==void 0&&L.device!==t.device||L.scene!==void 0&&L.scene!==t.scene||L.compareMode!==void 0&&L.compareMode!==t.compareMode||L.widgetCssPath!==void 0&&L.widgetCssPath!==t.widgetCssPath;t={...t,...L},F?E():k()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(L){a||(t={...t,zoom:L},m())}}}0&&(module.exports={createThemePreview});
203
+ - Resizable panes`});(pe=e.onAfterMount)==null||pe.call(e,{iframes:j,controllers:[...r]})};for(let we of j){let oe=we.dataset.mountId;if(!oe)continue;let X=B.find(se=>se.mountId===oe);X&&(we.addEventListener("load",()=>{re++,re>=Ie&&Ve()},{once:!0}),we.srcdoc=N(oe,X.shellMode,An(X.config),L))}Ie===0&&Ve()}function M(){var I;if(a)return;let S=pg(e);if(r.length!==S.length){E();return}if(S.some(R=>{let A=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!A||A.dataset.shellMode!==R.shellMode})){E();return}r.forEach((R,A)=>{var L;R.update(S[A].config),((L=e.scene)!=null?L:"conversation")==="minimized"&&R.close()});for(let R of S){let A=n.querySelector(`iframe[data-mount-id="${R.mountId}"]`);A&&cg(A,R.shellMode)}(I=e.onAfterUpdate)==null||I.call(e,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),E(),{update(S){if(a)return;let B=S.device!==void 0&&S.device!==e.device||S.scene!==void 0&&S.scene!==e.scene||S.compareMode!==void 0&&S.compareMode!==e.compareMode||S.widgetCssPath!==void 0&&S.widgetCssPath!==e.widgetCssPath;e={...e,...S},B?E():M()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(e={...e,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(S){a||(e={...e,zoom:S},m())}}}0&&(module.exports={createThemePreview});