@runtypelabs/persona 4.0.0 → 4.1.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,22 @@
1
- "use strict";var yg=Object.create;var ma=Object.defineProperty;var bg=Object.getOwnPropertyDescriptor;var vg=Object.getOwnPropertyNames;var xg=Object.getPrototypeOf,wg=Object.prototype.hasOwnProperty;var Es=(n,e)=>()=>(n&&(e=n(n=0)),e);var gi=(n,e)=>{for(var t in e)ma(n,t,{get:e[t],enumerable:!0})},Bp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vg(e))!wg.call(n,o)&&o!==t&&ma(n,o,{get:()=>e[o],enumerable:!(r=bg(e,o))||r.enumerable});return n};var Dp=(n,e,t)=>(t=n!=null?yg(xg(n)):{},Bp(e||!n||!n.__esModule?ma(t,"default",{value:n,enumerable:!0}):t,n)),Cg=n=>Bp(ma({},"__esModule",{value:!0}),n);var Op={};gi(Op,{DOMPurify:()=>Fp.default,Marked:()=>Np.Marked});var Np,Fp,_p=Es(()=>{"use strict";Np=require("marked"),Fp=Dp(require("dompurify"),1)});var os,Ii=Es(()=>{"use strict";os=class{constructor(e=24e3,t={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=e;let r=Math.max(0,(o=t.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),t=o,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.pcmToFloat32(t);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let t of e)this.scheduleSamples(t)}scheduleSamples(e){if(e.length===0)return;let t=this.ensureContext(),r=t.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=t.createBufferSource();o.buffer=r,o.connect(t.destination);let s=t.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),r=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Tf(n){return n.replace(/\/+$/,"")}async function Mf(n){var e,t;try{let r=await n.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${n.status}`}: ${r.detail}`:(t=r.error)!=null?t:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var La,Su=Es(()=>{"use strict";Ii();La=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,t;return(t=this.playerPromise)!=null?t:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new os(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,t){let r=++this.generation;this.run(r,e,t)}async run(e,t,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;e===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;e===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${Tf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,m=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!m.ok||!m.body)throw new Error(await Mf(m));let f=m.body.getReader();for(;;){let{done:g,value:u}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(g)break;u&&u.byteLength>0&&d.enqueue(u)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var Pa,Tu=Es(()=>{"use strict";Pa=class{constructor(e,t,r={}){this.primary=e;this.fallback=t;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,t){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=t.onStart)==null||o.call(t)},onEnd:()=>{var o;return(o=t.onEnd)==null?void 0:o.call(t)},onError:o=>{var s,a,i;if(r){(s=t.onError)==null||s.call(t,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,t)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,t,r,o;(t=(e=this.primary).destroy)==null||t.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Mu={};gi(Mu,{FallbackSpeechEngine:()=>Pa,RuntypeSpeechEngine:()=>La});var Eu=Es(()=>{"use strict";Su();Tu()});var Ry={};gi(Ry,{createThemePreview:()=>Zm});module.exports=Cg(Ry);var $p=null,ks=null,Xo=null;var Up=()=>ks?Promise.resolve(ks):Xo||($p?(Xo=$p().then(n=>(ks=n,n)),Xo):(Xo=Promise.resolve().then(()=>(_p(),Op)).then(n=>(ks=n,n)),Xo)),Eo=()=>ks;var Ag=n=>{if(n)return n},fi=n=>{let e=null;return t=>{var o,s;let r=Eo();if(!r)return so(t);if(!e){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;e=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Ag(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},ga=n=>n?fi({markedOptions:n.options,renderer:n.renderer}):fi(),Oy=fi();var so=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Sg={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"]},Tg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Mg=()=>{let n=null;return e=>{let t=Eo();if(!t)return so(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:")&&!Tg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,Sg)}},fa=n=>n===!1?null:typeof n=="function"?n:Mg();var ko="webmcp:",hi=new Map,qp=n=>{var e;hi.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&hi.set(t.name,r)}},yi=n=>hi.get(Kp(n)),ha={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},zp=null;function Vp(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}:${Eg(e.join(""))}`}function jp(n,e){let t=3735928559^e,r=1103547991^e;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);t=Math.imul(t^s,2654435761),r=Math.imul(r^s,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Eg(n){let e=jp(n,0).toString(36),t=jp(n,2654435761).toString(36);return`${e}.${t}`}var ya=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 ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}qp(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=Lg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return mr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return mr(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=Kp(e),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return mr(`Failed to read WebMCP registry: ${x}`)}qp(a);let i=a.find(v=>v.name===s);if(!i)return mr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return mr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let d=yi(s),c={toolName:s,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return mr("User declined the tool call.");if(r!=null&&r.aborted)return mr("Aborted by cancel()");let m=new AbortController,f=!1,g=setTimeout(()=>{f=!0,m.abort()},this.timeoutMs),u=()=>m.abort();r&&(r.aborted?m.abort():r.addEventListener("abort",u,{once:!0}));try{let v=await o.executeTool(i,Rg(t),{signal:m.signal});return Pg(v)}catch(v){if(f)return mr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return mr(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",u)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(zp?await zp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var r;let t=(r=this.confirmHandler)!=null?r:Ig;try{return await t(e)}catch(o){return ha.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=>kg(e,r))}},Kp=n=>n.startsWith(ko)?n.slice(ko.length):n,Jo=n=>n.startsWith(ko),kg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Lg=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Pg=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:Hg(e)}]}},mr=n=>({isError:!0,content:[{type:"text",text:n}]}),Ig=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Wg(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
1
+ "use strict";var wg=Object.create;var ma=Object.defineProperty;var Cg=Object.getOwnPropertyDescriptor;var Ag=Object.getOwnPropertyNames;var Sg=Object.getPrototypeOf,Tg=Object.prototype.hasOwnProperty;var Es=(n,e)=>()=>(n&&(e=n(n=0)),e);var gi=(n,e)=>{for(var t in e)ma(n,t,{get:e[t],enumerable:!0})},Bp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ag(e))!Tg.call(n,o)&&o!==t&&ma(n,o,{get:()=>e[o],enumerable:!(r=Cg(e,o))||r.enumerable});return n};var Dp=(n,e,t)=>(t=n!=null?wg(Sg(n)):{},Bp(e||!n||!n.__esModule?ma(t,"default",{value:n,enumerable:!0}):t,n)),Mg=n=>Bp(ma({},"__esModule",{value:!0}),n);var Op={};gi(Op,{DOMPurify:()=>Fp.default,Marked:()=>Np.Marked});var Np,Fp,_p=Es(()=>{"use strict";Np=require("marked"),Fp=Dp(require("dompurify"),1)});var os,Ii=Es(()=>{"use strict";os=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 Wf(n){return n.replace(/\/+$/,"")}async function Rf(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 La,ku=Es(()=>{"use strict";Ii();La=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,t;return(t=this.playerPromise)!=null?t:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new os(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,t){let r=++this.generation;this.run(r,e,t)}async run(e,t,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;e===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;e===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${Wf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,m=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!m.ok||!m.body)throw new Error(await Rf(m));let f=m.body.getReader();for(;;){let{done:g,value:u}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(g)break;u&&u.byteLength>0&&d.enqueue(u)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var Pa,Lu=Es(()=>{"use strict";Pa=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 Pu={};gi(Pu,{FallbackSpeechEngine:()=>Pa,RuntypeSpeechEngine:()=>La});var Iu=Es(()=>{"use strict";ku();Lu()});var _y={};gi(_y,{createThemePreview:()=>rg});module.exports=Mg(_y);var $p=null,ks=null,Xo=null;var Up=()=>ks?Promise.resolve(ks):Xo||($p?(Xo=$p().then(n=>(ks=n,n)),Xo):(Xo=Promise.resolve().then(()=>(_p(),Op)).then(n=>(ks=n,n)),Xo)),Eo=()=>ks;var Eg=n=>{if(n)return n},fi=n=>{let e=null;return t=>{var o,s;let r=Eo();if(!r)return so(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=Eg(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},ga=n=>n?fi({markedOptions:n.options,renderer:n.renderer}):fi(),Vy=fi();var so=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var kg={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Lg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pg=()=>{let n=null;return e=>{let t=Eo();if(!t)return so(e);if(!n){let{DOMPurify:r}=t;n=r(typeof window!="undefined"?window:void 0),n.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Lg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,kg)}},fa=n=>n===!1?null:typeof n=="function"?n:Pg();var qp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,zp=n=>n.includes("|"),jp=n=>{let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())},Ig=n=>`| ${n.join(" | ")} |`,Wg=n=>`| ${Array.from({length:n},()=>"---").join(" | ")} |`,Rg=(n,e)=>n.length>=e?n.slice(0,e):n.concat(Array.from({length:e-n.length},()=>"")),Vp=n=>{if(!n||!n.includes("|"))return n;let e=n.split(`
2
+ `),t=!1;for(let r=0;r<e.length-1;r++){let o=e[r],s=e[r+1];if(!zp(o)||qp.test(o)||!qp.test(s))continue;let a=jp(o).length;if(a<1)continue;let i=Wg(a);e[r+1]!==i&&(e[r+1]=i,t=!0);let d=r+2;for(;d<e.length;d++){let c=e[d];if(c.trim()===""||!zp(c))break;let m=Ig(Rg(jp(c),a));e[d]!==m&&(e[d]=m,t=!0)}r=d-1}return t?e.join(`
3
+ `):n};var ko="webmcp:",hi=new Map,Kp=n=>{var e;hi.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&hi.set(t.name,r)}},yi=n=>hi.get(Jp(n)),ha={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},Gp=null;function Xp(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}:${Hg(e.join(""))}`}function Qp(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 Hg(n){let e=Qp(n,0).toString(36),t=Qp(n,2654435761).toString(36);return`${e}.${t}`}var ya=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 ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Kp(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=Dg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return mr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return mr(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=Jp(e),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return mr(`Failed to read WebMCP registry: ${x}`)}Kp(a);let i=a.find(v=>v.name===s);if(!i)return mr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return mr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let d=yi(s),c={toolName:s,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return mr("User declined the tool call.");if(r!=null&&r.aborted)return mr("Aborted by cancel()");let m=new AbortController,f=!1,g=setTimeout(()=>{f=!0,m.abort()},this.timeoutMs),u=()=>m.abort();r&&(r.aborted?m.abort():r.addEventListener("abort",u,{once:!0}));try{let v=await o.executeTool(i,_g(t),{signal:m.signal});return Ng(v)}catch(v){if(f)return mr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return mr(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",u)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Gp?await Gp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var r;let t=(r=this.confirmHandler)!=null?r:Fg;try{return await t(e)}catch(o){return ha.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=>Bg(e,r))}},Jp=n=>n.startsWith(ko)?n.slice(ko.length):n,Jo=n=>n.startsWith(ko),Bg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Dg=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Ng=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:$g(e)}]}},mr=n=>({isError:!0,content:[{type:"text",text:n}]}),Fg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Og(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
2
4
 
3
5
  Arguments:
4
6
  ${e}`:"")+(n.description?`
5
7
 
6
- ${n.description}`:"");return window.confirm(t)},Wg=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)}},Rg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Hg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var ao=require("partial-json");var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Lr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(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},Ls=(...n)=>n.filter(Boolean).join(" ");var bi="ask_user_question",Ps=8,Yo="data-persona-ask-sheet-for",Bg="Other",Dg="Other\u2026",Qp="Type your own answer here",Xp="Send",Ng="Next",Fg="Back",Og="Submit all",_g="Skip",$g=3,vi="data-ask-current-index",xi="data-ask-question-count",Jp="data-ask-answers",wi="data-ask-grouped",Yp="data-ask-layout",Ug=n=>n.layout==="pills"?"pills":"rows",qg=n=>n.getAttribute(Yp)==="pills"?"pills":"rows",Gp=!1,Zp=n=>n.replace(/["\\]/g,"\\$&"),Lo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===bi,Ci=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},Zo=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,ao.parse)(o,ao.STR|ao.OBJ|ao.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Is=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>Ps&&!Gp&&(Gp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ps}.`)),e.slice(0,Ps)},zg=n=>{var e;return(e=Is(n)[0])!=null?e:null},jg=(n,e)=>{var t;return(t=Is(n)[e])!=null?t:null},Vg=(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))},eu=(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},Kg=(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=eu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Gg=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},Qg=(n,e,t,r)=>{var m,f,g;let s=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!t){for(let u=0;u<$g;u++)s.appendChild(Gg(r));return s}if(d.forEach((u,v)=>{s.appendChild(Kg(u,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let u=r==="rows"?Bg:Dg;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"),I=document.createElement("input");I.type="text",I.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",I.placeholder=(m=e.freeTextPlaceholder)!=null?m:Qp,I.setAttribute("data-ask-free-text-input","true"),I.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:u),x.appendChild(I),v.appendChild(x);let M=eu(r,a,d.length);M&&v.appendChild(M),s.appendChild(v)}else{let v=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=e.freeTextLabel)!=null?g:u,s.appendChild(v)}}return s},tu=(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:Qp,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:Xp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Xg=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:Xp,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Jg=(n,e,t)=>{var c,m,f,g;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Fg,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(m=t.skipLabel)!=null?m:_g,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:Og:(g=t.nextLabel)!=null?g:Ng,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Po=n=>{let e=n.getAttribute(Jp);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},nu=(n,e)=>{n.setAttribute(Jp,JSON.stringify(e))},sr=n=>{var t;let e=Number((t=n.getAttribute(vi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Yg=(n,e)=>{n.setAttribute(vi,String(Math.max(0,Math.floor(e))))},es=n=>{var t;let e=Number((t=n.getAttribute(xi))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},io=n=>n.getAttribute(wi)==="true",Zg=(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},ef=(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)))},ba=(n,e)=>{let{payload:t}=Zo(e),r=Is(t),o=Po(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},ru=n=>{let e=Po(n),t=sr(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",m=o.has(c);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},ou=n=>{if(!io(n))return;let e=Po(n),t=sr(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}},Ai=(n,e,t)=>{let r=Ci(t),o=qg(n),{payload:s,complete:a}=Zo(e),i=io(n),d=sr(n),c=es(n),m=i?jg(s,d):zg(s),f=!!(m!=null&&m.multiSelect),g=n.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let u=n.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let E=typeof(m==null?void 0:m.question)=="string"?m.question:"";v.textContent=E,v.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let E=Qg(m,r,a,o);x.replaceWith(E)}if(o!=="rows"){let E=n.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(tu(r,o))}let I=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!I?n.appendChild(Xg(r)):(!f||i)&&I&&I.remove(),n.setAttribute("data-multi-select",f?"true":"false");let M=n.querySelector('[data-ask-nav-row="true"]');if(i){let E=Jg(d,c,r);M?M.replaceWith(E):n.appendChild(E)}else M&&M.remove();ru(n),ou(n)},tf=(n,e,t)=>{let r=Ci(e),o=Ug(r),s=n.toolCall.id,a=Is(t),i=Math.max(1,a.length),d=i>1,c=Zg(n,a),m=d?ef(n,i):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Yo,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(xi,String(i)),f.setAttribute(vi,String(m)),f.setAttribute(wi,d?"true":"false"),f.setAttribute(Yp,o),nu(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`),Vg(f,r);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),f.appendChild(g);let I=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 I.setAttribute("data-ask-pill-list","true"),I.setAttribute("role","group"),f.appendChild(I),o!=="rows"&&f.appendChild(tu(r,o)),Ai(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},nf=(n,e,t)=>{let{payload:r}=Zo(e),o=Math.max(1,Is(r).length);o>es(n)&&(n.setAttribute(xi,String(o)),o>1&&!io(n)&&n.setAttribute(wi,"true")),Ai(n,e,t)};var va=(n,e,t)=>{if(!t||!Lo(n)||Ci(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${Yo}]`).forEach(c=>{c.getAttribute(Yo)!==o&&c.remove()});let a=t.querySelector(`[${Yo}="${Zp(o)}"]`);if(a){nf(a,n,e);return}let{payload:i}=Zo(n),d=tf(n,e,i);t.appendChild(d)},ts=(n,e)=>{if(!n)return;let t=e?`[${Yo}="${Zp(e)}"]`:`[${Yo}]`;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)})},Si=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),lo=(n,e)=>{let t=Po(n),r=sr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,nu(n,t),ru(n),ou(n)},xa=(n,e,t,r)=>{let o=es(n),s=Math.max(0,Math.min(o-1,r));Yg(n,s),Ai(n,e,t)};var $r="suggest_replies";var rf={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},su={name:$r,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:rf,origin:"sdk",annotations:{readOnlyHint:!0}},Ti=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Mi=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===$r},of=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},au=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Mi(r))continue;let o=of((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},iu=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 sf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ps,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},af={name:bi,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:sf,origin:"sdk",annotations:{readOnlyHint:!0}},Ei=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(af),iu(n)&&e.push(su),e};var ns=require("partial-json"),lu=n=>n.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),rs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},lf=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},cu=n=>n.status==="complete"?lf(n):n.status==="pending"?"Waiting":"",cf=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var du=n=>n.status==="complete"?cf(n):"Using tool...",wa=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Rs=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 wa(e)},Ca=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 wa(e)},ki=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Rs(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Aa=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Ws(r,t.slice(s,a.index),[]),a[1]!==void 0?Ws(r,a[1],["bold"]):a[2]!==void 0?Ws(r,a[2],["italic"]):a[3]!==void 0&&Ws(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Ws(r,t.slice(s),[]),r},Ws=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},df=()=>{let n=null,e=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${n.description}`:"");return window.confirm(t)},Og=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)}},_g=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},$g=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var ao=require("partial-json");var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Lr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(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},Ls=(...n)=>n.filter(Boolean).join(" ");var bi="ask_user_question",Ps=8,Yo="data-persona-ask-sheet-for",Ug="Other",qg="Other\u2026",Zp="Type your own answer here",eu="Send",zg="Next",jg="Back",Vg="Submit all",Kg="Skip",Gg=3,vi="data-ask-current-index",xi="data-ask-question-count",tu="data-ask-answers",wi="data-ask-grouped",nu="data-ask-layout",Qg=n=>n.layout==="pills"?"pills":"rows",Xg=n=>n.getAttribute(nu)==="pills"?"pills":"rows",Yp=!1,ru=n=>n.replace(/["\\]/g,"\\$&"),Lo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===bi,Ci=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},Zo=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,ao.parse)(o,ao.STR|ao.OBJ|ao.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Is=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>Ps&&!Yp&&(Yp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ps}.`)),e.slice(0,Ps)},Jg=n=>{var e;return(e=Is(n)[0])!=null?e:null},Yg=(n,e)=>{var t;return(t=Is(n)[e])!=null?t:null},Zg=(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))},ou=(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},ef=(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=ou(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},tf=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},nf=(n,e,t,r)=>{var m,f,g;let s=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!t){for(let u=0;u<Gg;u++)s.appendChild(tf(r));return s}if(d.forEach((u,v)=>{s.appendChild(ef(u,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let u=r==="rows"?Ug:qg;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"),I=document.createElement("input");I.type="text",I.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",I.placeholder=(m=e.freeTextPlaceholder)!=null?m:Zp,I.setAttribute("data-ask-free-text-input","true"),I.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:u),x.appendChild(I),v.appendChild(x);let M=ou(r,a,d.length);M&&v.appendChild(M),s.appendChild(v)}else{let v=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=e.freeTextLabel)!=null?g:u,s.appendChild(v)}}return s},su=(n,e)=>{var s,a;let r=b("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:Zp,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:eu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},rf=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:eu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},of=(n,e,t)=>{var c,m,f,g;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:jg,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(m=t.skipLabel)!=null?m:Kg,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:Vg:(g=t.nextLabel)!=null?g:zg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Po=n=>{let e=n.getAttribute(tu);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},au=(n,e)=>{n.setAttribute(tu,JSON.stringify(e))},sr=n=>{var t;let e=Number((t=n.getAttribute(vi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},sf=(n,e)=>{n.setAttribute(vi,String(Math.max(0,Math.floor(e))))},es=n=>{var t;let e=Number((t=n.getAttribute(xi))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},io=n=>n.getAttribute(wi)==="true",af=(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},lf=(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)))},ba=(n,e)=>{let{payload:t}=Zo(e),r=Is(t),o=Po(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},iu=n=>{let e=Po(n),t=sr(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",m=o.has(c);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},lu=n=>{if(!io(n))return;let e=Po(n),t=sr(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}},Ai=(n,e,t)=>{let r=Ci(t),o=Xg(n),{payload:s,complete:a}=Zo(e),i=io(n),d=sr(n),c=es(n),m=i?Yg(s,d):Jg(s),f=!!(m!=null&&m.multiSelect),g=n.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let u=n.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let E=typeof(m==null?void 0:m.question)=="string"?m.question:"";v.textContent=E,v.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let E=nf(m,r,a,o);x.replaceWith(E)}if(o!=="rows"){let E=n.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(su(r,o))}let I=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!I?n.appendChild(rf(r)):(!f||i)&&I&&I.remove(),n.setAttribute("data-multi-select",f?"true":"false");let M=n.querySelector('[data-ask-nav-row="true"]');if(i){let E=of(d,c,r);M?M.replaceWith(E):n.appendChild(E)}else M&&M.remove();iu(n),lu(n)},cf=(n,e,t)=>{let r=Ci(e),o=Qg(r),s=n.toolCall.id,a=Is(t),i=Math.max(1,a.length),d=i>1,c=af(n,a),m=d?lf(n,i):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Yo,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(xi,String(i)),f.setAttribute(vi,String(m)),f.setAttribute(wi,d?"true":"false"),f.setAttribute(nu,o),au(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`),Zg(f,r);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),f.appendChild(g);let I=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 I.setAttribute("data-ask-pill-list","true"),I.setAttribute("role","group"),f.appendChild(I),o!=="rows"&&f.appendChild(su(r,o)),Ai(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},df=(n,e,t)=>{let{payload:r}=Zo(e),o=Math.max(1,Is(r).length);o>es(n)&&(n.setAttribute(xi,String(o)),o>1&&!io(n)&&n.setAttribute(wi,"true")),Ai(n,e,t)};var va=(n,e,t)=>{if(!t||!Lo(n)||Ci(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${Yo}]`).forEach(c=>{c.getAttribute(Yo)!==o&&c.remove()});let a=t.querySelector(`[${Yo}="${ru(o)}"]`);if(a){df(a,n,e);return}let{payload:i}=Zo(n),d=cf(n,e,i);t.appendChild(d)},ts=(n,e)=>{if(!n)return;let t=e?`[${Yo}="${ru(e)}"]`:`[${Yo}]`;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)})},Si=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),lo=(n,e)=>{let t=Po(n),r=sr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,au(n,t),iu(n),lu(n)},xa=(n,e,t,r)=>{let o=es(n),s=Math.max(0,Math.min(o-1,r));sf(n,s),Ai(n,e,t)};var $r="suggest_replies";var pf={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},cu={name:$r,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:pf,origin:"sdk",annotations:{readOnlyHint:!0}},Ti=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Mi=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===$r},uf=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},du=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Mi(r))continue;let o=uf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},pu=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 mf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ps,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},gf={name:bi,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:mf,origin:"sdk",annotations:{readOnlyHint:!0}},Ei=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(gf),pu(n)&&e.push(cu),e};var ns=require("partial-json"),uu=n=>n.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),rs=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)}},ff=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`},mu=n=>n.status==="complete"?ff(n):n.status==="pending"?"Waiting":"",hf=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 gu=n=>n.status==="complete"?hf(n):"Using tool...",wa=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Rs=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 wa(e)},Ca=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 wa(e)},ki=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Rs(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Aa=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Ws(r,t.slice(s,a.index),[]),a[1]!==void 0?Ws(r,a[1],["bold"]):a[2]!==void 0?Ws(r,a[2],["italic"]):a[3]!==void 0&&Ws(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Ws(r,t.slice(s),[]),r},Ws=(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})},yf=()=>{let n=null,e=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
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()=>{}}},Hs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},pu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},uu=()=>{var e;let n=df();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},mu=()=>{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,ns.parse)(t,ns.STR|ns.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?lu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=lu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var gu=()=>{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 fu="4.0.0";var Bs=fu;var uf="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function mf(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Li=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function gf(n){switch(n){case"json":return mu;case"regex-json":return uu;case"xml":return gu;default:return pu}}var hu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function ff(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=hu(t);if(!hu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Hs(n);return Hs(e)!==null&&a===null?e:n}var Ds=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;this.apiUrl=(t=e.apiUrl)!=null?t:uf,this.headers={"Content-Type":"application/json","X-Persona-Version":Bs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:gf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new ya(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$/,""))||Sa}/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":Bs},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$/,""))||Sa}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Bs},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 L=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:L}),L}let c=await this.buildPayload(e.messages),m=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Li).map(L=>{var R,A,W;return{id:L.id,role:L.role,content:(W=(A=(R=L.contentParts)!=null?R:L.llmContent)!=null?A:L.rawContent)!=null?W:L.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,u=!!(g&&g.length>0),v=u?Vp(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,I=u&&x&&this.lastSentClientToolsFingerprint===v,M=!1,E=null,F;for(let L=0;;L++){let A={...f,...u&&(M||!I)&&g?{clientTools:g}:{},...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":Bs},body:JSON.stringify(A),signal:r.signal}),F.status===409&&L===0&&u){let W=await F.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}E=W!=null?W:{error:"Chat request failed"}}break}if(!F.ok){let L=E!=null?E: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(L.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let R=new Error(L.error||"Failed to send message");throw t({type:"error",error:R}),R}if(!F.body){let L=new Error("No response body received");throw t({type:"error",error:L}),L}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$/,""))||Sa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,m;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Sa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(m=r==null?void 0:r.streamResponse)!=null?m:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(Li).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ei(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(Li).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ei(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=m=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return r.current=f,o(f),f},c=m=>r.current?r.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=c(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,o(m)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r){var rn,hr,hn,Ve;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,m=T=>{let ue=T.reasoning?{...T.reasoning,chunks:[...T.reasoning.chunks]}:void 0,Le=T.toolCall?{...T.toolCall,chunks:T.toolCall.chunks?[...T.toolCall.chunks]:void 0}:void 0,Me=T.tools?T.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...T,reasoning:ue,toolCall:Le,tools:Me}},f=T=>{if(T.role!=="assistant"||T.variant)return!0;let ue=Array.isArray(T.contentParts)&&T.contentParts.length>0,Le=typeof T.rawContent=="string"&&T.rawContent.trim()!=="";return typeof T.content=="string"&&T.content.trim()!==""||ue||Le||!!T.stopReason},g=T=>{f(T)&&t({type:"message",message:m(T)})},u=null,v=null,x={current:null},I={current:null},M=null,E="",F=new Map,L=new Map,R=new Map,A=new Map,W=new Map,N={lastId:null,byStep:new Map},D={lastId:null,byCall:new Map},k=T=>{if(T==null)return null;try{return String(T)}catch{return null}},j=T=>{var ue,Le,Me,He,Ze;return k((Ze=(He=(Me=(Le=(ue=T.stepId)!=null?ue:T.step_id)!=null?Le:T.step)!=null?Me:T.parentId)!=null?He:T.flowStepId)!=null?Ze:T.flow_step_id)},V=T=>{var ue,Le,Me,He,Ze,Ge,ut;return k((ut=(Ge=(Ze=(He=(Me=(Le=(ue=T.callId)!=null?ue:T.call_id)!=null?Le:T.requestId)!=null?Me:T.request_id)!=null?He:T.toolCallId)!=null?Ze:T.tool_call_id)!=null?Ge:T.stepId)!=null?ut:T.step_id)},ne=r,Re=!1,Ue=()=>{if(u)return u;let T,ue=M;return!Re&&ne?(T=ne,Re=!0):ne&&ue?T=`${ne}_${ue}`:T=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:T,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(u),u},xe=(T,ue)=>{N.lastId=ue,T&&N.byStep.set(T,ue)},Ie=(T,ue)=>{var Ze;let Le=(Ze=T.reasoningId)!=null?Ze:T.id,Me=j(T);if(Le){let Ge=String(Le);return xe(Me,Ge),Ge}if(Me){let Ge=N.byStep.get(Me);if(Ge)return N.lastId=Ge,Ge}if(N.lastId&&!ue)return N.lastId;if(!ue)return null;let He=`reason-${c()}`;return xe(Me,He),He},_e=T=>{let ue=A.get(T);if(ue)return ue;let Le={id:`reason-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"streaming",chunks:[]}};return A.set(T,Le),g(Le),Le},Se=(T,ue)=>{D.lastId=ue,T&&D.byCall.set(T,ue)},ve=new Set,re=new Map,X=new Set,ie=new Map,he=T=>{if(!T)return!1;let ue=T.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},oe=(T,ue)=>{var Ze;let Le=(Ze=T.toolId)!=null?Ze:T.id,Me=V(T);if(Le){let Ge=String(Le);return Se(Me,Ge),Ge}if(Me){let Ge=D.byCall.get(Me);if(Ge)return D.lastId=Ge,Ge}if(D.lastId&&!ue)return D.lastId;if(!ue)return null;let He=`tool-${c()}`;return Se(Me,He),He},K=T=>{let ue=W.get(T);if(ue)return ue;let Le={id:`tool-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:T,status:"pending"}};return W.set(T,Le),g(Le),Le},te=T=>{if(typeof T=="number"&&Number.isFinite(T))return T;if(typeof T=="string"){let ue=Number(T);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Le=Date.parse(T);if(!Number.isNaN(Le))return Le}return Date.now()},qe=T=>{if(typeof T=="string")return T;if(T==null)return"";try{return JSON.stringify(T)}catch{return String(T)}},Y=new Map,le=new Map,Pe=new Map,it=(T,ue,Le)=>{var ut;let Me=Pe.get(T);Me||(Me=[],Pe.set(T,Me));let He=0,Ze=Me.length;for(;He<Ze;){let Wt=He+Ze>>>1;Me[Wt].seq<ue?He=Wt+1:Ze=Wt}((ut=Me[He])==null?void 0:ut.seq)===ue?Me[He]={seq:ue,text:Le}:Me.splice(He,0,{seq:ue,text:Le});let Ge="";for(let Wt=0;Wt<Me.length;Wt++)Ge+=Me[Wt].text;return Ge},lt=(T,ue)=>{let Le=qe(ue),Me=le.get(T.id),He=ff(Me,Le);T.rawContent=He;let Ze=Y.get(T.id),Ge=G=>{var ke;let de=(ke=T.content)!=null?ke:"";G.trim()!==""&&(de.trim().length===0||G.startsWith(de)||G.trimStart().startsWith(de.trim()))&&(T.content=G)},ut=()=>{var G;if(Ze){let de=(G=Ze.close)==null?void 0:G.call(Ze);de instanceof Promise&&de.catch(()=>{})}Y.delete(T.id),le.delete(T.id),T.streaming=!1,g(T)};if(!Ze){Ge(Le),ut();return}let Wt=Hs(He);if(Wt!==null&&Wt.trim()!==""){Ge(Wt),ut();return}let q=G=>{var vt;let de=typeof G=="string"?G:(vt=G==null?void 0:G.text)!=null?vt:null;if(de!==null&&de.trim()!=="")return de;let ke=Ze.getExtractedText();return ke!==null&&ke.trim()!==""?ke:Le},ot;try{ot=Ze.processChunk(He)}catch{Ge(Le),ut();return}if(ot instanceof Promise){ot.then(G=>{Ge(q(G)),ut()}).catch(()=>{Ge(Le),ut()});return}Ge(q(ot)),ut()},rt=null,Ee=(T,ue,Le,Me)=>{var Wt;T.rawContent=ue,Y.has(T.id)||Y.set(T.id,this.createStreamParser());let He=Y.get(T.id),Ze=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(Ze&&le.set(T.id,ue),He.__isPlainTextParser===!0){T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T);return}let ut=He.processChunk(ue);if(ut instanceof Promise)ut.then(q=>{var G;let ot=typeof q=="string"?q:(G=q==null?void 0:q.text)!=null?G:null;ot!==null&&ot.trim()!==""?(T.content=ot,g(T)):!Ze&&!ue.trim().startsWith("<")&&(T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T))}).catch(()=>{T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T)});else{let q=typeof ut=="string"?ut:(Wt=ut==null?void 0:ut.text)!=null?Wt:null;q!==null&&q.trim()!==""?(T.content=q,g(T)):!Ze&&!ue.trim().startsWith("<")&&(T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T))}},pe=(T,ue)=>{var Wt,q;let Le=ue!=null?ue:T.content;if(Le==null||Le===""){T.streaming=!1,g(T);return}let Me=le.get(T.id),He=Me!=null?Me:qe(Le);T.rawContent=He;let Ze=Y.get(T.id),Ge=null,ut=!1;if(Ze&&(Ge=Ze.getExtractedText(),Ge===null&&(Ge=Hs(He)),Ge===null)){let ot=Ze.processChunk(He);ot instanceof Promise?(ut=!0,ot.then(G=>{var ke;let de=typeof G=="string"?G:(ke=G==null?void 0:G.text)!=null?ke:null;de!==null&&(T.content=de,T.streaming=!1,Y.delete(T.id),le.delete(T.id),g(T))}).catch(()=>{})):Ge=typeof ot=="string"?ot:(Wt=ot==null?void 0:ot.text)!=null?Wt:null}if(!ut){Ge!==null&&Ge.trim()!==""?T.content=Ge:le.has(T.id)||(T.content=qe(Le));let ot=Y.get(T.id);if(ot){let G=(q=ot.close)==null?void 0:q.call(ot);G instanceof Promise&&G.catch(()=>{}),Y.delete(T.id)}le.delete(T.id),T.streaming=!1,g(T)}},Xe=(T,ue,Le)=>{let Me=L.get(T);if(Me)return Me;let He={id:`nested-${ue}-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Le?{variant:Le}:{},...Le==="reasoning"?{reasoning:{id:T,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return L.set(T,He),g(He),He},J=[],ce,we=new Map,je=0,Pt="agent",Te=null,me=null,fn=new Map,It=(rn=this.config.iterationDisplay)!=null?rn:"separate";for(ce=()=>{var T,ue,Le,Me,He,Ze,Ge,ut,Wt,q,ot,G,de,ke,vt,Yt,Zt,pn,Ht,et,Rt,ct,Kt,Jn,An,en,In,yr,xt,Nn,br,Pr,ir,yt,uo,vr,mo,Wn,No,jr,Ir,Vr,Kr,go,fo,Gr,Ct,Fn,On,Sn,St,Yn,Zn,_n,Qr,Wr,Xr,$n,Bt,Tn,er,Jr,Rr,Yr,xr,Un,ye,dt,Qt,on,wr,fs,Hr,ho,Cr,_,Fo,Ar,Sr,Br,Tr,lr,Oo,ra,qn,zn,cr,dr,yo,Dr,yn,Mr,_o,bo,$o,oa,Uo,sa,qo,ht,hs,tr,Rn,aa,ia;for(let Zr=0;Zr<J.length;Zr++){let tt=J[Zr].payloadType,w=J[Zr].payload;if(tt==="reasoning_start"){let U=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(U&&$){F.set(U,$),Xe(U,$,"reasoning");continue}let Q=(T=Ie(w,!0))!=null?T:`reason-${c()}`,fe=_e(Q);fe.reasoning=(ue=fe.reasoning)!=null?ue:{id:Q,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Me=fe.reasoning.startedAt)!=null?Me:te((Le=w.startedAt)!=null?Le:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(tt==="reasoning_delta"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)&&L.has(U)){let Oe=L.get(U),Je=(Ge=(Ze=(He=w.reasoningText)!=null?He:w.text)!=null?Ze:w.delta)!=null?Ge:"";Je&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(Je)),g(Oe));continue}let $=(Wt=(ut=Ie(w,!1))!=null?ut:Ie(w,!0))!=null?Wt:`reason-${c()}`,Q=_e($);Q.reasoning=(q=Q.reasoning)!=null?q:{id:$,status:"streaming",chunks:[]},Q.reasoning.startedAt=(G=Q.reasoning.startedAt)!=null?G:te((ot=w.startedAt)!=null?ot:w.timestamp);let fe=(vt=(ke=(de=w.reasoningText)!=null?de:w.text)!=null?ke:w.delta)!=null?vt:"";if(fe&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let Je=it($,Oe,String(fe));Q.reasoning.chunks=[Je]}else Q.reasoning.chunks.push(String(fe))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=te((Yt=w.completedAt)!=null?Yt:w.timestamp);let Oe=(Zt=Q.reasoning.startedAt)!=null?Zt:Date.now();Q.reasoning.durationMs=Math.max(0,((pn=Q.reasoning.completedAt)!=null?pn:Date.now())-Oe)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(tt==="reasoning_complete"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)&&L.has(U)){let Je=L.get(U);if(Je.reasoning){let Et=typeof w.text=="string"?w.text:"";Et&&Je.reasoning.chunks.length===0&&Je.reasoning.chunks.push(Et),Je.reasoning.status="complete",Je.streaming=!1,g(Je)}F.delete(U),L.delete(U);continue}let $=(et=(Ht=Ie(w,!1))!=null?Ht:Ie(w,!0))!=null?et:`reason-${c()}`,Q=typeof w.text=="string"?w.text:"";!A.get($)&&(Q||w.scope==="loop")&&_e($);let fe=A.get($);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),Q&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(Q),fe.reasoning.status="complete",fe.reasoning.completedAt=te((Rt=w.completedAt)!=null?Rt:w.timestamp);let Je=(ct=fe.reasoning.startedAt)!=null?ct:Date.now();fe.reasoning.durationMs=Math.max(0,((Kt=fe.reasoning.completedAt)!=null?Kt:Date.now())-Je),fe.streaming=!1,g(fe)}let Oe=j(w);Oe&&N.byStep.delete(Oe)}else if(tt==="tool_start"){u&&(u.streaming=!1,g(u),u=null),typeof w.iteration=="number"&&(je=w.iteration);let U=(An=(Jn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Jn:oe(w,!0))!=null?An:`tool-${c()}`,$=(en=w.toolName)!=null?en:w.name;if(he($)){ve.add(U);continue}Se(V(w),U);let Q=K(U),fe=(In=Q.toolCall)!=null?In:{id:U,status:"pending"};fe.name=$!=null?$:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(xt=fe.startedAt)!=null?xt:te((yr=w.startedAt)!=null?yr:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,Q.toolCall=fe,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(Q)}else if(tt==="tool_output_delta"){let U=(br=(Nn=oe(w,!1))!=null?Nn:oe(w,!0))!=null?br:`tool-${c()}`;if(ve.has(U))continue;let $=K(U),Q=(Pr=$.toolCall)!=null?Pr:{id:U,status:"running"};Q.startedAt=(yt=Q.startedAt)!=null?yt:te((ir=w.startedAt)!=null?ir:w.timestamp);let fe=(mo=(vr=(uo=w.text)!=null?uo:w.delta)!=null?vr:w.message)!=null?mo:"";fe&&(Q.chunks=(Wn=Q.chunks)!=null?Wn:[],Q.chunks.push(String(fe))),Q.status="running",$.toolCall=Q,$.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&($.agentMetadata=(Ir=$.agentMetadata)!=null?Ir:{executionId:(No=Oe==null?void 0:Oe.executionId)!=null?No:w.executionId,iteration:(jr=Oe==null?void 0:Oe.iteration)!=null?jr:w.iteration}),g($)}else if(tt==="tool_complete"){let U=(Kr=(Vr=oe(w,!1))!=null?Vr:oe(w,!0))!=null?Kr:`tool-${c()}`;if(ve.has(U)){ve.delete(U);continue}let $=K(U),Q=(go=$.toolCall)!=null?go:{id:U,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=te((fo=w.completedAt)!=null?fo:w.timestamp);let fe=(Gr=w.duration)!=null?Gr:w.executionTime;if(typeof fe=="number")Q.durationMs=fe;else{let Et=(Ct=Q.startedAt)!=null?Ct:Date.now();Q.durationMs=Math.max(0,((Fn=Q.completedAt)!=null?Fn:Date.now())-Et)}$.toolCall=Q,$.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&($.agentMetadata=(St=$.agentMetadata)!=null?St:{executionId:(On=Oe==null?void 0:Oe.executionId)!=null?On:w.executionId,iteration:(Sn=Oe==null?void 0:Oe.iteration)!=null?Sn:w.iteration}),g($);let Je=V(w);Je&&D.byCall.delete(Je)}else if(tt==="await"&&w.toolName){let U=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,$=(Yn=U!=null?U:w.toolId)!=null?Yn:`local-${c()}`,Q=K($),fe=w.toolName,Oe=w.origin==="webmcp"&&!Jo(fe)?`webmcp:${fe}`:fe,Je=Jo(Oe),Et=(Zn=Q.toolCall)!=null?Zn:{id:$,status:"pending"};Et.name=Oe,Et.args=w.parameters,Et.status=Je?"running":"complete",Et.chunks=(_n=Et.chunks)!=null?_n:[],Et.startedAt=(Xr=Et.startedAt)!=null?Xr:te((Wr=(Qr=w.startedAt)!=null?Qr:w.timestamp)!=null?Wr:w.awaitedAt),Je?(Et.completedAt=void 0,Et.duration=void 0,Et.durationMs=void 0):Et.completedAt=($n=Et.completedAt)!=null?$n:Et.startedAt,Q.toolCall=Et,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Tn=w.executionId)!=null?Tn:(Bt=Q.agentMetadata)==null?void 0:Bt.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(Q)}else if(tt==="text_start"){let U=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(U&&$){F.set(U,$);continue}let Q=u;Q&&(Pt==="flow"?(pe(Q),rt=Q):(Q.streaming=!1,g(Q)),u=null),M=typeof w.id=="string"?w.id:M,E=""}else if(tt==="text_delta"){let U=typeof w.id=="string"?w.id:null,$=U?F.get(U):void 0;if(U&&$){let fe=typeof w.delta=="string"?w.delta:"",Oe=((er=R.get(U))!=null?er:"")+fe;if(R.set(U,Oe),Oe.trim()==="")continue;let Je=Xe(U,$);Je.agentMetadata={...Je.agentMetadata,executionId:w.executionId,parentToolId:$},Ee(Je,Oe,fe,void 0);continue}if(M=typeof w.id=="string"?w.id:M,Pt==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(E+=fe,E.trim()==="")continue;let Oe=Ue();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ee(Oe,E,fe,void 0),v=Oe;continue}let Q=Ue();Q.content+=(Jr=w.delta)!=null?Jr:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Te!=null?Te:void 0,agentName:me==null?void 0:me.agentName},v=Q,g(Q)}else if(tt==="text_complete"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)){let Q=L.get(U);Q&&pe(Q),F.delete(U),R.delete(U),L.delete(U);continue}let $=u;$&&(Pt==="flow"?(pe($),rt=$):(((Rr=$.content)!=null?Rr:"")===""&&typeof w.text=="string"&&($.content=w.text),$.streaming=!1,g($)),u=null),M=null,E=""}else if(tt==="step_complete"){let U=w.stepType,$=w.executionType;if(U==="tool"||$==="context")continue;if(w.success===!1){let Q=w.error,fe=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((Yr=Q.message)!=null?Yr:"Step failed"):"Step failed";t({type:"error",error:new Error(fe)});let Oe=u;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),t({type:"status",status:"idle"});continue}{let Q=rt;rt=null;let fe=w.stopReason,Oe=(xr=w.result)==null?void 0:xr.response;if(Q)fe&&(Q.stopReason=fe),Oe!=null?lt(Q,Oe):Q.streaming!==!1&&(Y.delete(Q.id),le.delete(Q.id),Q.streaming=!1,g(Q));else{let Je=Oe!=null&&Oe!=="";if(Je||fe){let Et=Ue();fe&&(Et.stopReason=fe),Je?pe(Et,Oe):(Et.streaming=!1,g(Et))}}continue}}else if(tt==="execution_start")Pt=w.kind==="flow"?"flow":"agent",Pt==="agent"&&(me={executionId:w.executionId,agentId:(Un=w.agentId)!=null?Un:"virtual",agentName:(ye=w.agentName)!=null?ye:"",status:"running",currentIteration:0,maxTurns:(dt=w.maxTurns)!=null?dt:1,startedAt:te(w.startedAt)});else if(tt==="turn_start"){let U=typeof w.iteration=="number"?w.iteration:je;if(U!==je){if(me&&(me.currentIteration=U),It==="separate"&&U>1){let $=u;$&&($.streaming=!1,g($),fn.set(U-1,$),u=null)}je=U}Te=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let U=(Qt=w.toolCallId)!=null?Qt:D.lastId;if(U){let $=W.get(U);$!=null&&$.toolCall&&($.toolCall.chunks=(on=$.toolCall.chunks)!=null?on:[],$.toolCall.chunks.push((wr=w.delta)!=null?wr:""),g($))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let U=w.stopReason,$=u!=null?u:v;if(U&&$!==null){let Q=w.id;(!Q||((fs=$.agentMetadata)==null?void 0:fs.turnId)===Q)&&($.stopReason=U,g($))}Te===w.id&&(Te=null)}else if(tt==="media_start"){let U=String(w.id);we.set(U,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let U=we.get(String(w.id));U&&typeof w.delta=="string"&&U.parts.push(w.delta)}else if(tt==="media_complete"){let U=String(w.id),$=we.get(U);we.delete(U);let Q=(ho=(Hr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Hr:$==null?void 0:$.mediaType)!=null?ho:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:$&&$.parts.length>0?$.parts.join(""):void 0,Je=null;if(fe)Je={type:"media",data:fe,mediaType:Q};else if(Oe){let jn=Q.toLowerCase();Je={type:jn==="image"||jn.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:Q}}let Et=(Cr=w.toolCallId)!=null?Cr:$==null?void 0:$.toolCallId,Nr=Je?[Je]:[],Hn=[];for(let jn of Nr){if(!jn||typeof jn!="object")continue;let un=jn,eo=typeof un.type=="string"?un.type:void 0,Fr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",mn=null,Bn="";if(eo==="media"){let Vn=typeof un.data=="string"?un.data:void 0;if(!Vn)continue;Bn=Fr.length>0?Fr:"application/octet-stream",mn=`data:${Bn};base64,${Vn}`}else if(eo==="image-url"){let Vn=typeof un.url=="string"?un.url:void 0;if(!Vn)continue;Bn=Fr,mn=Vn}else if(eo==="file-url"){let Vn=typeof un.url=="string"?un.url:void 0;if(!Vn)continue;Bn=Fr,mn=Vn}else continue;if(mn)if(eo==="image-url"||Bn.startsWith("image/"))Hn.push({type:"image",image:mn,...Bn.includes("/")?{mimeType:Bn}:{}});else if(Bn.startsWith("audio/"))Hn.push({type:"audio",audio:mn,mimeType:Bn});else if(Bn.startsWith("video/"))Hn.push({type:"video",video:mn,mimeType:Bn});else{let Vn=Bn||"application/octet-stream";Hn.push({type:"file",data:mn,mimeType:Vn,filename:mf(Vn)})}}if(Hn.length>0){let jn=c(),un=Et,Fr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${jn}`:String(jn)}`,role:"assistant",content:"",contentParts:Hn,createdAt:new Date().toISOString(),streaming:!1,sequence:jn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:je}};g(Fr);let mn=u;mn&&(mn.streaming=!1,g(mn)),u=null,x.current=null}}else if(tt==="execution_complete"){let U=(_=w.kind)!=null?_:Pt;U==="agent"&&me&&(me.status=w.success?"complete":"error",me.completedAt=te(w.completedAt),me.stopReason=w.stopReason);let $=u;$&&(U==="flow"&&$.streaming!==!1?pe($):($.streaming=!1,g($)),u=null),M=null,E="",rt=null,t({type:"status",status:"idle"})}else if(tt==="execution_error"){let U=typeof w.error=="string"?w.error:(Ar=(Fo=w.error)==null?void 0:Fo.message)!=null?Ar:"Execution error";t({type:"error",error:new Error(U)})}else if(tt!=="ping"){if(tt==="approval_start"){let U=(Sr=w.approvalId)!=null?Sr:`approval-${c()}`,$={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:"pending",agentId:(Br=me==null?void 0:me.agentId)!=null?Br:"virtual",executionId:(lr=(Tr=w.executionId)!=null?Tr:me==null?void 0:me.executionId)!=null?lr:"",toolName:(Oo=w.toolName)!=null?Oo:"",toolType:w.toolType,description:(qn=w.description)!=null?qn:`Execute ${(ra=w.toolName)!=null?ra:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g($)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let U=(zn=w.approvalId)!=null?zn:`approval-${c()}`,$={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:"pending",agentId:(cr=me==null?void 0:me.agentId)!=null?cr:"virtual",executionId:(yo=(dr=w.executionId)!=null?dr:me==null?void 0:me.executionId)!=null?yo:"",toolName:(Dr=w.toolName)!=null?Dr:"",toolType:w.toolType,description:(Mr=w.description)!=null?Mr:`Execute ${(yn=w.toolName)!=null?yn:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g($)}else if(tt==="approval_complete"){let U=w.approvalId;if(U){let Q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:(_o=w.decision)!=null?_o:"approved",agentId:(bo=me==null?void 0:me.agentId)!=null?bo:"virtual",executionId:(oa=($o=w.executionId)!=null?$o:me==null?void 0:me.executionId)!=null?oa:"",toolName:(Uo=w.toolName)!=null?Uo:"",description:(sa=w.description)!=null?sa:"",resolvedAt:Date.now()}};g(Q)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let U=w.artifactType,$=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(t({type:"artifact_start",id:$,artifactType:U,title:Q,component:typeof w.component=="string"?w.component:void 0}),ie.set($,{markdown:"",title:Q}),!X.has($)){X.add($);let fe={id:`artifact-ref-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:$,title:Q,artifactType:U,status:"streaming"}})};re.set($,fe),g(fe)}}else if(tt==="artifact_delta"){let U=String(w.id),$=typeof w.delta=="string"?w.delta:String((qo=w.delta)!=null?qo:"");t({type:"artifact_delta",id:U,artDelta:$});let Q=ie.get(U);Q&&(Q.markdown+=$)}else if(tt==="artifact_update"){let U=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};t({type:"artifact_update",id:String(w.id),props:U,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let U=String(w.id);t({type:"artifact_complete",id:U});let $=re.get(U);if($){$.streaming=!1;try{let Q=JSON.parse((ht=$.rawContent)!=null?ht:"{}");if(Q.props){Q.props.status="complete";let fe=ie.get(U);fe!=null&&fe.markdown&&(Q.props.markdown=fe.markdown)}$.rawContent=JSON.stringify(Q)}catch{}ie.delete(U),g($),re.delete(U)}}}else if(tt==="transcript_insert"){let U=w.message;if(!U||typeof U!="object")continue;let $=String((hs=U.id)!=null?hs:`msg-${c()}`),Q=U.role,Oe={id:$,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:c()};if(g(Oe),Oe.rawContent)try{let Je=JSON.parse(Oe.rawContent),Et=(tr=Je==null?void 0:Je.props)==null?void 0:tr.artifactId;typeof Et=="string"&&X.add(Et)}catch{}u=null,x.current=null,Y.delete($),le.delete($)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let U=typeof w.error=="string"?w.error:((Rn=w.error)==null?void 0:Rn.message)!=null?String(w.error.message):"Execution error";t({type:"error",error:new Error(U)});let $=u;$&&$.streaming&&($.streaming=!1,g($)),t({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let U=null;if(w.error instanceof Error)U=w.error;else if(tt==="dispatch_error"){let $=(aa=w.message)!=null?aa:w.error;$!=null&&$!==""&&(U=new Error(String($)))}else{let $=w.error;typeof $=="string"&&$!==""?U=new Error($):$!=null&&typeof $=="object"&&"message"in $&&(U=new Error(String((ia=$.message)!=null?ia:$)))}if(U){t({type:"error",error:U});let $=u;$&&$.streaming&&($.streaming=!1,g($)),t({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:T,value:ue}=await o.read();if(T)break;a+=s.decode(ue,{stream:!0});let Le=a.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Hs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},fu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},hu=()=>{var e;let n=yf();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)}},yu=()=>{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,ns.parse)(t,ns.STR|ns.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?uu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=uu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var bu=()=>{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 vu="4.1.0";var Bs=vu;var vf="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function xf(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 Li=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 wf(n){switch(n){case"json":return yu;case"regex-json":return hu;case"xml":return bu;default:return fu}}var xu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function Cf(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=xu(t);if(!xu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Hs(n);return Hs(e)!==null&&a===null?e:n}var Ds=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:vf,this.headers={"Content-Type":"application/json","X-Persona-Version":Bs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:wf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new ya(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var 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$/,""))||Sa}/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":Bs},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$/,""))||Sa}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Bs},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 L=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:L}),L}let c=await this.buildPayload(e.messages),m=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Li).map(L=>{var R,A,W;return{id:L.id,role:L.role,content:(W=(A=(R=L.contentParts)!=null?R:L.llmContent)!=null?A:L.rawContent)!=null?W:L.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,u=!!(g&&g.length>0),v=u?Xp(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,I=u&&x&&this.lastSentClientToolsFingerprint===v,M=!1,E=null,F;for(let L=0;;L++){let A={...f,...u&&(M||!I)&&g?{clientTools:g}:{},...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":Bs},body:JSON.stringify(A),signal:r.signal}),F.status===409&&L===0&&u){let W=await F.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}E=W!=null?W:{error:"Chat request failed"}}break}if(!F.ok){let L=E!=null?E: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(L.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let R=new Error(L.error||"Failed to send message");throw t({type:"error",error:R}),R}if(!F.body){let L=new Error("No response body received");throw t({type:"error",error:L}),L}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$/,""))||Sa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,m;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Sa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(m=r==null?void 0:r.streamResponse)!=null?m:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(Li).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ei(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(Li).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ei(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=m=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return r.current=f,o(f),f},c=m=>r.current?r.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=c(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,o(m)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r){var rn,hr,hn,Ve;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,m=T=>{let ue=T.reasoning?{...T.reasoning,chunks:[...T.reasoning.chunks]}:void 0,Le=T.toolCall?{...T.toolCall,chunks:T.toolCall.chunks?[...T.toolCall.chunks]:void 0}:void 0,Me=T.tools?T.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...T,reasoning:ue,toolCall:Le,tools:Me}},f=T=>{if(T.role!=="assistant"||T.variant)return!0;let ue=Array.isArray(T.contentParts)&&T.contentParts.length>0,Le=typeof T.rawContent=="string"&&T.rawContent.trim()!=="";return typeof T.content=="string"&&T.content.trim()!==""||ue||Le||!!T.stopReason},g=T=>{f(T)&&t({type:"message",message:m(T)})},u=null,v=null,x={current:null},I={current:null},M=null,E="",F=new Map,L=new Map,R=new Map,A=new Map,W=new Map,N={lastId:null,byStep:new Map},D={lastId:null,byCall:new Map},k=T=>{if(T==null)return null;try{return String(T)}catch{return null}},j=T=>{var ue,Le,Me,He,Ze;return k((Ze=(He=(Me=(Le=(ue=T.stepId)!=null?ue:T.step_id)!=null?Le:T.step)!=null?Me:T.parentId)!=null?He:T.flowStepId)!=null?Ze:T.flow_step_id)},V=T=>{var ue,Le,Me,He,Ze,Ge,ut;return k((ut=(Ge=(Ze=(He=(Me=(Le=(ue=T.callId)!=null?ue:T.call_id)!=null?Le:T.requestId)!=null?Me:T.request_id)!=null?He:T.toolCallId)!=null?Ze:T.tool_call_id)!=null?Ge:T.stepId)!=null?ut:T.step_id)},ne=r,Re=!1,Ue=()=>{if(u)return u;let T,ue=M;return!Re&&ne?(T=ne,Re=!0):ne&&ue?T=`${ne}_${ue}`:T=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:T,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(u),u},xe=(T,ue)=>{N.lastId=ue,T&&N.byStep.set(T,ue)},Ie=(T,ue)=>{var Ze;let Le=(Ze=T.reasoningId)!=null?Ze:T.id,Me=j(T);if(Le){let Ge=String(Le);return xe(Me,Ge),Ge}if(Me){let Ge=N.byStep.get(Me);if(Ge)return N.lastId=Ge,Ge}if(N.lastId&&!ue)return N.lastId;if(!ue)return null;let He=`reason-${c()}`;return xe(Me,He),He},_e=T=>{let ue=A.get(T);if(ue)return ue;let Le={id:`reason-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"streaming",chunks:[]}};return A.set(T,Le),g(Le),Le},Se=(T,ue)=>{D.lastId=ue,T&&D.byCall.set(T,ue)},ve=new Set,re=new Map,X=new Set,ie=new Map,he=T=>{if(!T)return!1;let ue=T.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},oe=(T,ue)=>{var Ze;let Le=(Ze=T.toolId)!=null?Ze:T.id,Me=V(T);if(Le){let Ge=String(Le);return Se(Me,Ge),Ge}if(Me){let Ge=D.byCall.get(Me);if(Ge)return D.lastId=Ge,Ge}if(D.lastId&&!ue)return D.lastId;if(!ue)return null;let He=`tool-${c()}`;return Se(Me,He),He},K=T=>{let ue=W.get(T);if(ue)return ue;let Le={id:`tool-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:T,status:"pending"}};return W.set(T,Le),g(Le),Le},te=T=>{if(typeof T=="number"&&Number.isFinite(T))return T;if(typeof T=="string"){let ue=Number(T);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Le=Date.parse(T);if(!Number.isNaN(Le))return Le}return Date.now()},qe=T=>{if(typeof T=="string")return T;if(T==null)return"";try{return JSON.stringify(T)}catch{return String(T)}},Y=new Map,le=new Map,Pe=new Map,it=(T,ue,Le)=>{var ut;let Me=Pe.get(T);Me||(Me=[],Pe.set(T,Me));let He=0,Ze=Me.length;for(;He<Ze;){let Wt=He+Ze>>>1;Me[Wt].seq<ue?He=Wt+1:Ze=Wt}((ut=Me[He])==null?void 0:ut.seq)===ue?Me[He]={seq:ue,text:Le}:Me.splice(He,0,{seq:ue,text:Le});let Ge="";for(let Wt=0;Wt<Me.length;Wt++)Ge+=Me[Wt].text;return Ge},lt=(T,ue)=>{let Le=qe(ue),Me=le.get(T.id),He=Cf(Me,Le);T.rawContent=He;let Ze=Y.get(T.id),Ge=G=>{var ke;let de=(ke=T.content)!=null?ke:"";G.trim()!==""&&(de.trim().length===0||G.startsWith(de)||G.trimStart().startsWith(de.trim()))&&(T.content=G)},ut=()=>{var G;if(Ze){let de=(G=Ze.close)==null?void 0:G.call(Ze);de instanceof Promise&&de.catch(()=>{})}Y.delete(T.id),le.delete(T.id),T.streaming=!1,g(T)};if(!Ze){Ge(Le),ut();return}let Wt=Hs(He);if(Wt!==null&&Wt.trim()!==""){Ge(Wt),ut();return}let q=G=>{var vt;let de=typeof G=="string"?G:(vt=G==null?void 0:G.text)!=null?vt:null;if(de!==null&&de.trim()!=="")return de;let ke=Ze.getExtractedText();return ke!==null&&ke.trim()!==""?ke:Le},ot;try{ot=Ze.processChunk(He)}catch{Ge(Le),ut();return}if(ot instanceof Promise){ot.then(G=>{Ge(q(G)),ut()}).catch(()=>{Ge(Le),ut()});return}Ge(q(ot)),ut()},rt=null,Ee=(T,ue,Le,Me)=>{var Wt;T.rawContent=ue,Y.has(T.id)||Y.set(T.id,this.createStreamParser());let He=Y.get(T.id),Ze=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(Ze&&le.set(T.id,ue),He.__isPlainTextParser===!0){T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T);return}let ut=He.processChunk(ue);if(ut instanceof Promise)ut.then(q=>{var G;let ot=typeof q=="string"?q:(G=q==null?void 0:q.text)!=null?G:null;ot!==null&&ot.trim()!==""?(T.content=ot,g(T)):!Ze&&!ue.trim().startsWith("<")&&(T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T))}).catch(()=>{T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T)});else{let q=typeof ut=="string"?ut:(Wt=ut==null?void 0:ut.text)!=null?Wt:null;q!==null&&q.trim()!==""?(T.content=q,g(T)):!Ze&&!ue.trim().startsWith("<")&&(T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T))}},pe=(T,ue)=>{var Wt,q;let Le=ue!=null?ue:T.content;if(Le==null||Le===""){T.streaming=!1,g(T);return}let Me=le.get(T.id),He=Me!=null?Me:qe(Le);T.rawContent=He;let Ze=Y.get(T.id),Ge=null,ut=!1;if(Ze&&(Ge=Ze.getExtractedText(),Ge===null&&(Ge=Hs(He)),Ge===null)){let ot=Ze.processChunk(He);ot instanceof Promise?(ut=!0,ot.then(G=>{var ke;let de=typeof G=="string"?G:(ke=G==null?void 0:G.text)!=null?ke:null;de!==null&&(T.content=de,T.streaming=!1,Y.delete(T.id),le.delete(T.id),g(T))}).catch(()=>{})):Ge=typeof ot=="string"?ot:(Wt=ot==null?void 0:ot.text)!=null?Wt:null}if(!ut){Ge!==null&&Ge.trim()!==""?T.content=Ge:le.has(T.id)||(T.content=qe(Le));let ot=Y.get(T.id);if(ot){let G=(q=ot.close)==null?void 0:q.call(ot);G instanceof Promise&&G.catch(()=>{}),Y.delete(T.id)}le.delete(T.id),T.streaming=!1,g(T)}},Xe=(T,ue,Le)=>{let Me=L.get(T);if(Me)return Me;let He={id:`nested-${ue}-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Le?{variant:Le}:{},...Le==="reasoning"?{reasoning:{id:T,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return L.set(T,He),g(He),He},J=[],ce,we=new Map,je=0,Pt="agent",Te=null,me=null,fn=new Map,It=(rn=this.config.iterationDisplay)!=null?rn:"separate";for(ce=()=>{var T,ue,Le,Me,He,Ze,Ge,ut,Wt,q,ot,G,de,ke,vt,Yt,Zt,pn,Ht,et,Rt,ct,Kt,Jn,An,en,In,yr,xt,Nn,br,Pr,ir,yt,uo,vr,mo,Wn,No,jr,Ir,Vr,Kr,go,fo,Gr,Ct,Fn,On,Sn,St,Yn,Zn,_n,Qr,Wr,Xr,$n,Bt,Tn,er,Jr,Rr,Yr,xr,Un,ye,dt,Qt,on,wr,fs,Hr,ho,Cr,_,Fo,Ar,Sr,Br,Tr,lr,Oo,ra,qn,zn,cr,dr,yo,Dr,yn,Mr,_o,bo,$o,oa,Uo,sa,qo,ht,hs,tr,Rn,aa,ia;for(let Zr=0;Zr<J.length;Zr++){let tt=J[Zr].payloadType,w=J[Zr].payload;if(tt==="reasoning_start"){let U=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(U&&$){F.set(U,$),Xe(U,$,"reasoning");continue}let Q=(T=Ie(w,!0))!=null?T:`reason-${c()}`,fe=_e(Q);fe.reasoning=(ue=fe.reasoning)!=null?ue:{id:Q,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Me=fe.reasoning.startedAt)!=null?Me:te((Le=w.startedAt)!=null?Le:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(tt==="reasoning_delta"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)&&L.has(U)){let Oe=L.get(U),Je=(Ge=(Ze=(He=w.reasoningText)!=null?He:w.text)!=null?Ze:w.delta)!=null?Ge:"";Je&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(Je)),g(Oe));continue}let $=(Wt=(ut=Ie(w,!1))!=null?ut:Ie(w,!0))!=null?Wt:`reason-${c()}`,Q=_e($);Q.reasoning=(q=Q.reasoning)!=null?q:{id:$,status:"streaming",chunks:[]},Q.reasoning.startedAt=(G=Q.reasoning.startedAt)!=null?G:te((ot=w.startedAt)!=null?ot:w.timestamp);let fe=(vt=(ke=(de=w.reasoningText)!=null?de:w.text)!=null?ke:w.delta)!=null?vt:"";if(fe&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let Je=it($,Oe,String(fe));Q.reasoning.chunks=[Je]}else Q.reasoning.chunks.push(String(fe))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=te((Yt=w.completedAt)!=null?Yt:w.timestamp);let Oe=(Zt=Q.reasoning.startedAt)!=null?Zt:Date.now();Q.reasoning.durationMs=Math.max(0,((pn=Q.reasoning.completedAt)!=null?pn:Date.now())-Oe)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(tt==="reasoning_complete"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)&&L.has(U)){let Je=L.get(U);if(Je.reasoning){let Et=typeof w.text=="string"?w.text:"";Et&&Je.reasoning.chunks.length===0&&Je.reasoning.chunks.push(Et),Je.reasoning.status="complete",Je.streaming=!1,g(Je)}F.delete(U),L.delete(U);continue}let $=(et=(Ht=Ie(w,!1))!=null?Ht:Ie(w,!0))!=null?et:`reason-${c()}`,Q=typeof w.text=="string"?w.text:"";!A.get($)&&(Q||w.scope==="loop")&&_e($);let fe=A.get($);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),Q&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(Q),fe.reasoning.status="complete",fe.reasoning.completedAt=te((Rt=w.completedAt)!=null?Rt:w.timestamp);let Je=(ct=fe.reasoning.startedAt)!=null?ct:Date.now();fe.reasoning.durationMs=Math.max(0,((Kt=fe.reasoning.completedAt)!=null?Kt:Date.now())-Je),fe.streaming=!1,g(fe)}let Oe=j(w);Oe&&N.byStep.delete(Oe)}else if(tt==="tool_start"){u&&(u.streaming=!1,g(u),u=null),typeof w.iteration=="number"&&(je=w.iteration);let U=(An=(Jn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Jn:oe(w,!0))!=null?An:`tool-${c()}`,$=(en=w.toolName)!=null?en:w.name;if(he($)){ve.add(U);continue}Se(V(w),U);let Q=K(U),fe=(In=Q.toolCall)!=null?In:{id:U,status:"pending"};fe.name=$!=null?$:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(xt=fe.startedAt)!=null?xt:te((yr=w.startedAt)!=null?yr:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,Q.toolCall=fe,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(Q)}else if(tt==="tool_output_delta"){let U=(br=(Nn=oe(w,!1))!=null?Nn:oe(w,!0))!=null?br:`tool-${c()}`;if(ve.has(U))continue;let $=K(U),Q=(Pr=$.toolCall)!=null?Pr:{id:U,status:"running"};Q.startedAt=(yt=Q.startedAt)!=null?yt:te((ir=w.startedAt)!=null?ir:w.timestamp);let fe=(mo=(vr=(uo=w.text)!=null?uo:w.delta)!=null?vr:w.message)!=null?mo:"";fe&&(Q.chunks=(Wn=Q.chunks)!=null?Wn:[],Q.chunks.push(String(fe))),Q.status="running",$.toolCall=Q,$.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&($.agentMetadata=(Ir=$.agentMetadata)!=null?Ir:{executionId:(No=Oe==null?void 0:Oe.executionId)!=null?No:w.executionId,iteration:(jr=Oe==null?void 0:Oe.iteration)!=null?jr:w.iteration}),g($)}else if(tt==="tool_complete"){let U=(Kr=(Vr=oe(w,!1))!=null?Vr:oe(w,!0))!=null?Kr:`tool-${c()}`;if(ve.has(U)){ve.delete(U);continue}let $=K(U),Q=(go=$.toolCall)!=null?go:{id:U,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=te((fo=w.completedAt)!=null?fo:w.timestamp);let fe=(Gr=w.duration)!=null?Gr:w.executionTime;if(typeof fe=="number")Q.durationMs=fe;else{let Et=(Ct=Q.startedAt)!=null?Ct:Date.now();Q.durationMs=Math.max(0,((Fn=Q.completedAt)!=null?Fn:Date.now())-Et)}$.toolCall=Q,$.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&($.agentMetadata=(St=$.agentMetadata)!=null?St:{executionId:(On=Oe==null?void 0:Oe.executionId)!=null?On:w.executionId,iteration:(Sn=Oe==null?void 0:Oe.iteration)!=null?Sn:w.iteration}),g($);let Je=V(w);Je&&D.byCall.delete(Je)}else if(tt==="await"&&w.toolName){let U=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,$=(Yn=U!=null?U:w.toolId)!=null?Yn:`local-${c()}`,Q=K($),fe=w.toolName,Oe=w.origin==="webmcp"&&!Jo(fe)?`webmcp:${fe}`:fe,Je=Jo(Oe),Et=(Zn=Q.toolCall)!=null?Zn:{id:$,status:"pending"};Et.name=Oe,Et.args=w.parameters,Et.status=Je?"running":"complete",Et.chunks=(_n=Et.chunks)!=null?_n:[],Et.startedAt=(Xr=Et.startedAt)!=null?Xr:te((Wr=(Qr=w.startedAt)!=null?Qr:w.timestamp)!=null?Wr:w.awaitedAt),Je?(Et.completedAt=void 0,Et.duration=void 0,Et.durationMs=void 0):Et.completedAt=($n=Et.completedAt)!=null?$n:Et.startedAt,Q.toolCall=Et,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Tn=w.executionId)!=null?Tn:(Bt=Q.agentMetadata)==null?void 0:Bt.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(Q)}else if(tt==="text_start"){let U=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(U&&$){F.set(U,$);continue}let Q=u;Q&&(Pt==="flow"?(pe(Q),rt=Q):(Q.streaming=!1,g(Q)),u=null),M=typeof w.id=="string"?w.id:M,E=""}else if(tt==="text_delta"){let U=typeof w.id=="string"?w.id:null,$=U?F.get(U):void 0;if(U&&$){let fe=typeof w.delta=="string"?w.delta:"",Oe=((er=R.get(U))!=null?er:"")+fe;if(R.set(U,Oe),Oe.trim()==="")continue;let Je=Xe(U,$);Je.agentMetadata={...Je.agentMetadata,executionId:w.executionId,parentToolId:$},Ee(Je,Oe,fe,void 0);continue}if(M=typeof w.id=="string"?w.id:M,Pt==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(E+=fe,E.trim()==="")continue;let Oe=Ue();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ee(Oe,E,fe,void 0),v=Oe;continue}let Q=Ue();Q.content+=(Jr=w.delta)!=null?Jr:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Te!=null?Te:void 0,agentName:me==null?void 0:me.agentName},v=Q,g(Q)}else if(tt==="text_complete"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)){let Q=L.get(U);Q&&pe(Q),F.delete(U),R.delete(U),L.delete(U);continue}let $=u;$&&(Pt==="flow"?(pe($),rt=$):(((Rr=$.content)!=null?Rr:"")===""&&typeof w.text=="string"&&($.content=w.text),$.streaming=!1,g($)),u=null),M=null,E=""}else if(tt==="step_complete"){let U=w.stepType,$=w.executionType;if(U==="tool"||$==="context")continue;if(w.success===!1){let Q=w.error,fe=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((Yr=Q.message)!=null?Yr:"Step failed"):"Step failed";t({type:"error",error:new Error(fe)});let Oe=u;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),t({type:"status",status:"idle"});continue}{let Q=rt;rt=null;let fe=w.stopReason,Oe=(xr=w.result)==null?void 0:xr.response;if(Q)fe&&(Q.stopReason=fe),Oe!=null?lt(Q,Oe):Q.streaming!==!1&&(Y.delete(Q.id),le.delete(Q.id),Q.streaming=!1,g(Q));else{let Je=Oe!=null&&Oe!=="";if(Je||fe){let Et=Ue();fe&&(Et.stopReason=fe),Je?pe(Et,Oe):(Et.streaming=!1,g(Et))}}continue}}else if(tt==="execution_start")Pt=w.kind==="flow"?"flow":"agent",Pt==="agent"&&(me={executionId:w.executionId,agentId:(Un=w.agentId)!=null?Un:"virtual",agentName:(ye=w.agentName)!=null?ye:"",status:"running",currentIteration:0,maxTurns:(dt=w.maxTurns)!=null?dt:1,startedAt:te(w.startedAt)});else if(tt==="turn_start"){let U=typeof w.iteration=="number"?w.iteration:je;if(U!==je){if(me&&(me.currentIteration=U),It==="separate"&&U>1){let $=u;$&&($.streaming=!1,g($),fn.set(U-1,$),u=null)}je=U}Te=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let U=(Qt=w.toolCallId)!=null?Qt:D.lastId;if(U){let $=W.get(U);$!=null&&$.toolCall&&($.toolCall.chunks=(on=$.toolCall.chunks)!=null?on:[],$.toolCall.chunks.push((wr=w.delta)!=null?wr:""),g($))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let U=w.stopReason,$=u!=null?u:v;if(U&&$!==null){let Q=w.id;(!Q||((fs=$.agentMetadata)==null?void 0:fs.turnId)===Q)&&($.stopReason=U,g($))}Te===w.id&&(Te=null)}else if(tt==="media_start"){let U=String(w.id);we.set(U,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let U=we.get(String(w.id));U&&typeof w.delta=="string"&&U.parts.push(w.delta)}else if(tt==="media_complete"){let U=String(w.id),$=we.get(U);we.delete(U);let Q=(ho=(Hr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Hr:$==null?void 0:$.mediaType)!=null?ho:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:$&&$.parts.length>0?$.parts.join(""):void 0,Je=null;if(fe)Je={type:"media",data:fe,mediaType:Q};else if(Oe){let jn=Q.toLowerCase();Je={type:jn==="image"||jn.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:Q}}let Et=(Cr=w.toolCallId)!=null?Cr:$==null?void 0:$.toolCallId,Nr=Je?[Je]:[],Hn=[];for(let jn of Nr){if(!jn||typeof jn!="object")continue;let un=jn,eo=typeof un.type=="string"?un.type:void 0,Fr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",mn=null,Bn="";if(eo==="media"){let Vn=typeof un.data=="string"?un.data:void 0;if(!Vn)continue;Bn=Fr.length>0?Fr:"application/octet-stream",mn=`data:${Bn};base64,${Vn}`}else if(eo==="image-url"){let Vn=typeof un.url=="string"?un.url:void 0;if(!Vn)continue;Bn=Fr,mn=Vn}else if(eo==="file-url"){let Vn=typeof un.url=="string"?un.url:void 0;if(!Vn)continue;Bn=Fr,mn=Vn}else continue;if(mn)if(eo==="image-url"||Bn.startsWith("image/"))Hn.push({type:"image",image:mn,...Bn.includes("/")?{mimeType:Bn}:{}});else if(Bn.startsWith("audio/"))Hn.push({type:"audio",audio:mn,mimeType:Bn});else if(Bn.startsWith("video/"))Hn.push({type:"video",video:mn,mimeType:Bn});else{let Vn=Bn||"application/octet-stream";Hn.push({type:"file",data:mn,mimeType:Vn,filename:xf(Vn)})}}if(Hn.length>0){let jn=c(),un=Et,Fr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${jn}`:String(jn)}`,role:"assistant",content:"",contentParts:Hn,createdAt:new Date().toISOString(),streaming:!1,sequence:jn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:je}};g(Fr);let mn=u;mn&&(mn.streaming=!1,g(mn)),u=null,x.current=null}}else if(tt==="execution_complete"){let U=(_=w.kind)!=null?_:Pt;U==="agent"&&me&&(me.status=w.success?"complete":"error",me.completedAt=te(w.completedAt),me.stopReason=w.stopReason);let $=u;$&&(U==="flow"&&$.streaming!==!1?pe($):($.streaming=!1,g($)),u=null),M=null,E="",rt=null,t({type:"status",status:"idle"})}else if(tt==="execution_error"){let U=typeof w.error=="string"?w.error:(Ar=(Fo=w.error)==null?void 0:Fo.message)!=null?Ar:"Execution error";t({type:"error",error:new Error(U)})}else if(tt!=="ping"){if(tt==="approval_start"){let U=(Sr=w.approvalId)!=null?Sr:`approval-${c()}`,$={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:"pending",agentId:(Br=me==null?void 0:me.agentId)!=null?Br:"virtual",executionId:(lr=(Tr=w.executionId)!=null?Tr:me==null?void 0:me.executionId)!=null?lr:"",toolName:(Oo=w.toolName)!=null?Oo:"",toolType:w.toolType,description:(qn=w.description)!=null?qn:`Execute ${(ra=w.toolName)!=null?ra:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g($)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let U=(zn=w.approvalId)!=null?zn:`approval-${c()}`,$={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:"pending",agentId:(cr=me==null?void 0:me.agentId)!=null?cr:"virtual",executionId:(yo=(dr=w.executionId)!=null?dr:me==null?void 0:me.executionId)!=null?yo:"",toolName:(Dr=w.toolName)!=null?Dr:"",toolType:w.toolType,description:(Mr=w.description)!=null?Mr:`Execute ${(yn=w.toolName)!=null?yn:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g($)}else if(tt==="approval_complete"){let U=w.approvalId;if(U){let Q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:(_o=w.decision)!=null?_o:"approved",agentId:(bo=me==null?void 0:me.agentId)!=null?bo:"virtual",executionId:(oa=($o=w.executionId)!=null?$o:me==null?void 0:me.executionId)!=null?oa:"",toolName:(Uo=w.toolName)!=null?Uo:"",description:(sa=w.description)!=null?sa:"",resolvedAt:Date.now()}};g(Q)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let U=w.artifactType,$=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(t({type:"artifact_start",id:$,artifactType:U,title:Q,component:typeof w.component=="string"?w.component:void 0}),ie.set($,{markdown:"",title:Q}),!X.has($)){X.add($);let fe={id:`artifact-ref-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:$,title:Q,artifactType:U,status:"streaming"}})};re.set($,fe),g(fe)}}else if(tt==="artifact_delta"){let U=String(w.id),$=typeof w.delta=="string"?w.delta:String((qo=w.delta)!=null?qo:"");t({type:"artifact_delta",id:U,artDelta:$});let Q=ie.get(U);Q&&(Q.markdown+=$)}else if(tt==="artifact_update"){let U=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};t({type:"artifact_update",id:String(w.id),props:U,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let U=String(w.id);t({type:"artifact_complete",id:U});let $=re.get(U);if($){$.streaming=!1;try{let Q=JSON.parse((ht=$.rawContent)!=null?ht:"{}");if(Q.props){Q.props.status="complete";let fe=ie.get(U);fe!=null&&fe.markdown&&(Q.props.markdown=fe.markdown)}$.rawContent=JSON.stringify(Q)}catch{}ie.delete(U),g($),re.delete(U)}}}else if(tt==="transcript_insert"){let U=w.message;if(!U||typeof U!="object")continue;let $=String((hs=U.id)!=null?hs:`msg-${c()}`),Q=U.role,Oe={id:$,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:c()};if(g(Oe),Oe.rawContent)try{let Je=JSON.parse(Oe.rawContent),Et=(tr=Je==null?void 0:Je.props)==null?void 0:tr.artifactId;typeof Et=="string"&&X.add(Et)}catch{}u=null,x.current=null,Y.delete($),le.delete($)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let U=typeof w.error=="string"?w.error:((Rn=w.error)==null?void 0:Rn.message)!=null?String(w.error.message):"Execution error";t({type:"error",error:new Error(U)});let $=u;$&&$.streaming&&($.streaming=!1,g($)),t({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let U=null;if(w.error instanceof Error)U=w.error;else if(tt==="dispatch_error"){let $=(aa=w.message)!=null?aa:w.error;$!=null&&$!==""&&(U=new Error(String($)))}else{let $=w.error;typeof $=="string"&&$!==""?U=new Error($):$!=null&&typeof $=="object"&&"message"in $&&(U=new Error(String((ia=$.message)!=null?ia:$)))}if(U){t({type:"error",error:U});let $=u;$&&$.streaming&&($.streaming=!1,g($)),t({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:T,value:ue}=await o.read();if(T)break;a+=s.decode(ue,{stream:!0});let Le=a.split(`
10
12
 
11
13
  `);a=(hr=Le.pop())!=null?hr:"";for(let Me of Le){let He=Me.split(`
12
- `),Ze="message",Ge="";for(let q of He)q.startsWith("event:")?Ze=q.replace("event:","").trim():q.startsWith("data:")&&(Ge+=q.replace("data:","").trim());if(!Ge)continue;let ut;try{ut=JSON.parse(Ge)}catch(q){t({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Wt=Ze!=="message"?Ze:(hn=ut.type)!=null?hn:"message";if((Ve=this.onSSEEvent)==null||Ve.call(this,Wt,ut),this.parseSSEEvent){x.current=u;let q=await this.handleCustomSSEEvent(ut,t,x,g,c,I);if(x.current&&x.current!==u&&(u=x.current),q)continue}J.push({payloadType:Wt,payload:ut}),ce()}}ce()}};function Ta(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Ns(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ma="[Image]";function Pi(n){return{type:"text",text:n}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],hf=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Ur=[...yu,...hf];function yf(n){return yu.includes(n)||n.startsWith("image/")}function Ea(n){return yf(n.type)}async function bu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ea(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function vu(n,e=Ur,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function bf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function xu(n,e){let t=bf(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||t||"FILE"}Ii();var wu=16e3,vf=24e3,xf=4096,wf=1380533830;function Cf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===wf?new Uint8Array(n,44):new Uint8Array(n)}function Af(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Fs=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 m=window.AudioContext||window.webkitAudioContext,f=new m({sampleRate:wu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new os(vf);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${Af(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(u,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let I=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${I}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(xf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let m=0;m<d.length;m++){let f=Math.max(-1,Math.min(1,d[m]));c[m]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=Cf(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var Io=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,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 ss(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Fs(n.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function Cu(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ss({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ss({type:"runtype",runtype:n.runtype});if(Io.isSupported())return ss({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Wi(n){try{return Cu(n),!0}catch{return!1}}function ka(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 as=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):ka(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,m;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(m=t.onError)==null||m.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Os=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 Ri(n){if(!n)return"";let e=Sf(n);return Au(e!==null?e:n)}function Sf(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Au(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
14
+ `),Ze="message",Ge="";for(let q of He)q.startsWith("event:")?Ze=q.replace("event:","").trim():q.startsWith("data:")&&(Ge+=q.replace("data:","").trim());if(!Ge)continue;let ut;try{ut=JSON.parse(Ge)}catch(q){t({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Wt=Ze!=="message"?Ze:(hn=ut.type)!=null?hn:"message";if((Ve=this.onSSEEvent)==null||Ve.call(this,Wt,ut),this.parseSSEEvent){x.current=u;let q=await this.handleCustomSSEEvent(ut,t,x,g,c,I);if(x.current&&x.current!==u&&(u=x.current),q)continue}J.push({payloadType:Wt,payload:ut}),ce()}}ce()}};function Ta(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Ns(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ma="[Image]";function Pi(n){return{type:"text",text:n}}var wu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Af=["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"],Ur=[...wu,...Af];function Sf(n){return wu.includes(n)||n.startsWith("image/")}function Ea(n){return Sf(n.type)}async function Cu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ea(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 Au(n,e=Ur,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 Tf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function Su(n,e){let t=Tf(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"}Ii();var Tu=16e3,Mf=24e3,Ef=4096,kf=1380533830;function Lf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===kf?new Uint8Array(n,44):new Uint8Array(n)}function Pf(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 Fs=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:Tu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let m=window.AudioContext||window.webkitAudioContext,f=new m({sampleRate:Tu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new os(Mf);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${Pf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(u,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let I=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${I}`)),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(Ef,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let m=0;m<d.length;m++){let f=Math.max(-1,Math.min(1,d[m]));c[m]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=Lf(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 Io=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,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 ss(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Fs(n.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(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 Mu(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ss({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ss({type:"runtype",runtype:n.runtype});if(Io.isSupported())return ss({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Wi(n){try{return Mu(n),!0}catch{return!1}}function ka(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 as=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):ka(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,m;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(m=t.onError)==null||m.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Os=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 Ri(n){if(!n)return"";let e=If(n);return Eu(e!==null?e:n)}function If(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 Eu(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
15
  `),e=e.replace(/\n{2,}/g,`
14
- `),e.trim()}var ku=null;var Hi=()=>ku?ku():Promise.resolve().then(()=>(Eu(),Mu));var Ef=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function kf(n,e){return Ef.some(t=>n[t]!==e[t])}function Lu(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${r}
16
+ `),e.trim()}var Wu=null;var Hi=()=>Wu?Wu():Promise.resolve().then(()=>(Iu(),Pu));var Hf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Bf(n,e){return Hf.some(t=>n[t]!==e[t])}function Ru(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}
15
17
 
16
- _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]}),Pu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,Iu=n=>Jo(n)||n===$r,Ia=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 Os(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,m,f;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,u=!!(g!=null&&g.name)&&(Jo(g.name)||g.name===$r&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&u&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(m=this.callbacks).onError)==null||f.call(m,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ds(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||Hi().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 Wi((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=as.isSupported()?new as({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,m=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&m)return Hi().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:u})=>{let v=new g({host:d,agentId:c,clientToken:m,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&t?new u(v,t,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&t)return m&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ss(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let m=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=m.id}if(c){this.pendingVoiceUserMessageId=null;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let m=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=m.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,m,f;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((m=e.browser)==null?void 0:m.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!kf(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Ds(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:m,rawContent:f}=e,u={id:a!=null?a:t==="user"?Ta():t==="assistant"?Ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};return this.upsertMessage(u),u}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:m,streaming:f=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:o==="user"?Ta():o==="assistant"?Ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,m,f,g,u;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Ta(),s=Ns(),a={id:o,role:"user",content:r||Ma,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 I=Lu(v,this.config.errorMessage);if(I){let M={id:s,role:"assistant",createdAt:new Date().toISOString(),content:I,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(m=this.callbacks).onError)==null||f.call(m,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Ns();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){let m=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!m){let f=Lu(c,this.config.errorMessage);if(f){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var m,f,g,u,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(m=a==null?void 0:a.createdAt)!=null?m:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(c?x=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),x){let I=null;if(x instanceof Response){if(!x.ok){let M=await x.json().catch(()=>null);throw new Error((g=M==null?void 0:M.error)!=null?g:`Approval request failed: ${x.status}`)}I=x.body}else x instanceof ReadableStream&&(I=x);I?await this.connectStream(I,{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 I=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(v=(u=this.callbacks).onError)==null||v.call(u,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var m,f,g,u,v,x,I,M,E,F,L,R;let r=this.messages.find(A=>A.id===e.id);if(((m=r==null?void 0:r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let 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 N=typeof((I=W[0])==null?void 0:I.question)=="string"?W[0].question:"";N&&(a={[N]:t})}}this.markAskUserQuestionResolved(e,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(E=e.toolCall)==null?void 0:E.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,N])=>`${W}: ${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((W,N)=>{let D=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!D)return;let k=A[D],j=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${N}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${N}`,role:"user",content:j||"*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=(L=this.callbacks).onError)==null||R.call(L,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)!==$r)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,m,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async g=>{var R,A,W,N,D,k,j;let u=(R=g.toolCall)==null?void 0:R.name,v=(A=g.toolCall)==null?void 0:A.id;if(!u||!v)return null;let x=`${e}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let I=this.markWebMcpToolRunning(g),M=(N=(W=g.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?N:u;if(u===$r)return{dedupeKey:x,resumeKey:M,output:Ti(),toolMessage:g,startedAt:I,completedAt:Date.now()};let E=new AbortController;this.webMcpResolveControllers.add(E),o.push(E);let F=this.client.executeWebMcpToolCall(u,(D=g.toolCall)==null?void 0:D.args,E.signal),L;if(!F)L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{L=await F}catch(V){let ne=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return ne||(j=(k=this.callbacks).onError)==null||j.call(k,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(g,_s(ne?"Aborted by cancel()":Pu(V)),I),this.webMcpInflightKeys.delete(x),null}return E.signal.aborted?(this.markWebMcpToolComplete(g,_s("Aborted by cancel()"),I),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:M,output:L,toolMessage:g,startedAt:I,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let u=await this.client.resumeFlow(e,g,{signal:s.signal});if(!u.ok){let v=await u.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${u.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===$r?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(f=(m=this.callbacks).onError)==null||f.call(m,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,_s("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,x,I,M,E,F,L,R,A,W,N,D;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(x=e.toolCall)==null?void 0:x.name,o=(I=e.toolCall)==null?void 0:I.id;if(!t){(E=(M=this.callbacks).onError)==null||E.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let k=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);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(k)}catch(j){(L=(F=this.callbacks).onError)==null||L.call(F,j instanceof Error?j:new Error(String(j)))}finally{this.webMcpInflightKeys.delete(k)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===$r,m=(R=e.toolCall)==null?void 0:R.args,f=c?null:this.client.executeWebMcpToolCall(r,m,d),g="execute",u=a;try{let k;if(c?k=Ti():f?k=await f:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),d.aborted){this.markWebMcpToolComplete(e,_s("Aborted by cancel()"),a);return}let j=(W=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?W:r;g="resume",await this.resumeWithToolOutput(t,j,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,k,a,u,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let j=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(g==="execute"||j||d.aborted)&&this.markWebMcpToolComplete(e,_s(j||d.aborted?"Aborted by cancel()":Pu(k)),a),j||(D=(N=this.callbacks).onError)==null||D.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(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=Ri(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ka(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Ri(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var m,f,g,u,v,x,I,M,E,F,L,R,A,W,N;if(s!==r)return o;let a={...o,...t};if(((m=o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let D=o.approval,k=t.approval;a.approval={...D,...k,executionId:k.executionId||D.executionId,toolName:k.toolName||D.toolName,description:k.description||D.description,toolType:(u=k.toolType)!=null?u:D.toolType,reason:(v=k.reason)!=null?v:D.reason,parameters:(x=k.parameters)!=null?x:D.parameters}}let i=(I=t.toolCall)==null?void 0:I.name,d=(M=t.agentMetadata)==null?void 0:M.executionId,c=(E=t.toolCall)==null?void 0:E.id;if(i&&Iu(i)&&d&&c&&((F=t.agentMetadata)==null?void 0:F.awaitingLocalTool)===!0){let D=`${d}:${c}`,k=this.webMcpInflightKeys.has(D),j=this.webMcpResolvedKeys.has(D),V=(L=o.toolCall)==null?void 0:L.name,ne=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&V!==void 0&&Iu(V)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(k||j||ne)&&(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(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 C=require("lucide"),Lf={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},Ae=(n,e=24,t="currentColor",r=2)=>{let o=Lf[n];return o?Pf(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 Pf(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,m])=>{c!=="stroke"&&d.setAttribute(c,String(m))}),o.appendChild(d)}),o}var Wa={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function If(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Wf(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 $s=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Wa.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Wa.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Wa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Wa.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let m=vu(c,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let f=(o=m.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await bu(c),g=Ea(c)?URL.createObjectURL(c):null,u={id:If(),file:c,previewUrl:g,contentPart:f};this.attachments.push(u),this.renderPreview(u)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Ea(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=Wf(e.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=xu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Wu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Us(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];Wu(s)&&Wu(o)?t[r]=Us(s,o):t[r]=o}return t}var qr="min(440px, calc(100vw - 24px))",Hu="440px",Rf={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:qr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Rf,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Ru(n,e){if(!(!n&&!e))return n?e?Us(n,e):n:e}function Bu(n){var e,t,r,o,s,a,i,d,c,m,f,g,u,v,x,I,M,E,F,L,R;return n?{...Nt,...n,theme:Ru(Nt.theme,n.theme),darkTheme:Ru(Nt.darkTheme,n.darkTheme),launcher:{...Nt.launcher,...n.launcher,dock:{...(e=Nt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Nt.copy,...n.copy},sendButton:{...Nt.sendButton,...n.sendButton},statusIndicator:{...Nt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,X,ie,he,oe,K,te,qe,Y,le;let A=(re=Nt.features)==null?void 0:re.artifacts,W=(X=n.features)==null?void 0:X.artifacts,N=(ie=Nt.features)==null?void 0:ie.scrollToBottom,D=(he=n.features)==null?void 0:he.scrollToBottom,k=(oe=Nt.features)==null?void 0:oe.scrollBehavior,j=(K=n.features)==null?void 0:K.scrollBehavior,V=(te=Nt.features)==null?void 0:te.streamAnimation,ne=(qe=n.features)==null?void 0:qe.streamAnimation,Re=(Y=Nt.features)==null?void 0:Y.askUserQuestion,Ue=(le=n.features)==null?void 0:le.askUserQuestion,xe=A===void 0&&W===void 0?void 0:{...A,...W,layout:{...A==null?void 0:A.layout,...W==null?void 0:W.layout}},Ie=N===void 0&&D===void 0?void 0:{...N,...D},_e=k===void 0&&j===void 0?void 0:{...k,...j},Se=V===void 0&&ne===void 0?void 0:{...V,...ne},ve=Re===void 0&&Ue===void 0?void 0:{...Re,...Ue,styles:{...Re==null?void 0:Re.styles,...Ue==null?void 0:Ue.styles}};return{...Nt.features,...n.features,...Ie!==void 0?{scrollToBottom:Ie}:{},..._e!==void 0?{scrollBehavior:_e}:{},...xe!==void 0?{artifacts:xe}:{},...Se!==void 0?{streamAnimation:Se}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Nt.layout,...n.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(m=Nt.layout)==null?void 0:m.messages)==null?void 0:f.avatar,...(u=(g=n.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(M=(I=n.layout)==null?void 0:I.messages)==null?void 0:M.timestamp}},slots:{...(E=Nt.layout)==null?void 0:E.slots,...(F=n.layout)==null?void 0:F.slots}},markdown:{...Nt.markdown,...n.markdown,options:{...(L=Nt.markdown)==null?void 0:L.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...Nt.messageActions,...n.messageActions}}:Nt}var Hf={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"}},Bf={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"}},Df={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:qr,maxWidth:Hu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function is(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."))?is(n,r):r}function Du(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=is(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 Nf(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function Nu(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Nu(s,o):t[r]=o}return t}function Ff(n,e){return e?Nu(n,e):n}function Wo(n,e={}){var o,s,a,i,d,c,m,f,g,u,v,x,I;let t={palette:Hf,semantic:Bf,components:Df},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(m=n==null?void 0:n.semantic)==null?void 0:m.colors,interactive:{...t.semantic.colors.interactive,...(g=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(u=n==null?void 0:n.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(I=n==null?void 0:n.semantic)==null?void 0:I.typography}},components:Ff(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let M=Nf(r);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(E=>E.message).join(", ")}`)}if(e.plugins)for(let M of e.plugins)r=M.transform(r);return r}function Fu(n){var x,I,M,E,F,L,R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re,X,ie,he,oe,K,te,qe,Y,le,Pe,it,lt,rt,Ee,pe,Xe,J,ce,we,je,Pt,Te,me,fn,It,rn,hr,hn,Ve,T,ue,Le,Me,He,Ze,Ge,ut,Wt,q,ot,G,de,ke,vt,Yt,Zt,pn,Ht,et,Rt,ct,Kt,Jn,An,en,In,yr,xt,Nn,br,Pr,ir,yt,uo,vr,mo,Wn,No,jr,Ir,Vr,Kr,go,fo,Gr,Ct,Fn,On,Sn,St,Yn,Zn,_n,Qr,Wr,Xr,$n,Bt,Tn,er,Jr,Rr,Yr,xr,Un;let e=Du(n),t={};for(let[ye,dt]of Object.entries(e)){let Qt=ye.replace(/\./g,"-");t[`--persona-${Qt}`]=dt.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(I=t["--persona-semantic-colors-secondary"])!=null?I:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(M=t["--persona-semantic-colors-accent"])!=null?M:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(E=t["--persona-semantic-colors-surface"])!=null?E: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"]=(L=t["--persona-semantic-colors-container"])!=null?L: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"]=(N=t["--persona-semantic-colors-border"])!=null?N:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(D=t["--persona-semantic-colors-divider"])!=null?D:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(k=t["--persona-components-voice-recording-indicator"])!=null?k:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(j=t["--persona-components-voice-recording-background"])!=null?j:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Re=t["--persona-components-approval-requested-background"])!=null?Re:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Ue=t["--persona-components-approval-requested-border"])!=null?Ue:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(xe=t["--persona-components-approval-requested-text"])!=null?xe:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Ie=t["--persona-components-approval-requested-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(_e=t["--persona-components-approval-approve-background"])!=null?_e:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Se=t["--persona-components-approval-deny-background"])!=null?Se:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ve=t["--persona-components-attachment-image-background"])!=null?ve:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(re=t["--persona-components-attachment-image-border"])!=null?re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(X=t["--persona-semantic-typography-fontFamily"])!=null?X:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ie=t["--persona-semantic-typography-fontSize"])!=null?ie:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(he=t["--persona-semantic-typography-fontWeight"])!=null?he:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(oe=t["--persona-semantic-typography-lineHeight"])!=null?oe: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"]=(te=t["--persona-palette-radius-md"])!=null?te:"0.375rem",t["--persona-radius-lg"]=(qe=t["--persona-palette-radius-lg"])!=null?qe:"0.5rem",t["--persona-radius-xl"]=(Y=t["--persona-palette-radius-xl"])!=null?Y:"0.75rem",t["--persona-radius-full"]=(le=t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-launcher-radius"]=(it=(Pe=t["--persona-components-launcher-borderRadius"])!=null?Pe: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"]=(rt=t["--persona-components-launcher-foreground"])!=null?rt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(Ee=t["--persona-components-launcher-border"])!=null?Ee:t["--persona-border"],t["--persona-button-primary-bg"]=(pe=t["--persona-components-button-primary-background"])!=null?pe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Xe=t["--persona-components-button-primary-foreground"])!=null?Xe:t["--persona-text-inverse"],t["--persona-button-radius"]=(ce=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?ce:"9999px",t["--persona-panel-radius"]=(je=(we=t["--persona-components-panel-borderRadius"])!=null?we:t["--persona-radius-xl"])!=null?je:"0.75rem",t["--persona-panel-border"]=(Pt=t["--persona-components-panel-border"])!=null?Pt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(me=(Te=t["--persona-components-panel-shadow"])!=null?Te:t["--persona-palette-shadows-xl"])!=null?me:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(fn=t["--persona-components-launcher-shadow"])!=null?fn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(rn=(It=t["--persona-components-input-borderRadius"])!=null?It:t["--persona-radius-lg"])!=null?rn:"0.5rem",t["--persona-message-user-radius"]=(hn=(hr=t["--persona-components-message-user-borderRadius"])!=null?hr:t["--persona-radius-lg"])!=null?hn:"0.5rem",t["--persona-message-assistant-radius"]=(T=(Ve=t["--persona-components-message-assistant-borderRadius"])!=null?Ve:t["--persona-radius-lg"])!=null?T:"0.5rem",t["--persona-header-bg"]=(ue=t["--persona-components-header-background"])!=null?ue:t["--persona-surface"],t["--persona-header-border"]=(Le=t["--persona-components-header-border"])!=null?Le:t["--persona-divider"],t["--persona-header-icon-bg"]=(Me=t["--persona-components-header-iconBackground"])!=null?Me:t["--persona-primary"],t["--persona-header-icon-fg"]=(He=t["--persona-components-header-iconForeground"])!=null?He:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ze=t["--persona-components-header-titleForeground"])!=null?Ze:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ge=t["--persona-components-header-subtitleForeground"])!=null?Ge:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ut=t["--persona-components-header-actionIconForeground"])!=null?ut:t["--persona-muted"];let r=(Wt=n.components)==null?void 0:Wt.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(q=n.components)==null?void 0:q.introCard;t["--persona-intro-card-bg"]=(ot=t["--persona-components-introCard-background"])!=null?ot:t["--persona-surface"],t["--persona-intro-card-radius"]=(G=t["--persona-components-introCard-borderRadius"])!=null?G:"1rem",t["--persona-intro-card-padding"]=(de=t["--persona-components-introCard-padding"])!=null?de:"1.5rem",t["--persona-intro-card-shadow"]=(vt=(ke=o==null?void 0:o.shadow)!=null?ke:t["--persona-components-introCard-shadow"])!=null?vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Yt=t["--persona-components-input-background"])!=null?Yt:t["--persona-surface"],t["--persona-input-placeholder"]=(Zt=t["--persona-components-input-placeholder"])!=null?Zt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(pn=t["--persona-components-message-user-background"])!=null?pn:t["--persona-accent"],t["--persona-message-user-text"]=(Ht=t["--persona-components-message-user-text"])!=null?Ht:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(et=t["--persona-components-message-user-shadow"])!=null?et:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Rt=t["--persona-components-message-assistant-background"])!=null?Rt:t["--persona-surface"],t["--persona-message-assistant-text"]=(ct=t["--persona-components-message-assistant-text"])!=null?ct:t["--persona-text"],t["--persona-message-assistant-border"]=(Kt=t["--persona-components-message-assistant-border"])!=null?Kt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Jn=t["--persona-components-message-assistant-shadow"])!=null?Jn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(en=(An=t["--persona-components-scrollToBottom-background"])!=null?An:t["--persona-button-primary-bg"])!=null?en:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(yr=(In=t["--persona-components-scrollToBottom-foreground"])!=null?In:t["--persona-button-primary-fg"])!=null?yr: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"]=(Nn=t["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",t["--persona-scroll-to-bottom-radius"]=(ir=(Pr=(br=t["--persona-components-scrollToBottom-borderRadius"])!=null?br:t["--persona-button-radius"])!=null?Pr:t["--persona-radius-full"])!=null?ir:"9999px",t["--persona-scroll-to-bottom-shadow"]=(uo=(yt=t["--persona-components-scrollToBottom-shadow"])!=null?yt:t["--persona-palette-shadows-sm"])!=null?uo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(vr=t["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(mo=t["--persona-components-scrollToBottom-gap"])!=null?mo:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(No=(Wn=t["--persona-components-scrollToBottom-fontSize"])!=null?Wn:t["--persona-palette-typography-fontSize-sm"])!=null?No:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(jr=t["--persona-components-scrollToBottom-iconSize"])!=null?jr:"14px",t["--persona-tool-bubble-shadow"]=(Ir=t["--persona-components-toolBubble-shadow"])!=null?Ir:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Vr=t["--persona-components-reasoningBubble-shadow"])!=null?Vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Kr=t["--persona-components-composer-shadow"])!=null?Kr:"none",t["--persona-md-inline-code-bg"]=(go=t["--persona-components-markdown-inlineCode-background"])!=null?go:t["--persona-container"],t["--persona-md-inline-code-color"]=(fo=t["--persona-components-markdown-inlineCode-foreground"])!=null?fo:t["--persona-text"],t["--persona-md-link-color"]=(Ct=(Gr=t["--persona-components-markdown-link-foreground"])!=null?Gr: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"]=(Fn=t["--persona-components-markdown-codeBlock-background"])!=null?Fn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(On=t["--persona-components-markdown-codeBlock-borderColor"])!=null?On:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Sn=t["--persona-components-markdown-codeBlock-textColor"])!=null?Sn:"inherit",t["--persona-md-table-header-bg"]=(St=t["--persona-components-markdown-table-headerBackground"])!=null?St:t["--persona-container"],t["--persona-md-table-border-color"]=(Yn=t["--persona-components-markdown-table-borderColor"])!=null?Yn:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(_n=t["--persona-components-markdown-blockquote-borderColor"])!=null?_n:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Qr=t["--persona-components-markdown-blockquote-background"])!=null?Qr:"transparent",t["--persona-md-blockquote-text-color"]=(Wr=t["--persona-components-markdown-blockquote-textColor"])!=null?Wr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Xr=t["--persona-components-collapsibleWidget-container"])!=null?Xr:t["--persona-surface"],t["--cw-surface"]=($n=t["--persona-components-collapsibleWidget-surface"])!=null?$n:t["--persona-surface"],t["--cw-border"]=(Bt=t["--persona-components-collapsibleWidget-border"])!=null?Bt:t["--persona-border"],t["--persona-message-border"]=(Tn=t["--persona-components-message-border"])!=null?Tn:t["--persona-border"];let m=n.components,f=m==null?void 0:m.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let g=m==null?void 0:m.labelButton;g&&(g.background&&(t["--persona-label-btn-bg"]=g.background),g.border&&(t["--persona-label-btn-border"]=g.border),g.color&&(t["--persona-label-btn-color"]=g.color),g.padding&&(t["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(t["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(t["--persona-label-btn-gap"]=g.gap));let u=m==null?void 0:m.toggleGroup;u&&(u.gap&&(t["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(t["--persona-toggle-group-radius"]=u.borderRadius));let v=m==null?void 0:m.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,t["--persona-dropdown-bg"]=(er=t["--persona-dropdown-bg"])!=null?er:ye.copyMenuBackground),ye.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,t["--persona-dropdown-border"]=(Jr=t["--persona-dropdown-border"])!=null?Jr:ye.copyMenuBorder),ye.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,t["--persona-dropdown-shadow"]=(Rr=t["--persona-dropdown-shadow"])!=null?Rr:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Yr=t["--persona-dropdown-radius"])!=null?Yr:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(xr=t["--persona-dropdown-item-hover-bg"])!=null?xr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(t["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(t["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(t["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(t["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(t["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(t["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let dt=(Un=is(n,ye.toolbarBackground))!=null?Un:ye.toolbarBackground;t["--persona-artifact-toolbar-bg"]=dt}}return t}var Of={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Ou=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Bi=()=>{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"},_f=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Bi()},$f=n=>_f(n),Uf=n=>Wo(n),qf=n=>{var t;let e=Wo(void 0,{validate:!1});return Wo({...n,palette:{...e.palette,colors:{...Of.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ra=n=>{let e=$f(n),t=Ou(n==null?void 0:n.theme),r=Ou(n==null?void 0:n.darkTheme);return e==="dark"?qf(Us(t!=null?t:{},r!=null?r:{})):Uf(t)},zf=n=>Fu(n),ls=(n,e)=>{let t=Ra(e),r=zf(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},_u=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Bi())});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(Bi());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 $u=require("idiomorph"),Ha=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;$u.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 Uu=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Ba={index:-1,draft:""};function qu(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:{...Ba}}}function zu(n,e){var t,r,o,s,a,i,d,c,m,f,g,u,v,x,I,M,E,F,L,R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re,X,ie;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(m=(c=n.llmContent)==null?void 0:c.length)!=null?m:0,(g=(f=n.approval)==null?void 0:f.status)!=null?g:"",(v=(u=n.toolCall)==null?void 0:u.status)!=null?v:"",(I=(x=n.toolCall)==null?void 0:x.name)!=null?I:"",(F=(E=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:E.length)!=null?F:0,(W=(A=(R=(L=n.toolCall)==null?void 0:L.chunks)==null?void 0:R[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?W:"",typeof((N=n.toolCall)==null?void 0:N.args)=="string"?n.toolCall.args.length:(D=n.toolCall)!=null&&D.args?JSON.stringify(n.toolCall.args).length:0,(V=(j=(k=n.reasoning)==null?void 0:k.chunks)==null?void 0:j.length)!=null?V:0,(xe=(Ue=(Re=(ne=n.reasoning)==null?void 0:ne.chunks)==null?void 0:Re[n.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?xe:0,(ve=(Se=(_e=(Ie=n.reasoning)==null?void 0:Ie.chunks)==null?void 0:_e[n.reasoning.chunks.length-1])==null?void 0:Se.slice(-32))!=null?ve:"",(X=(re=n.contentParts)==null?void 0:re.length)!=null?X:0,(ie=n.stopReason)!=null?ie:"",e].join("\0")}function ju(){return new Map}function Vu(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Ku(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Gu(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Da(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function zr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function Ro(n,e){return zr(n)-n.scrollTop<=e}function Na(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,m=t-r;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:t}:!e&&o&&(!c||m>0)?{action:"resume",delta:m,nextLastScrollTop:t}:e&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:m,nextLastScrollTop:t}:{action:"none",delta:m,nextLastScrollTop:t}}function Fa(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function Qu(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function Xu(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Ju(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,co=wn+1;var qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},jf=["pre","code","a","script","style"],Oa=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:qs.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:qs.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:qs.speed,duration:(o=n==null?void 0:n.duration)!=null?o:qs.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:qs.buffer}},Vf=[{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"}],Zu=new Map;for(let n of Vf)Zu.set(n.name,n);var zs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Zu.get(n))!=null?r:null},_a=(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},Kf=(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},Gf=(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},Di=/\s/,Qf=(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},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=0;for(;i<s.length;)if(Di.test(s[i])){let c=i;for(;c<s.length&&Di.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let m=i;for(;m<s.length&&!Di.test(s[m]);)c.appendChild(Kf(r,s[m],e,t.value)),t.value+=1,m+=1;a.appendChild(c),i=m}o.replaceChild(a,n)},Jf=(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(Gf(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},js=(n,e,t,r)=>{var f,g;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:jf).map(u=>u.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Qf(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},m=e==="char"?Xf:Jf;for(let u of i)m(u,t,c);return o.innerHTML},$a=(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},Vs=(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},Yu=new WeakMap,Yf=(n,e)=>{var s;if(!n.styles)return;let t=Yu.get(e);if(t||(t=new Set,Yu.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)},Ni=new WeakMap,Zf=(n,e)=>{if(!n.onAttach)return;let t=Ni.get(e);if(t||(t=new Map,Ni.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},em=n=>{let e=Ni.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Fi=(n,e)=>{Yf(n,e),Zf(n,e)};function Oi(n,e=wn){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 Ks=0,po=null;function _i(n=document){var t;if(Ks++,Ks===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;po={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,Ks=Math.max(0,Ks-1),Ks===0&&po)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=po.originalOverflow,o.style.position=po.originalPosition,o.style.top=po.originalTop,o.style.width=po.originalWidth,s.scrollTo(0,po.scrollY),po=null}}}var Gs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},gn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},Qs=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},gr=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:Gs.side,width:(o=e==null?void 0:e.width)!=null?o:Gs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Gs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Gs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Gs.maxHeight}};var fr={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var eh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ua=(n,e={})=>{var I,M,E,F,L,R;let{showClose:t=!0,wrapperClassName:r=eh,buttonSize:o,iconSize:s="28px"}=e,a=(I=n==null?void 0:n.launcher)!=null?I:{},i=(M=o!=null?o:a.closeButtonSize)!=null?M:"32px",d=b("div",r),c=(E=a.closeButtonTooltipText)!=null?E:"Close chat",m=(F=a.closeButtonShowTooltip)!=null?F:!0,f=(L=a.closeButtonIconName)!=null?L:"x",g=(R=a.closeButtonIconText)!=null?R:"\xD7",u=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Mt("button",{className:Ls("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!u&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||Pn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:u?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=Ae(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),m&&c){let A=null,W=()=>{if(A)return;let D=v.ownerDocument,k=D.body;if(!k)return;A=Lr(D,"div","persona-clear-chat-tooltip"),A.textContent=c;let j=Lr(D,"div");j.className="persona-clear-chat-tooltip-arrow",A.appendChild(j);let V=v.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(co),A.style.left=`${V.left+V.width/2}px`,A.style.top=`${V.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",W),d.addEventListener("mouseleave",N),v.addEventListener("focus",W),v.addEventListener("blur",N),d._cleanupTooltip=()=>{N(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",N),v.removeEventListener("focus",W),v.removeEventListener("blur",N)}}return{button:v,wrapper:d}},th="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",qa=(n,e={})=>{var A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e;let{wrapperClassName:t=th,buttonSize:r,iconSize:o="20px"}=e,a=(W=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?W:{},i=(N=r!=null?r:a.size)!=null?N:"32px",d=(D=a.iconName)!=null?D:"refresh-cw",c=(k=a.iconColor)!=null?k:"",m=(j=a.backgroundColor)!=null?j:"",f=(V=a.borderWidth)!=null?V:"",g=(ne=a.borderColor)!=null?ne:"",u=(Re=a.borderRadius)!=null?Re:"",v=(Ue=a.paddingX)!=null?Ue:"",x=(xe=a.paddingY)!=null?xe:"",I=(Ie=a.tooltipText)!=null?Ie:"Clear chat",M=(_e=a.showTooltip)!=null?_e:!0,E=b("div",t),F=!!(f||g),L=Mt("button",{className:Ls("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!m&&"hover:persona-bg-gray-100",!F&&"persona-border-none",!u&&"persona-rounded-full"),attrs:{type:"button","aria-label":I},style:{height:i,width:i,color:c||Pn.actionIconColor,backgroundColor:m||void 0,border:F?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:u||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),R=Ae(d,o,"currentColor",1);if(R&&(R.style.display="block",L.appendChild(R)),E.appendChild(L),M&&I){let Se=null,ve=()=>{if(Se)return;let X=L.ownerDocument,ie=X.body;if(!ie)return;Se=Lr(X,"div","persona-clear-chat-tooltip"),Se.textContent=I;let he=Lr(X,"div");he.className="persona-clear-chat-tooltip-arrow",Se.appendChild(he);let oe=L.getBoundingClientRect();Se.style.position="fixed",Se.style.zIndex=String(co),Se.style.left=`${oe.left+oe.width/2}px`,Se.style.top=`${oe.top-8}px`,Se.style.transform="translate(-50%, -100%)",ie.appendChild(Se)},re=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};E.addEventListener("mouseenter",ve),E.addEventListener("mouseleave",re),L.addEventListener("focus",ve),L.addEventListener("blur",re),E._cleanupTooltip=()=>{re(),E.removeEventListener("mouseenter",ve),E.removeEventListener("mouseleave",re),L.removeEventListener("focus",ve),L.removeEventListener("blur",re)}}return{button:L,wrapper:E}};var Pn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ho=n=>{var R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve;let{config:e,showClose:t=!0}=n,r=Mt("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=(N=o.headerIconHidden)!=null?N:!1,d=o.headerIconName,c=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,X=Ae(d,re*.6,"currentColor",1);X?c.replaceChildren(X):c.textContent=(k=(D=e==null?void 0:e.launcher)==null?void 0:D.agentIconText)!=null?k:"\u{1F4AC}"}else if((j=e==null?void 0:e.launcher)!=null&&j.iconUrl){let re=b("img");re.src=e.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(ne=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?ne:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Mt("span",{className:"persona-text-base persona-font-semibold",text:(Ue=(Re=e==null?void 0:e.launcher)==null?void 0:Re.title)!=null?Ue:"Chat Assistant",style:{color:Pn.titleColor}}),g=Mt("span",{className:"persona-text-xs",text:(Ie=(xe=e==null?void 0:e.launcher)==null?void 0:xe.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:Pn.subtitleColor}});m.append(f,g),i?r.append(m):r.append(c,m);let u=(_e=o.clearChat)!=null?_e:{},v=(Se=u.enabled)!=null?Se:!0,x=(ve=u.placement)!=null?ve:"inline",I=null,M=null;if(v){let X=qa(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=X.button,M=X.wrapper,x==="top-right"&&(M.style.right="48px"),x==="inline"&&r.appendChild(M)}let E=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:L}=Ua(e,{showClose:t,wrapperClassName:E});return a!=="top-right"&&r.appendChild(L),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:g,closeButton:F,closeButtonWrapper:L,clearChatButton:I,clearChatButtonWrapper:M}},Xs=(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 cs(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(co)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of e){if(u.dividerBefore){let I=document.createElement("hr");a.appendChild(I)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let I=Ae(u.icon,16,"currentColor",1.5);I&&v.appendChild(I)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",I=>{I.stopPropagation(),m(),t(u.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&m()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():m()}function g(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:m,toggle:f,destroy:g}}function Cn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=Ae(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[m,f]of Object.entries(i))d.setAttribute(m,f);return d}function $i(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let m=b("button",c);if(m.type="button",m.setAttribute("aria-label",t),e){let g=Ae(e,s!=null?s:14,"currentColor",2);g&&m.appendChild(g)}let f=b("span");if(f.textContent=t,m.appendChild(f),i&&m.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))m.setAttribute(g,u);return m}function tm(n){var u,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let m=b("span","persona-combo-btn-label");m.textContent=e,c.appendChild(m);let f=Ae(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var x,I;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(I=d.border)!=null?I:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=cs({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",x=>{x.stopPropagation();let I=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",I?"false":"true"),g.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{m.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var nh=n=>{var r;let e=Ho({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 rh(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Ae(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=cs({items:a.menuItems,onSelect:m=>t==null?void 0:t(m),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",m=>{m.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var oh=n=>{var E,F,L,R,A,W,N,D,k;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,m;if(d)c=tm({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Pn.titleColor,m=(L=c.querySelector(".persona-combo-btn-label"))!=null?L:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Pn.titleColor,m.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(m),rh(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 V=o.onTitleClick;c.addEventListener("click",ne=>{ne.target.closest("button")||V()}),c.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let j=o==null?void 0:o.titleRowHover;j&&(c.style.borderRadius=(W=j.borderRadius)!=null?W:"10px",c.style.padding=(N=j.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 V,ne;c.style.backgroundColor=(V=j.background)!=null?V:"",c.style.borderColor=(ne=j.border)!=null?ne:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(D=a.closeButtonSize)!=null?D:"32px",g=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=f,u.style.width=f,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=t?"":"none",u.style.color=a.closeButtonColor||Pn.actionIconColor;let v=(k=a.closeButtonIconName)!=null?k:"x",x=Ae(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let I=b("div");I.style.display="none";let M=b("span");return M.style.display="none",{header:i,iconHolder:I,headerTitle:m,headerSubtitle:M,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},nm={default:nh,minimal:oh},sh=n=>{var e;return(e=nm[n])!=null?e:nm.default},za=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),m=b("div");m.style.display="none";let f=b("span"),g=b("span"),u=b("button");u.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:m,headerTitle:f,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=sh(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 ja=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}},Va=n=>{var R,A,W,N,D,k,j,V,ne,Re,Ue,xe;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=(N=e.stopIconName)!=null?N:"square",a=(D=e.tooltipText)!=null?D:"Send message",i=(k=e.stopTooltipText)!=null?k:"Stop generating",d=(V=(j=n==null?void 0:n.copy)==null?void 0:j.sendButtonLabel)!=null?V:"Send",c=(Re=(ne=n==null?void 0:n.copy)==null?void 0:ne.stopButtonLabel)!=null?Re:"Stop",m=(Ue=e.showTooltip)!=null?Ue:!1,f=(xe=e.size)!=null?xe:"40px",g=e.backgroundColor,u=e.textColor,v=b("div","persona-send-button-wrapper"),x=Mt("button",{className:Ls("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!g&&"persona-bg-persona-primary",!t&&!u&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?f:void 0,height:t?f:void 0,minWidth:t?f:void 0,minHeight:t?f:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?u||"var(--persona-button-primary-fg, #ffffff)":u||void 0,backgroundColor:t&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),I=null,M=null;if(t){let Ie=parseFloat(f)||24,_e=(u==null?void 0:u.trim())||"currentColor";o?(I=Ae(o,Ie,_e,2),I?x.appendChild(I):x.textContent=r):x.textContent=r,M=Ae(s,Ie,_e,2)}else x.textContent=d;let E=null;m&&a&&(E=b("div","persona-send-button-tooltip"),E.textContent=a,v.appendChild(E)),x.setAttribute("aria-label",a),v.appendChild(x);let F="send";return{button:x,wrapper:v,setMode:Ie=>{if(Ie===F)return;F=Ie;let _e=Ie==="stop"?i:a;if(x.setAttribute("aria-label",_e),E&&(E.textContent=_e),t){if(I&&M){let Se=Ie==="stop"?M:I;x.replaceChildren(Se)}}else x.textContent=Ie==="stop"?c:d}}},Ka=n=>{var E,F,L,R,A,W,N,D,k,j,V,ne;let e=(E=n==null?void 0:n.voiceRecognition)!=null?E:{};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=(L=n==null?void 0:n.sendButton)==null?void 0:L.size)!=null?R:"40px",i=(A=e.iconName)!=null?A:"mic",d=(W=e.iconSize)!=null?W:a,c=parseFloat(d)||24,m=(D=e.backgroundColor)!=null?D:(N=n==null?void 0:n.sendButton)==null?void 0:N.backgroundColor,f=(j=e.iconColor)!=null?j:(k=n==null?void 0:n.sendButton)==null?void 0:k.textColor,g=b("div","persona-send-button-wrapper"),u=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:m||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),x=Ae(i,c,f||"currentColor",1.5);x?u.appendChild(x):u.textContent="\u{1F3A4}",g.appendChild(u);let I=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((ne=e.showTooltip)!=null?ne:!1)&&I){let Re=b("div","persona-send-button-tooltip");Re.textContent=I,g.appendChild(Re)}return{button:u,wrapper:g}},Ga=n=>{var v,x,I,M,E,F,L,R;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(I=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?I:"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=((M=e.allowedTypes)!=null?M:Ur).join(","),o.multiple=((E=e.maxFiles)!=null?E: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"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(L=e.buttonTooltipText)!=null?L:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});m.addEventListener("mouseenter",()=>{m.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),m.addEventListener("mouseleave",()=>{m.style.backgroundColor="transparent"});let f=Ae(s,d,"currentColor",1.5);f?m.appendChild(f):m.textContent="\u{1F4CE}",m.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(m);let g=(R=e.buttonTooltipText)!=null?R:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=g,c.appendChild(u),{button:m,wrapper:c,input:o,previewsContainer:r}},Qa=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},Xa=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ja=n=>{var v,x,I,M,E,F;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa(),o=Mt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ja(e);a();let i=Va(e),d=Ka(e),c=Ga(e),m=Qa(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),f.append(g,u),o.append(f),o.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,m),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:m,attachmentButton:(I=c==null?void 0:c.button)!=null?I:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:f,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var rm=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=Ae("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=Ae("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},om=n=>{var v,x,I,M,E,F;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa();r.style.display="none";let o=Qa(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ja(e);s.style.maxHeight="100px",a();let i=Va(e),d=Ka(e),c=Ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let m=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),m.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&m.append(c.input),m.append(f,s,g),c&&t.append(c.previewsContainer),t.append(m,r,o);let u=m;return{footer:t,suggestions:r,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(I=c==null?void 0:c.button)!=null?I:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var sm=n=>{var m,f,g,u,v,x,I,M,E,F,L,R,A,W,N,D,k;let e=(f=(m=n==null?void 0:n.launcher)==null?void 0:m.enabled)!=null?f:!0,t=gn(n);if(Qs(n)){let j=(u=(g=n==null?void 0:n.launcher)==null?void 0:g.composerBar)!=null?u:{},V=b("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",V.style.zIndex=String((I=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?I:wn);let ne=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let Re=b("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(M=j.expandedSize)!=null?M:"anchored",Re.style.zIndex=String((F=(E=n==null?void 0:n.launcher)==null?void 0:E.zIndex)!=null?F:wn),{wrapper:V,panel:ne,pillRoot:Re}}if(t){let j=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(V),{wrapper:j,panel:V}}if(!e){let j=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(R=(L=n==null?void 0:n.launcher)==null?void 0:L.width)!=null?R:"100%";return j.style.width=ne,V.style.width="100%",j.appendChild(V),{wrapper:j,panel:V}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((N=(W=n==null?void 0:n.launcher)==null?void 0:W.zIndex)!=null?N:wn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(D=n==null?void 0:n.launcher)==null?void 0:D.width)!=null?k:n==null?void 0:n.launcherWidth,c=d!=null?d:qr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},ah=(n,e)=>{var L,R,A,W,N,D,k,j,V;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}=Ua(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=(L=n==null?void 0:n.launcher)==null?void 0:L.clearChat)==null?void 0:R.enabled)!=null?A:!0,a=null,i=null;if(s){let ne=qa(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let m=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(W=n==null?void 0:n.copy)==null?void 0:W.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),f=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(D=n==null?void 0:n.copy)==null?void 0:D.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),g=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},m,f),u=b("div","persona-flex persona-flex-col persona-gap-3"),v=(j=n==null?void 0:n.layout)==null?void 0:j.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((V=n==null?void 0:n.copy)==null?void 0:V.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,u);let I=Mt("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=om({config:n}),{root:E,textNode:F}=rm();return t.append(d,o,c,I),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:u,composerOverlay:I,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:m,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("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:E,peekTextNode:F}},am=(n,e=!0)=>{var I,M,E,F,L,R,A,W,N;if(Qs(n))return ah(n,e);let t=Mt("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=(I=n==null?void 0:n.layout)==null?void 0:I.header,o=((M=n==null?void 0:n.layout)==null?void 0:M.showHeader)!==!1,s=r?za(n,r,{showClose:e}):Ho({config:n,showClose:e}),a=Mt("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=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(E=n==null?void 0:n.copy)==null?void 0:E.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:gn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),m=b("div","persona-flex persona-flex-col persona-gap-3"),f=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;f&&(m.style.maxWidth=f,m.style.marginLeft="auto",m.style.marginRight="auto",m.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,m);let u=Ja({config:n}),v=((N=n==null?void 0:n.layout)==null?void 0:N.showFooter)!==!1;o?Xs(t,s,n):(s.header.style.display="none",Xs(t,s,n)),t.append(a);let x=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(u.footer.style.display="none"),t.append(u.footer),t.append(x),{container:t,body:a,messagesWrapper:m,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Ui=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
18
+ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]}),Hu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,Bu=n=>Jo(n)||n===$r,Ia=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 Os(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,m,f;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,u=!!(g!=null&&g.name)&&(Jo(g.name)||g.name===$r&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&u&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(m=this.callbacks).onError)==null||f.call(m,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ds(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||Hi().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 Wi((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=as.isSupported()?new as({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,m=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&m)return Hi().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:u})=>{let v=new g({host:d,agentId:c,clientToken:m,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&t?new u(v,t,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&t)return m&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ss(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let m=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=m.id}if(c){this.pendingVoiceUserMessageId=null;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let m=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=m.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,m,f;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((m=e.browser)==null?void 0:m.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Bf(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 Ds(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:m,rawContent:f}=e,u={id:a!=null?a:t==="user"?Ta():t==="assistant"?Ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};return this.upsertMessage(u),u}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:m,streaming:f=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:o==="user"?Ta():o==="assistant"?Ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,m,f,g,u;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Ta(),s=Ns(),a={id:o,role:"user",content:r||Ma,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 I=Ru(v,this.config.errorMessage);if(I){let M={id:s,role:"assistant",createdAt:new Date().toISOString(),content:I,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(m=this.callbacks).onError)==null||f.call(m,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Ns();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){let m=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!m){let f=Ru(c,this.config.errorMessage);if(f){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var m,f,g,u,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(m=a==null?void 0:a.createdAt)!=null?m:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(c?x=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),x){let I=null;if(x instanceof Response){if(!x.ok){let M=await x.json().catch(()=>null);throw new Error((g=M==null?void 0:M.error)!=null?g:`Approval request failed: ${x.status}`)}I=x.body}else x instanceof ReadableStream&&(I=x);I?await this.connectStream(I,{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 I=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(v=(u=this.callbacks).onError)==null||v.call(u,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var m,f,g,u,v,x,I,M,E,F,L,R;let r=this.messages.find(A=>A.id===e.id);if(((m=r==null?void 0:r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let 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 N=typeof((I=W[0])==null?void 0:I.question)=="string"?W[0].question:"";N&&(a={[N]:t})}}this.markAskUserQuestionResolved(e,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(E=e.toolCall)==null?void 0:E.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,N])=>`${W}: ${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((W,N)=>{let D=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!D)return;let k=A[D],j=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${N}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${N}`,role:"user",content:j||"*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=(L=this.callbacks).onError)==null||R.call(L,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)!==$r)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,m,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async g=>{var R,A,W,N,D,k,j;let u=(R=g.toolCall)==null?void 0:R.name,v=(A=g.toolCall)==null?void 0:A.id;if(!u||!v)return null;let x=`${e}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let I=this.markWebMcpToolRunning(g),M=(N=(W=g.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?N:u;if(u===$r)return{dedupeKey:x,resumeKey:M,output:Ti(),toolMessage:g,startedAt:I,completedAt:Date.now()};let E=new AbortController;this.webMcpResolveControllers.add(E),o.push(E);let F=this.client.executeWebMcpToolCall(u,(D=g.toolCall)==null?void 0:D.args,E.signal),L;if(!F)L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{L=await F}catch(V){let ne=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return ne||(j=(k=this.callbacks).onError)==null||j.call(k,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(g,_s(ne?"Aborted by cancel()":Hu(V)),I),this.webMcpInflightKeys.delete(x),null}return E.signal.aborted?(this.markWebMcpToolComplete(g,_s("Aborted by cancel()"),I),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:M,output:L,toolMessage:g,startedAt:I,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let u=await this.client.resumeFlow(e,g,{signal:s.signal});if(!u.ok){let v=await u.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${u.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===$r?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(f=(m=this.callbacks).onError)==null||f.call(m,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,_s("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,x,I,M,E,F,L,R,A,W,N,D;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(x=e.toolCall)==null?void 0:x.name,o=(I=e.toolCall)==null?void 0:I.id;if(!t){(E=(M=this.callbacks).onError)==null||E.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let k=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);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(k)}catch(j){(L=(F=this.callbacks).onError)==null||L.call(F,j instanceof Error?j:new Error(String(j)))}finally{this.webMcpInflightKeys.delete(k)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===$r,m=(R=e.toolCall)==null?void 0:R.args,f=c?null:this.client.executeWebMcpToolCall(r,m,d),g="execute",u=a;try{let k;if(c?k=Ti():f?k=await f:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),d.aborted){this.markWebMcpToolComplete(e,_s("Aborted by cancel()"),a);return}let j=(W=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?W:r;g="resume",await this.resumeWithToolOutput(t,j,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,k,a,u,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let j=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(g==="execute"||j||d.aborted)&&this.markWebMcpToolComplete(e,_s(j||d.aborted?"Aborted by cancel()":Hu(k)),a),j||(D=(N=this.callbacks).onError)==null||D.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(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=Ri(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ka(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Ri(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var m,f,g,u,v,x,I,M,E,F,L,R,A,W,N;if(s!==r)return o;let a={...o,...t};if(((m=o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let D=o.approval,k=t.approval;a.approval={...D,...k,executionId:k.executionId||D.executionId,toolName:k.toolName||D.toolName,description:k.description||D.description,toolType:(u=k.toolType)!=null?u:D.toolType,reason:(v=k.reason)!=null?v:D.reason,parameters:(x=k.parameters)!=null?x:D.parameters}}let i=(I=t.toolCall)==null?void 0:I.name,d=(M=t.agentMetadata)==null?void 0:M.executionId,c=(E=t.toolCall)==null?void 0:E.id;if(i&&Bu(i)&&d&&c&&((F=t.agentMetadata)==null?void 0:F.awaitingLocalTool)===!0){let D=`${d}:${c}`,k=this.webMcpInflightKeys.has(D),j=this.webMcpResolvedKeys.has(D),V=(L=o.toolCall)==null?void 0:L.name,ne=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&V!==void 0&&Bu(V)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(k||j||ne)&&(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(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 C=require("lucide"),Df={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},Ae=(n,e=24,t="currentColor",r=2)=>{let o=Df[n];return o?Nf(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 Nf(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,m])=>{c!=="stroke"&&d.setAttribute(c,String(m))}),o.appendChild(d)}),o}var Wa={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function Ff(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Of(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 $s=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Wa.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Wa.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Wa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Wa.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let m=Au(c,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let f=(o=m.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await Cu(c),g=Ea(c)?URL.createObjectURL(c):null,u={id:Ff(),file:c,previewUrl:g,contentPart:f};this.attachments.push(u),this.renderPreview(u)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Ea(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=Of(e.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Su(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Du=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Us(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];Du(s)&&Du(o)?t[r]=Us(s,o):t[r]=o}return t}var qr="min(440px, calc(100vw - 24px))",Fu="440px",_f={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:qr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:_f,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 Nu(n,e){if(!(!n&&!e))return n?e?Us(n,e):n:e}function Ou(n){var e,t,r,o,s,a,i,d,c,m,f,g,u,v,x,I,M,E,F,L,R;return n?{...Nt,...n,theme:Nu(Nt.theme,n.theme),darkTheme:Nu(Nt.darkTheme,n.darkTheme),launcher:{...Nt.launcher,...n.launcher,dock:{...(e=Nt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Nt.copy,...n.copy},sendButton:{...Nt.sendButton,...n.sendButton},statusIndicator:{...Nt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,X,ie,he,oe,K,te,qe,Y,le;let A=(re=Nt.features)==null?void 0:re.artifacts,W=(X=n.features)==null?void 0:X.artifacts,N=(ie=Nt.features)==null?void 0:ie.scrollToBottom,D=(he=n.features)==null?void 0:he.scrollToBottom,k=(oe=Nt.features)==null?void 0:oe.scrollBehavior,j=(K=n.features)==null?void 0:K.scrollBehavior,V=(te=Nt.features)==null?void 0:te.streamAnimation,ne=(qe=n.features)==null?void 0:qe.streamAnimation,Re=(Y=Nt.features)==null?void 0:Y.askUserQuestion,Ue=(le=n.features)==null?void 0:le.askUserQuestion,xe=A===void 0&&W===void 0?void 0:{...A,...W,layout:{...A==null?void 0:A.layout,...W==null?void 0:W.layout}},Ie=N===void 0&&D===void 0?void 0:{...N,...D},_e=k===void 0&&j===void 0?void 0:{...k,...j},Se=V===void 0&&ne===void 0?void 0:{...V,...ne},ve=Re===void 0&&Ue===void 0?void 0:{...Re,...Ue,styles:{...Re==null?void 0:Re.styles,...Ue==null?void 0:Ue.styles}};return{...Nt.features,...n.features,...Ie!==void 0?{scrollToBottom:Ie}:{},..._e!==void 0?{scrollBehavior:_e}:{},...xe!==void 0?{artifacts:xe}:{},...Se!==void 0?{streamAnimation:Se}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Nt.layout,...n.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(m=Nt.layout)==null?void 0:m.messages)==null?void 0:f.avatar,...(u=(g=n.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(M=(I=n.layout)==null?void 0:I.messages)==null?void 0:M.timestamp}},slots:{...(E=Nt.layout)==null?void 0:E.slots,...(F=n.layout)==null?void 0:F.slots}},markdown:{...Nt.markdown,...n.markdown,options:{...(L=Nt.markdown)==null?void 0:L.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...Nt.messageActions,...n.messageActions}}:Nt}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"},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"}},Uf={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"}},qf={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:qr,maxWidth:Fu,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 is(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."))?is(n,r):r}function _u(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=is(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 zf(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 $u(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]=$u(s,o):t[r]=o}return t}function jf(n,e){return e?$u(n,e):n}function Wo(n,e={}){var o,s,a,i,d,c,m,f,g,u,v,x,I;let t={palette:$f,semantic:Uf,components:qf},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(m=n==null?void 0:n.semantic)==null?void 0:m.colors,interactive:{...t.semantic.colors.interactive,...(g=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(u=n==null?void 0:n.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(I=n==null?void 0:n.semantic)==null?void 0:I.typography}},components:jf(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let M=zf(r);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(E=>E.message).join(", ")}`)}if(e.plugins)for(let M of e.plugins)r=M.transform(r);return r}function Uu(n){var x,I,M,E,F,L,R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re,X,ie,he,oe,K,te,qe,Y,le,Pe,it,lt,rt,Ee,pe,Xe,J,ce,we,je,Pt,Te,me,fn,It,rn,hr,hn,Ve,T,ue,Le,Me,He,Ze,Ge,ut,Wt,q,ot,G,de,ke,vt,Yt,Zt,pn,Ht,et,Rt,ct,Kt,Jn,An,en,In,yr,xt,Nn,br,Pr,ir,yt,uo,vr,mo,Wn,No,jr,Ir,Vr,Kr,go,fo,Gr,Ct,Fn,On,Sn,St,Yn,Zn,_n,Qr,Wr,Xr,$n,Bt,Tn,er,Jr,Rr,Yr,xr,Un;let e=_u(n),t={};for(let[ye,dt]of Object.entries(e)){let Qt=ye.replace(/\./g,"-");t[`--persona-${Qt}`]=dt.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(I=t["--persona-semantic-colors-secondary"])!=null?I:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(M=t["--persona-semantic-colors-accent"])!=null?M:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(E=t["--persona-semantic-colors-surface"])!=null?E: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"]=(L=t["--persona-semantic-colors-container"])!=null?L: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"]=(N=t["--persona-semantic-colors-border"])!=null?N:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(D=t["--persona-semantic-colors-divider"])!=null?D:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(k=t["--persona-components-voice-recording-indicator"])!=null?k:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(j=t["--persona-components-voice-recording-background"])!=null?j:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Re=t["--persona-components-approval-requested-background"])!=null?Re:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Ue=t["--persona-components-approval-requested-border"])!=null?Ue:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(xe=t["--persona-components-approval-requested-text"])!=null?xe:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Ie=t["--persona-components-approval-requested-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(_e=t["--persona-components-approval-approve-background"])!=null?_e:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Se=t["--persona-components-approval-deny-background"])!=null?Se:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ve=t["--persona-components-attachment-image-background"])!=null?ve:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(re=t["--persona-components-attachment-image-border"])!=null?re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(X=t["--persona-semantic-typography-fontFamily"])!=null?X:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ie=t["--persona-semantic-typography-fontSize"])!=null?ie:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(he=t["--persona-semantic-typography-fontWeight"])!=null?he:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(oe=t["--persona-semantic-typography-lineHeight"])!=null?oe: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"]=(te=t["--persona-palette-radius-md"])!=null?te:"0.375rem",t["--persona-radius-lg"]=(qe=t["--persona-palette-radius-lg"])!=null?qe:"0.5rem",t["--persona-radius-xl"]=(Y=t["--persona-palette-radius-xl"])!=null?Y:"0.75rem",t["--persona-radius-full"]=(le=t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-launcher-radius"]=(it=(Pe=t["--persona-components-launcher-borderRadius"])!=null?Pe: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"]=(rt=t["--persona-components-launcher-foreground"])!=null?rt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(Ee=t["--persona-components-launcher-border"])!=null?Ee:t["--persona-border"],t["--persona-button-primary-bg"]=(pe=t["--persona-components-button-primary-background"])!=null?pe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Xe=t["--persona-components-button-primary-foreground"])!=null?Xe:t["--persona-text-inverse"],t["--persona-button-radius"]=(ce=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?ce:"9999px",t["--persona-panel-radius"]=(je=(we=t["--persona-components-panel-borderRadius"])!=null?we:t["--persona-radius-xl"])!=null?je:"0.75rem",t["--persona-panel-border"]=(Pt=t["--persona-components-panel-border"])!=null?Pt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(me=(Te=t["--persona-components-panel-shadow"])!=null?Te:t["--persona-palette-shadows-xl"])!=null?me:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(fn=t["--persona-components-launcher-shadow"])!=null?fn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(rn=(It=t["--persona-components-input-borderRadius"])!=null?It:t["--persona-radius-lg"])!=null?rn:"0.5rem",t["--persona-message-user-radius"]=(hn=(hr=t["--persona-components-message-user-borderRadius"])!=null?hr:t["--persona-radius-lg"])!=null?hn:"0.5rem",t["--persona-message-assistant-radius"]=(T=(Ve=t["--persona-components-message-assistant-borderRadius"])!=null?Ve:t["--persona-radius-lg"])!=null?T:"0.5rem",t["--persona-header-bg"]=(ue=t["--persona-components-header-background"])!=null?ue:t["--persona-surface"],t["--persona-header-border"]=(Le=t["--persona-components-header-border"])!=null?Le:t["--persona-divider"],t["--persona-header-icon-bg"]=(Me=t["--persona-components-header-iconBackground"])!=null?Me:t["--persona-primary"],t["--persona-header-icon-fg"]=(He=t["--persona-components-header-iconForeground"])!=null?He:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ze=t["--persona-components-header-titleForeground"])!=null?Ze:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ge=t["--persona-components-header-subtitleForeground"])!=null?Ge:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ut=t["--persona-components-header-actionIconForeground"])!=null?ut:t["--persona-muted"];let r=(Wt=n.components)==null?void 0:Wt.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(q=n.components)==null?void 0:q.introCard;t["--persona-intro-card-bg"]=(ot=t["--persona-components-introCard-background"])!=null?ot:t["--persona-surface"],t["--persona-intro-card-radius"]=(G=t["--persona-components-introCard-borderRadius"])!=null?G:"1rem",t["--persona-intro-card-padding"]=(de=t["--persona-components-introCard-padding"])!=null?de:"1.5rem",t["--persona-intro-card-shadow"]=(vt=(ke=o==null?void 0:o.shadow)!=null?ke:t["--persona-components-introCard-shadow"])!=null?vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Yt=t["--persona-components-input-background"])!=null?Yt:t["--persona-surface"],t["--persona-input-placeholder"]=(Zt=t["--persona-components-input-placeholder"])!=null?Zt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(pn=t["--persona-components-message-user-background"])!=null?pn:t["--persona-accent"],t["--persona-message-user-text"]=(Ht=t["--persona-components-message-user-text"])!=null?Ht:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(et=t["--persona-components-message-user-shadow"])!=null?et:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Rt=t["--persona-components-message-assistant-background"])!=null?Rt:t["--persona-surface"],t["--persona-message-assistant-text"]=(ct=t["--persona-components-message-assistant-text"])!=null?ct:t["--persona-text"],t["--persona-message-assistant-border"]=(Kt=t["--persona-components-message-assistant-border"])!=null?Kt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Jn=t["--persona-components-message-assistant-shadow"])!=null?Jn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(en=(An=t["--persona-components-scrollToBottom-background"])!=null?An:t["--persona-button-primary-bg"])!=null?en:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(yr=(In=t["--persona-components-scrollToBottom-foreground"])!=null?In:t["--persona-button-primary-fg"])!=null?yr: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"]=(Nn=t["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",t["--persona-scroll-to-bottom-radius"]=(ir=(Pr=(br=t["--persona-components-scrollToBottom-borderRadius"])!=null?br:t["--persona-button-radius"])!=null?Pr:t["--persona-radius-full"])!=null?ir:"9999px",t["--persona-scroll-to-bottom-shadow"]=(uo=(yt=t["--persona-components-scrollToBottom-shadow"])!=null?yt:t["--persona-palette-shadows-sm"])!=null?uo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(vr=t["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(mo=t["--persona-components-scrollToBottom-gap"])!=null?mo:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(No=(Wn=t["--persona-components-scrollToBottom-fontSize"])!=null?Wn:t["--persona-palette-typography-fontSize-sm"])!=null?No:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(jr=t["--persona-components-scrollToBottom-iconSize"])!=null?jr:"14px",t["--persona-tool-bubble-shadow"]=(Ir=t["--persona-components-toolBubble-shadow"])!=null?Ir:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Vr=t["--persona-components-reasoningBubble-shadow"])!=null?Vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Kr=t["--persona-components-composer-shadow"])!=null?Kr:"none",t["--persona-md-inline-code-bg"]=(go=t["--persona-components-markdown-inlineCode-background"])!=null?go:t["--persona-container"],t["--persona-md-inline-code-color"]=(fo=t["--persona-components-markdown-inlineCode-foreground"])!=null?fo:t["--persona-text"],t["--persona-md-link-color"]=(Ct=(Gr=t["--persona-components-markdown-link-foreground"])!=null?Gr: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"]=(Fn=t["--persona-components-markdown-codeBlock-background"])!=null?Fn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(On=t["--persona-components-markdown-codeBlock-borderColor"])!=null?On:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Sn=t["--persona-components-markdown-codeBlock-textColor"])!=null?Sn:"inherit",t["--persona-md-table-header-bg"]=(St=t["--persona-components-markdown-table-headerBackground"])!=null?St:t["--persona-container"],t["--persona-md-table-border-color"]=(Yn=t["--persona-components-markdown-table-borderColor"])!=null?Yn:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(_n=t["--persona-components-markdown-blockquote-borderColor"])!=null?_n:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Qr=t["--persona-components-markdown-blockquote-background"])!=null?Qr:"transparent",t["--persona-md-blockquote-text-color"]=(Wr=t["--persona-components-markdown-blockquote-textColor"])!=null?Wr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Xr=t["--persona-components-collapsibleWidget-container"])!=null?Xr:t["--persona-surface"],t["--cw-surface"]=($n=t["--persona-components-collapsibleWidget-surface"])!=null?$n:t["--persona-surface"],t["--cw-border"]=(Bt=t["--persona-components-collapsibleWidget-border"])!=null?Bt:t["--persona-border"],t["--persona-message-border"]=(Tn=t["--persona-components-message-border"])!=null?Tn:t["--persona-border"];let m=n.components,f=m==null?void 0:m.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let g=m==null?void 0:m.labelButton;g&&(g.background&&(t["--persona-label-btn-bg"]=g.background),g.border&&(t["--persona-label-btn-border"]=g.border),g.color&&(t["--persona-label-btn-color"]=g.color),g.padding&&(t["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(t["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(t["--persona-label-btn-gap"]=g.gap));let u=m==null?void 0:m.toggleGroup;u&&(u.gap&&(t["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(t["--persona-toggle-group-radius"]=u.borderRadius));let v=m==null?void 0:m.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,t["--persona-dropdown-bg"]=(er=t["--persona-dropdown-bg"])!=null?er:ye.copyMenuBackground),ye.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,t["--persona-dropdown-border"]=(Jr=t["--persona-dropdown-border"])!=null?Jr:ye.copyMenuBorder),ye.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,t["--persona-dropdown-shadow"]=(Rr=t["--persona-dropdown-shadow"])!=null?Rr:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Yr=t["--persona-dropdown-radius"])!=null?Yr:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(xr=t["--persona-dropdown-item-hover-bg"])!=null?xr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(t["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(t["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(t["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(t["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(t["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(t["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let dt=(Un=is(n,ye.toolbarBackground))!=null?Un:ye.toolbarBackground;t["--persona-artifact-toolbar-bg"]=dt}}return t}var Vf={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"}}},qu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Bi=()=>{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"},Kf=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Bi()},Gf=n=>Kf(n),Qf=n=>Wo(n),Xf=n=>{var t;let e=Wo(void 0,{validate:!1});return Wo({...n,palette:{...e.palette,colors:{...Vf.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ra=n=>{let e=Gf(n),t=qu(n==null?void 0:n.theme),r=qu(n==null?void 0:n.darkTheme);return e==="dark"?Xf(Us(t!=null?t:{},r!=null?r:{})):Qf(t)},Jf=n=>Uu(n),ls=(n,e)=>{let t=Ra(e),r=Jf(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},zu=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Bi())});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(Bi());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 ju=require("idiomorph"),Ha=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;ju.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 Vu=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Ba={index:-1,draft:""};function Ku(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:{...Ba}}}function Gu(n,e){var t,r,o,s,a,i,d,c,m,f,g,u,v,x,I,M,E,F,L,R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re,X,ie;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(m=(c=n.llmContent)==null?void 0:c.length)!=null?m:0,(g=(f=n.approval)==null?void 0:f.status)!=null?g:"",(v=(u=n.toolCall)==null?void 0:u.status)!=null?v:"",(I=(x=n.toolCall)==null?void 0:x.name)!=null?I:"",(F=(E=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:E.length)!=null?F:0,(W=(A=(R=(L=n.toolCall)==null?void 0:L.chunks)==null?void 0:R[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?W:"",typeof((N=n.toolCall)==null?void 0:N.args)=="string"?n.toolCall.args.length:(D=n.toolCall)!=null&&D.args?JSON.stringify(n.toolCall.args).length:0,(V=(j=(k=n.reasoning)==null?void 0:k.chunks)==null?void 0:j.length)!=null?V:0,(xe=(Ue=(Re=(ne=n.reasoning)==null?void 0:ne.chunks)==null?void 0:Re[n.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?xe:0,(ve=(Se=(_e=(Ie=n.reasoning)==null?void 0:Ie.chunks)==null?void 0:_e[n.reasoning.chunks.length-1])==null?void 0:Se.slice(-32))!=null?ve:"",(X=(re=n.contentParts)==null?void 0:re.length)!=null?X:0,(ie=n.stopReason)!=null?ie:"",e].join("\0")}function Qu(){return new Map}function Xu(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Ju(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Yu(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Da(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function zr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function Ro(n,e){return zr(n)-n.scrollTop<=e}function Na(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,m=t-r;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:t}:!e&&o&&(!c||m>0)?{action:"resume",delta:m,nextLastScrollTop:t}:e&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:m,nextLastScrollTop:t}:{action:"none",delta:m,nextLastScrollTop:t}}function Fa(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 Zu(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function em(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 tm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,co=wn+1;var qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Yf=["pre","code","a","script","style"],Oa=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:qs.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:qs.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:qs.speed,duration:(o=n==null?void 0:n.duration)!=null?o:qs.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:qs.buffer}},Zf=[{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"}],rm=new Map;for(let n of Zf)rm.set(n.name,n);var zs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=rm.get(n))!=null?r:null},_a=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
19
+ `);return s<0?"":n.slice(0,s)}return n},eh=(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},th=(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},Di=/\s/,nh=(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},rh=(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(Di.test(s[i])){let c=i;for(;c<s.length&&Di.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let m=i;for(;m<s.length&&!Di.test(s[m]);)c.appendChild(eh(r,s[m],e,t.value)),t.value+=1,m+=1;a.appendChild(c),i=m}o.replaceChild(a,n)},oh=(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(th(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},js=(n,e,t,r)=>{var f,g;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:Yf).map(u=>u.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)nh(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},m=e==="char"?rh:oh;for(let u of i)m(u,t,c);return o.innerHTML},$a=(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},Vs=(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},nm=new WeakMap,sh=(n,e)=>{var s;if(!n.styles)return;let t=nm.get(e);if(t||(t=new Set,nm.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)},Ni=new WeakMap,ah=(n,e)=>{if(!n.onAttach)return;let t=Ni.get(e);if(t||(t=new Map,Ni.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},om=n=>{let e=Ni.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Fi=(n,e)=>{sh(n,e),ah(n,e)};function Oi(n,e=wn){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 Ks=0,po=null;function _i(n=document){var t;if(Ks++,Ks===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;po={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,Ks=Math.max(0,Ks-1),Ks===0&&po)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=po.originalOverflow,o.style.position=po.originalPosition,o.style.top=po.originalTop,o.style.width=po.originalWidth,s.scrollTo(0,po.scrollY),po=null}}}var Gs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},gn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},Qs=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},gr=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:Gs.side,width:(o=e==null?void 0:e.width)!=null?o:Gs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Gs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Gs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Gs.maxHeight}};var fr={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var ih="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ua=(n,e={})=>{var I,M,E,F,L,R;let{showClose:t=!0,wrapperClassName:r=ih,buttonSize:o,iconSize:s="28px"}=e,a=(I=n==null?void 0:n.launcher)!=null?I:{},i=(M=o!=null?o:a.closeButtonSize)!=null?M:"32px",d=b("div",r),c=(E=a.closeButtonTooltipText)!=null?E:"Close chat",m=(F=a.closeButtonShowTooltip)!=null?F:!0,f=(L=a.closeButtonIconName)!=null?L:"x",g=(R=a.closeButtonIconText)!=null?R:"\xD7",u=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Mt("button",{className:Ls("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!u&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||Pn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:u?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=Ae(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),m&&c){let A=null,W=()=>{if(A)return;let D=v.ownerDocument,k=D.body;if(!k)return;A=Lr(D,"div","persona-clear-chat-tooltip"),A.textContent=c;let j=Lr(D,"div");j.className="persona-clear-chat-tooltip-arrow",A.appendChild(j);let V=v.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(co),A.style.left=`${V.left+V.width/2}px`,A.style.top=`${V.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",W),d.addEventListener("mouseleave",N),v.addEventListener("focus",W),v.addEventListener("blur",N),d._cleanupTooltip=()=>{N(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",N),v.removeEventListener("focus",W),v.removeEventListener("blur",N)}}return{button:v,wrapper:d}},lh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",qa=(n,e={})=>{var A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e;let{wrapperClassName:t=lh,buttonSize:r,iconSize:o="20px"}=e,a=(W=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?W:{},i=(N=r!=null?r:a.size)!=null?N:"32px",d=(D=a.iconName)!=null?D:"refresh-cw",c=(k=a.iconColor)!=null?k:"",m=(j=a.backgroundColor)!=null?j:"",f=(V=a.borderWidth)!=null?V:"",g=(ne=a.borderColor)!=null?ne:"",u=(Re=a.borderRadius)!=null?Re:"",v=(Ue=a.paddingX)!=null?Ue:"",x=(xe=a.paddingY)!=null?xe:"",I=(Ie=a.tooltipText)!=null?Ie:"Clear chat",M=(_e=a.showTooltip)!=null?_e:!0,E=b("div",t),F=!!(f||g),L=Mt("button",{className:Ls("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!m&&"hover:persona-bg-gray-100",!F&&"persona-border-none",!u&&"persona-rounded-full"),attrs:{type:"button","aria-label":I},style:{height:i,width:i,color:c||Pn.actionIconColor,backgroundColor:m||void 0,border:F?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:u||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),R=Ae(d,o,"currentColor",1);if(R&&(R.style.display="block",L.appendChild(R)),E.appendChild(L),M&&I){let Se=null,ve=()=>{if(Se)return;let X=L.ownerDocument,ie=X.body;if(!ie)return;Se=Lr(X,"div","persona-clear-chat-tooltip"),Se.textContent=I;let he=Lr(X,"div");he.className="persona-clear-chat-tooltip-arrow",Se.appendChild(he);let oe=L.getBoundingClientRect();Se.style.position="fixed",Se.style.zIndex=String(co),Se.style.left=`${oe.left+oe.width/2}px`,Se.style.top=`${oe.top-8}px`,Se.style.transform="translate(-50%, -100%)",ie.appendChild(Se)},re=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};E.addEventListener("mouseenter",ve),E.addEventListener("mouseleave",re),L.addEventListener("focus",ve),L.addEventListener("blur",re),E._cleanupTooltip=()=>{re(),E.removeEventListener("mouseenter",ve),E.removeEventListener("mouseleave",re),L.removeEventListener("focus",ve),L.removeEventListener("blur",re)}}return{button:L,wrapper:E}};var Pn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ho=n=>{var R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve;let{config:e,showClose:t=!0}=n,r=Mt("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=(N=o.headerIconHidden)!=null?N:!1,d=o.headerIconName,c=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,X=Ae(d,re*.6,"currentColor",1);X?c.replaceChildren(X):c.textContent=(k=(D=e==null?void 0:e.launcher)==null?void 0:D.agentIconText)!=null?k:"\u{1F4AC}"}else if((j=e==null?void 0:e.launcher)!=null&&j.iconUrl){let re=b("img");re.src=e.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(ne=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?ne:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Mt("span",{className:"persona-text-base persona-font-semibold",text:(Ue=(Re=e==null?void 0:e.launcher)==null?void 0:Re.title)!=null?Ue:"Chat Assistant",style:{color:Pn.titleColor}}),g=Mt("span",{className:"persona-text-xs",text:(Ie=(xe=e==null?void 0:e.launcher)==null?void 0:xe.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:Pn.subtitleColor}});m.append(f,g),i?r.append(m):r.append(c,m);let u=(_e=o.clearChat)!=null?_e:{},v=(Se=u.enabled)!=null?Se:!0,x=(ve=u.placement)!=null?ve:"inline",I=null,M=null;if(v){let X=qa(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=X.button,M=X.wrapper,x==="top-right"&&(M.style.right="48px"),x==="inline"&&r.appendChild(M)}let E=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:L}=Ua(e,{showClose:t,wrapperClassName:E});return a!=="top-right"&&r.appendChild(L),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:g,closeButton:F,closeButtonWrapper:L,clearChatButton:I,clearChatButtonWrapper:M}},Xs=(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 cs(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(co)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of e){if(u.dividerBefore){let I=document.createElement("hr");a.appendChild(I)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let I=Ae(u.icon,16,"currentColor",1.5);I&&v.appendChild(I)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",I=>{I.stopPropagation(),m(),t(u.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&m()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():m()}function g(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:m,toggle:f,destroy:g}}function Cn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=Ae(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[m,f]of Object.entries(i))d.setAttribute(m,f);return d}function $i(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let m=b("button",c);if(m.type="button",m.setAttribute("aria-label",t),e){let g=Ae(e,s!=null?s:14,"currentColor",2);g&&m.appendChild(g)}let f=b("span");if(f.textContent=t,m.appendChild(f),i&&m.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))m.setAttribute(g,u);return m}function sm(n){var u,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let m=b("span","persona-combo-btn-label");m.textContent=e,c.appendChild(m);let f=Ae(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var x,I;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(I=d.border)!=null?I:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=cs({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",x=>{x.stopPropagation();let I=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",I?"false":"true"),g.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{m.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var ch=n=>{var r;let e=Ho({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 dh(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Ae(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=cs({items:a.menuItems,onSelect:m=>t==null?void 0:t(m),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",m=>{m.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var ph=n=>{var E,F,L,R,A,W,N,D,k;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,m;if(d)c=sm({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Pn.titleColor,m=(L=c.querySelector(".persona-combo-btn-label"))!=null?L:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Pn.titleColor,m.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(m),dh(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 V=o.onTitleClick;c.addEventListener("click",ne=>{ne.target.closest("button")||V()}),c.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let j=o==null?void 0:o.titleRowHover;j&&(c.style.borderRadius=(W=j.borderRadius)!=null?W:"10px",c.style.padding=(N=j.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 V,ne;c.style.backgroundColor=(V=j.background)!=null?V:"",c.style.borderColor=(ne=j.border)!=null?ne:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(D=a.closeButtonSize)!=null?D:"32px",g=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=f,u.style.width=f,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=t?"":"none",u.style.color=a.closeButtonColor||Pn.actionIconColor;let v=(k=a.closeButtonIconName)!=null?k:"x",x=Ae(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let I=b("div");I.style.display="none";let M=b("span");return M.style.display="none",{header:i,iconHolder:I,headerTitle:m,headerSubtitle:M,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},am={default:ch,minimal:ph},uh=n=>{var e;return(e=am[n])!=null?e:am.default},za=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),m=b("div");m.style.display="none";let f=b("span"),g=b("span"),u=b("button");u.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:m,headerTitle:f,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=uh(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 ja=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}},Va=n=>{var R,A,W,N,D,k,j,V,ne,Re,Ue,xe;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=(N=e.stopIconName)!=null?N:"square",a=(D=e.tooltipText)!=null?D:"Send message",i=(k=e.stopTooltipText)!=null?k:"Stop generating",d=(V=(j=n==null?void 0:n.copy)==null?void 0:j.sendButtonLabel)!=null?V:"Send",c=(Re=(ne=n==null?void 0:n.copy)==null?void 0:ne.stopButtonLabel)!=null?Re:"Stop",m=(Ue=e.showTooltip)!=null?Ue:!1,f=(xe=e.size)!=null?xe:"40px",g=e.backgroundColor,u=e.textColor,v=b("div","persona-send-button-wrapper"),x=Mt("button",{className:Ls("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!g&&"persona-bg-persona-primary",!t&&!u&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?f:void 0,height:t?f:void 0,minWidth:t?f:void 0,minHeight:t?f:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?u||"var(--persona-button-primary-fg, #ffffff)":u||void 0,backgroundColor:t&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),I=null,M=null;if(t){let Ie=parseFloat(f)||24,_e=(u==null?void 0:u.trim())||"currentColor";o?(I=Ae(o,Ie,_e,2),I?x.appendChild(I):x.textContent=r):x.textContent=r,M=Ae(s,Ie,_e,2)}else x.textContent=d;let E=null;m&&a&&(E=b("div","persona-send-button-tooltip"),E.textContent=a,v.appendChild(E)),x.setAttribute("aria-label",a),v.appendChild(x);let F="send";return{button:x,wrapper:v,setMode:Ie=>{if(Ie===F)return;F=Ie;let _e=Ie==="stop"?i:a;if(x.setAttribute("aria-label",_e),E&&(E.textContent=_e),t){if(I&&M){let Se=Ie==="stop"?M:I;x.replaceChildren(Se)}}else x.textContent=Ie==="stop"?c:d}}},Ka=n=>{var E,F,L,R,A,W,N,D,k,j,V,ne;let e=(E=n==null?void 0:n.voiceRecognition)!=null?E:{};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=(L=n==null?void 0:n.sendButton)==null?void 0:L.size)!=null?R:"40px",i=(A=e.iconName)!=null?A:"mic",d=(W=e.iconSize)!=null?W:a,c=parseFloat(d)||24,m=(D=e.backgroundColor)!=null?D:(N=n==null?void 0:n.sendButton)==null?void 0:N.backgroundColor,f=(j=e.iconColor)!=null?j:(k=n==null?void 0:n.sendButton)==null?void 0:k.textColor,g=b("div","persona-send-button-wrapper"),u=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:m||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),x=Ae(i,c,f||"currentColor",1.5);x?u.appendChild(x):u.textContent="\u{1F3A4}",g.appendChild(u);let I=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((ne=e.showTooltip)!=null?ne:!1)&&I){let Re=b("div","persona-send-button-tooltip");Re.textContent=I,g.appendChild(Re)}return{button:u,wrapper:g}},Ga=n=>{var v,x,I,M,E,F,L,R;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(I=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?I:"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=((M=e.allowedTypes)!=null?M:Ur).join(","),o.multiple=((E=e.maxFiles)!=null?E: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"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(L=e.buttonTooltipText)!=null?L:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});m.addEventListener("mouseenter",()=>{m.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),m.addEventListener("mouseleave",()=>{m.style.backgroundColor="transparent"});let f=Ae(s,d,"currentColor",1.5);f?m.appendChild(f):m.textContent="\u{1F4CE}",m.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(m);let g=(R=e.buttonTooltipText)!=null?R:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=g,c.appendChild(u),{button:m,wrapper:c,input:o,previewsContainer:r}},Qa=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},Xa=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ja=n=>{var v,x,I,M,E,F;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa(),o=Mt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ja(e);a();let i=Va(e),d=Ka(e),c=Ga(e),m=Qa(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),f.append(g,u),o.append(f),o.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,m),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:m,attachmentButton:(I=c==null?void 0:c.button)!=null?I:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:f,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var im=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=Ae("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=Ae("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},lm=n=>{var v,x,I,M,E,F;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa();r.style.display="none";let o=Qa(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ja(e);s.style.maxHeight="100px",a();let i=Va(e),d=Ka(e),c=Ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let m=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),m.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&m.append(c.input),m.append(f,s,g),c&&t.append(c.previewsContainer),t.append(m,r,o);let u=m;return{footer:t,suggestions:r,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(I=c==null?void 0:c.button)!=null?I:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var cm=n=>{var m,f,g,u,v,x,I,M,E,F,L,R,A,W,N,D,k;let e=(f=(m=n==null?void 0:n.launcher)==null?void 0:m.enabled)!=null?f:!0,t=gn(n);if(Qs(n)){let j=(u=(g=n==null?void 0:n.launcher)==null?void 0:g.composerBar)!=null?u:{},V=b("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",V.style.zIndex=String((I=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?I:wn);let ne=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let Re=b("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(M=j.expandedSize)!=null?M:"anchored",Re.style.zIndex=String((F=(E=n==null?void 0:n.launcher)==null?void 0:E.zIndex)!=null?F:wn),{wrapper:V,panel:ne,pillRoot:Re}}if(t){let j=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(V),{wrapper:j,panel:V}}if(!e){let j=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(R=(L=n==null?void 0:n.launcher)==null?void 0:L.width)!=null?R:"100%";return j.style.width=ne,V.style.width="100%",j.appendChild(V),{wrapper:j,panel:V}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((N=(W=n==null?void 0:n.launcher)==null?void 0:W.zIndex)!=null?N:wn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(D=n==null?void 0:n.launcher)==null?void 0:D.width)!=null?k:n==null?void 0:n.launcherWidth,c=d!=null?d:qr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},mh=(n,e)=>{var L,R,A,W,N,D,k,j,V;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}=Ua(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=(L=n==null?void 0:n.launcher)==null?void 0:L.clearChat)==null?void 0:R.enabled)!=null?A:!0,a=null,i=null;if(s){let ne=qa(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let m=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(W=n==null?void 0:n.copy)==null?void 0:W.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),f=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(D=n==null?void 0:n.copy)==null?void 0:D.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),g=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},m,f),u=b("div","persona-flex persona-flex-col persona-gap-3"),v=(j=n==null?void 0:n.layout)==null?void 0:j.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((V=n==null?void 0:n.copy)==null?void 0:V.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,u);let I=Mt("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=lm({config:n}),{root:E,textNode:F}=im();return t.append(d,o,c,I),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:u,composerOverlay:I,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:m,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("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:E,peekTextNode:F}},dm=(n,e=!0)=>{var I,M,E,F,L,R,A,W,N;if(Qs(n))return mh(n,e);let t=Mt("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=(I=n==null?void 0:n.layout)==null?void 0:I.header,o=((M=n==null?void 0:n.layout)==null?void 0:M.showHeader)!==!1,s=r?za(n,r,{showClose:e}):Ho({config:n,showClose:e}),a=Mt("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=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(E=n==null?void 0:n.copy)==null?void 0:E.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:gn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),m=b("div","persona-flex persona-flex-col persona-gap-3"),f=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;f&&(m.style.maxWidth=f,m.style.marginLeft="auto",m.style.marginRight="auto",m.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,m);let u=Ja({config:n}),v=((N=n==null?void 0:n.layout)==null?void 0:N.showFooter)!==!1;o?Xs(t,s,n):(s.header.style.display="none",Xs(t,s,n)),t.append(a);let x=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(u.footer.style.display="none"),t.append(u.footer),t.append(x),{container:t,body:a,messagesWrapper:m,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Ui=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
18
20
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
19
21
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
20
22
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -22,14 +24,14 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
22
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
23
25
  </span>
24
26
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
25
- `,t.addEventListener("click",e);let r=s=>{var F,L,R,A,W,N,D,k,j,V,ne,Re,Ue;let a=(F=s.launcher)!=null?F:{},i=gn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let xe=(L=a.title)!=null?L:"Chat Assistant";d.textContent=xe,d.setAttribute("title",xe)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let xe=(R=a.subtitle)!=null?R:"Here to help you get answers fast";c.textContent=xe,c.setAttribute("title",xe)}let m=t.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let xe=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=xe,f.style.width=xe,f.innerHTML="",a.agentIconName){let Ie=parseFloat(xe)||24,_e=Ae(a.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);_e?(f.appendChild(_e),f.style.display=""):(f.textContent=(W=a.agentIconText)!=null?W:"\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 g=t.querySelector("[data-role='launcher-image']");if(g){let xe=(D=a.agentIconSize)!=null?D:"40px";g.style.height=xe,g.style.width=xe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=t.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let xe=(k=a.callToActionIconSize)!=null?k:"32px";u.style.height=xe,u.style.width=xe,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,Ie=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let _e=parseFloat(xe)||24,Se=Math.max(_e-Ie,8),ve=Ae(a.callToActionIconName,Se,"currentColor",2);ve?u.appendChild(ve):u.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else u.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&fr[a.position]?fr[a.position]:fr["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",I="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?I:`${x} ${v}`,i||(t.style.zIndex=String((ne=a.zIndex)!=null?ne:wn));let M="1px solid var(--persona-border, #e5e7eb)",E="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=(Re=a.border)!=null?Re:M,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,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=(Ue=a.collapsedMaxWidth)!=null?Ue:"",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 im=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=sm(n),s=am(n,e),a={wrapper:t,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},qi=({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:()=>Ui(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=Ui(n,t);return{instance:o,element:o.element}};var ih=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}},lh=(n,e)=>{if(!n)return null;let t=ih(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},ch=(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},dh=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},zi=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(":"))},ji=320,cm=320,ph=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),uh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),mh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),gh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),fh=(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=`${ji}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 m=!1;o+=1,c.addEventListener("error",()=>{m||(m=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{m=!0}),dh(i.image)?(c.src=i.image,r.appendChild(c)):(m=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},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","audio");let t=0;return n.forEach(r=>{if(!zi(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=`${ji}px`,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","video");let t=0;return n.forEach(r=>{if(!zi(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=`${ji}px`,o.style.maxHeight=`${cm}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}},bh=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(!zi(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}},Js=()=>{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},vh=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:Js};if(e){let o=e(r);if(o!==null)return o}return Js()},xh=(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},lm=(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},wh=(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},Ch=(n,e,t)=>{var v,x,I,M,E,F,L;let r=(v=e.showCopy)!=null?v:!0,o=(x=e.showUpvote)!=null?x:!0,s=(I=e.showDownvote)!=null?I:!0,a=(M=e.showReadAloud)!=null?M:!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=(E=e.visibility)!=null?E:"hover",d=(F=e.align)!=null?F:"right",c=(L=e.layout)!=null?L:"pill-inside",m={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${m} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${n.id}`,g.setAttribute("data-actions-for",n.id);let u=(R,A,W)=>{let N=Cn({icon:R,label:A,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",W),N};return r&&g.appendChild(u("copy","Copy message","copy")),a&&g.appendChild(u("volume-2","Read aloud","read-aloud")),o&&g.appendChild(u("thumbs-up","Upvote","upvote")),s&&g.appendChild(u("thumbs-down","Downvote","downvote")),g},Vi=(n,e,t,r,o,s)=>{var re,X,ie,he,oe,K,te,qe,Y,le,Pe,it,lt,rt,Ee,pe,Xe;let a=t!=null?t:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,m=(X=d==null?void 0:d.show)!=null?X:!1,f=(ie=c==null?void 0:c.show)!=null?ie:!1,g=(he=d==null?void 0:d.position)!=null?he:"left",u=(oe=c==null?void 0:c.position)!=null?oe:"below",v=wh(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 I=ph(n),M=(te=(K=n.content)==null?void 0:K.trim())!=null?te:"",F=I.length>0&&M===Ma,L=Oa((Y=(qe=s==null?void 0:s.widgetConfig)==null?void 0:qe.features)==null?void 0:Y.streamAnimation),R=(it=(Pe=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Pe.streamAnimation)==null?void 0:it.plugins,A=n.role==="assistant"&&L.type!=="none"?zs(L.type,R):null,W=n.role==="assistant"&&((lt=A==null?void 0:A.isAnimating)==null?void 0:lt.call(A,n))===!0,N=n.role==="assistant"&&A!==null&&(!!n.streaming||W);N&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),N&&A&&(A.containerClass&&D.classList.add(A.containerClass),D.style.setProperty("--persona-stream-step",`${L.speed}ms`),D.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let k=N?_a((rt=n.content)!=null?rt:"",L.buffer,A,n,!!n.streaming):(Ee=n.content)!=null?Ee:"",j=e({text:k,message:n,streaming:!!n.streaming,raw:n.rawContent}),V=j;N&&(A==null?void 0:A.wrap)==="char"?V=js(j,"char",n.id,{skipTags:A.skipTags}):N&&(A==null?void 0:A.wrap)==="word"&&(V=js(j,"word",n.id,{skipTags:A.skipTags}));let ne=null;if(F?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",D.appendChild(ne)):D.innerHTML=V,N&&(A!=null&&A.useCaret)&&!F&&M){let J=$a(),ce=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=ce[ce.length-1];if(we!=null&&we.parentNode)we.parentNode.insertBefore(J,we.nextSibling);else{let je=D.lastElementChild;je?je.appendChild(J):D.appendChild(J)}}if(f&&u==="inline"&&n.createdAt){let J=lm(n,c,"span");J.classList.add("persona-timestamp-inline");let ce=D.lastElementChild;ce?ce.appendChild(J):D.appendChild(J)}if(I.length>0){let J=fh(I,!F&&!!M,()=>{F&&ne&&(ne.style.display="")});J?x.appendChild(J):F&&ne&&(ne.style.display="")}let Re=uh(n);if(Re.length>0){let J=hh(Re);J&&x.appendChild(J)}let Ue=mh(n);if(Ue.length>0){let J=yh(Ue);J&&x.appendChild(J)}let xe=gh(n);if(xe.length>0){let J=bh(xe);J&&x.appendChild(J)}if(x.appendChild(D),f&&u==="below"&&n.createdAt){let J=lm(n,c);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ie=n.role==="assistant"?lh(n.stopReason,(Xe=(pe=s==null?void 0:s.widgetConfig)==null?void 0:pe.copy)==null?void 0:Xe.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let J=!!(k&&k.trim()),ce=L.placeholder==="skeleton",we=ce&&L.buffer==="line"&&J;if(J)we&&x.appendChild(Vs());else if(ce)x.appendChild(Vs());else{let je=vh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);je&&x.appendChild(je)}}if(Ie&&n.stopReason&&!n.streaming&&(M||(D.style.display="none"),x.appendChild(ch(n.stopReason,Ie))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Ch(n,r,o);x.appendChild(J)}if(!m||n.role==="system")return x;let Se=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),ve=xh(d,n.role);return g==="right"||g==="left"&&n.role==="user"?Se.append(x,ve):Se.append(ve,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Se};var ds=new Set,Ah=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Sh=(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
- `):""},dm=(n,e)=>{let t=ds.has(n),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=Ae(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},Ki=(n,e)=>{var Ue,xe,Ie,_e,Se,ve,re,X,ie,he,oe;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=(xe=(Ue=e==null?void 0:e.features)==null?void 0:Ue.reasoningDisplay)!=null?xe:{},s=o.expandable!==!1,a=s&&ds.has(n.id),i=t.status!=="complete",d=Sh(n,(Ie=o.previewMaxLines)!=null?Ie:3),c=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let m=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(_e=e==null?void 0:e.reasoning)!=null?_e:{},v=String((Se=t.startedAt)!=null?Se:Date.now()),x=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Ca(t),K},I=(ve=u.renderCollapsedSummary)==null?void 0:ve.call(u,{message:n,reasoning:t,defaultSummary:g,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ca(t),createElapsedElement:x});typeof I=="string"&&I.trim()?(f.textContent=I,m.appendChild(f)):I instanceof HTMLElement?m.appendChild(I):(f.textContent=g,m.appendChild(f));let M=b("span","persona-text-xs persona-text-persona-primary");M.textContent=cu(t),m.appendChild(M);let E=(re=o.loadingAnimation)!=null?re:"none",F=u.activeTextTemplate,L=u.completeTextTemplate,R=i?F:L,A=I instanceof HTMLElement,W=(K,te,qe)=>{let Y=qe;for(let le of te){let Pe=b("span","persona-tool-char");Pe.style.setProperty("--char-index",String(Y)),Pe.textContent=le===" "?"\xA0":le,K.appendChild(Pe),Y++}return Y},N=(K,te)=>{f.textContent="";let qe=Aa(K,""),Y=0;for(let le of qe){let Pe=le.styles.length>0?(()=>{let it=b("span",le.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return f.appendChild(it),it})():f;if(le.isDuration&&i)Pe.appendChild(x());else{let it=le.isDuration?Ca(t):le.text;te?Y=W(Pe,it,Y):Pe.appendChild(document.createTextNode(it))}}};if(!A&&R)if(M.style.display="none",f.style.display="",i&&E!=="none"){let K=(X=u.loadingAnimationDuration)!=null?X:2e3;f.setAttribute("data-preserve-animation","true"),E==="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-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),N(R,!0))}else N(R,!1);else if(!A&&i&&E!=="none"){f.style.display="";let K=(ie=u.loadingAnimationDuration)!=null?ie:2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let te=f.textContent||g;f.textContent="",W(f,te,0)}t.status==="complete"&&(f.style.display="none")}else A||(t.status==="complete"?f.style.display="none":f.style.display="");let D=null;if(s){D=b("div","persona-flex persona-items-center");let te=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);te?D.appendChild(te):D.textContent=a?"Hide":"Show";let qe=b("div","persona-flex persona-items-center persona-ml-auto");qe.append(D),c.append(m,qe)}else c.append(m);let k=b("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=(oe=(he=e==null?void 0:e.reasoning)==null?void 0:he.renderCollapsedPreview)==null?void 0:oe.call(he,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});Ah(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 j=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let V=t.chunks.join(""),ne=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(ne),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let te=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);te?D.appendChild(te):D.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,j),r};var ps=new Set,Th=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Mh=(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
+ `,t.addEventListener("click",e);let r=s=>{var F,L,R,A,W,N,D,k,j,V,ne,Re,Ue;let a=(F=s.launcher)!=null?F:{},i=gn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let xe=(L=a.title)!=null?L:"Chat Assistant";d.textContent=xe,d.setAttribute("title",xe)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let xe=(R=a.subtitle)!=null?R:"Here to help you get answers fast";c.textContent=xe,c.setAttribute("title",xe)}let m=t.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let xe=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=xe,f.style.width=xe,f.innerHTML="",a.agentIconName){let Ie=parseFloat(xe)||24,_e=Ae(a.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);_e?(f.appendChild(_e),f.style.display=""):(f.textContent=(W=a.agentIconText)!=null?W:"\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 g=t.querySelector("[data-role='launcher-image']");if(g){let xe=(D=a.agentIconSize)!=null?D:"40px";g.style.height=xe,g.style.width=xe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=t.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let xe=(k=a.callToActionIconSize)!=null?k:"32px";u.style.height=xe,u.style.width=xe,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,Ie=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let _e=parseFloat(xe)||24,Se=Math.max(_e-Ie,8),ve=Ae(a.callToActionIconName,Se,"currentColor",2);ve?u.appendChild(ve):u.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else u.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&fr[a.position]?fr[a.position]:fr["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",I="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?I:`${x} ${v}`,i||(t.style.zIndex=String((ne=a.zIndex)!=null?ne:wn));let M="1px solid var(--persona-border, #e5e7eb)",E="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=(Re=a.border)!=null?Re:M,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,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=(Ue=a.collapsedMaxWidth)!=null?Ue:"",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 pm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=cm(n),s=dm(n,e),a={wrapper:t,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},qi=({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:()=>Ui(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=Ui(n,t);return{instance:o,element:o.element}};var gh=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}},fh=(n,e)=>{if(!n)return null;let t=gh(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},hh=(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},yh=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},zi=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(":"))},ji=320,mm=320,bh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),vh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),xh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),wh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Ch=(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=`${ji}px`,c.style.maxHeight=`${mm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let m=!1;o+=1,c.addEventListener("error",()=>{m||(m=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{m=!0}),yh(i.image)?(c.src=i.image,r.appendChild(c)):(m=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},Ah=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(!zi(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=`${ji}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Sh=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(!zi(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=`${ji}px`,o.style.maxHeight=`${mm}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}},Th=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(!zi(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}},Js=()=>{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},Mh=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:Js};if(e){let o=e(r);if(o!==null)return o}return Js()},Eh=(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},um=(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},kh=(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},Lh=(n,e,t)=>{var v,x,I,M,E,F,L;let r=(v=e.showCopy)!=null?v:!0,o=(x=e.showUpvote)!=null?x:!0,s=(I=e.showDownvote)!=null?I:!0,a=(M=e.showReadAloud)!=null?M:!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=(E=e.visibility)!=null?E:"hover",d=(F=e.align)!=null?F:"right",c=(L=e.layout)!=null?L:"pill-inside",m={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${m} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${n.id}`,g.setAttribute("data-actions-for",n.id);let u=(R,A,W)=>{let N=Cn({icon:R,label:A,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",W),N};return r&&g.appendChild(u("copy","Copy message","copy")),a&&g.appendChild(u("volume-2","Read aloud","read-aloud")),o&&g.appendChild(u("thumbs-up","Upvote","upvote")),s&&g.appendChild(u("thumbs-down","Downvote","downvote")),g},Vi=(n,e,t,r,o,s)=>{var re,X,ie,he,oe,K,te,qe,Y,le,Pe,it,lt,rt,Ee,pe,Xe;let a=t!=null?t:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,m=(X=d==null?void 0:d.show)!=null?X:!1,f=(ie=c==null?void 0:c.show)!=null?ie:!1,g=(he=d==null?void 0:d.position)!=null?he:"left",u=(oe=c==null?void 0:c.position)!=null?oe:"below",v=kh(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 I=bh(n),M=(te=(K=n.content)==null?void 0:K.trim())!=null?te:"",F=I.length>0&&M===Ma,L=Oa((Y=(qe=s==null?void 0:s.widgetConfig)==null?void 0:qe.features)==null?void 0:Y.streamAnimation),R=(it=(Pe=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Pe.streamAnimation)==null?void 0:it.plugins,A=n.role==="assistant"&&L.type!=="none"?zs(L.type,R):null,W=n.role==="assistant"&&((lt=A==null?void 0:A.isAnimating)==null?void 0:lt.call(A,n))===!0,N=n.role==="assistant"&&A!==null&&(!!n.streaming||W);N&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),n.streaming&&D.classList.add("persona-content-streaming"),N&&A&&(A.containerClass&&D.classList.add(A.containerClass),D.style.setProperty("--persona-stream-step",`${L.speed}ms`),D.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let k=N?_a((rt=n.content)!=null?rt:"",L.buffer,A,n,!!n.streaming):(Ee=n.content)!=null?Ee:"",j=e({text:k,message:n,streaming:!!n.streaming,raw:n.rawContent}),V=j;N&&(A==null?void 0:A.wrap)==="char"?V=js(j,"char",n.id,{skipTags:A.skipTags}):N&&(A==null?void 0:A.wrap)==="word"&&(V=js(j,"word",n.id,{skipTags:A.skipTags}));let ne=null;if(F?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",D.appendChild(ne)):D.innerHTML=V,N&&(A!=null&&A.useCaret)&&!F&&M){let J=$a(),ce=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=ce[ce.length-1];if(we!=null&&we.parentNode)we.parentNode.insertBefore(J,we.nextSibling);else{let je=D.lastElementChild;je?je.appendChild(J):D.appendChild(J)}}if(f&&u==="inline"&&n.createdAt){let J=um(n,c,"span");J.classList.add("persona-timestamp-inline");let ce=D.lastElementChild;ce?ce.appendChild(J):D.appendChild(J)}if(I.length>0){let J=Ch(I,!F&&!!M,()=>{F&&ne&&(ne.style.display="")});J?x.appendChild(J):F&&ne&&(ne.style.display="")}let Re=vh(n);if(Re.length>0){let J=Ah(Re);J&&x.appendChild(J)}let Ue=xh(n);if(Ue.length>0){let J=Sh(Ue);J&&x.appendChild(J)}let xe=wh(n);if(xe.length>0){let J=Th(xe);J&&x.appendChild(J)}if(x.appendChild(D),f&&u==="below"&&n.createdAt){let J=um(n,c);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ie=n.role==="assistant"?fh(n.stopReason,(Xe=(pe=s==null?void 0:s.widgetConfig)==null?void 0:pe.copy)==null?void 0:Xe.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let J=!!(k&&k.trim()),ce=L.placeholder==="skeleton",we=ce&&L.buffer==="line"&&J;if(J)we&&x.appendChild(Vs());else if(ce)x.appendChild(Vs());else{let je=Mh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);je&&x.appendChild(je)}}if(Ie&&n.stopReason&&!n.streaming&&(M||(D.style.display="none"),x.appendChild(hh(n.stopReason,Ie))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Lh(n,r,o);x.appendChild(J)}if(!m||n.role==="system")return x;let Se=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),ve=Eh(d,n.role);return g==="right"||g==="left"&&n.role==="user"?Se.append(x,ve):Se.append(ve,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Se};var ds=new Set,Ph=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Ih=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
28
+ `):""},gm=(n,e)=>{let t=ds.has(n),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=Ae(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},Ki=(n,e)=>{var Ue,xe,Ie,_e,Se,ve,re,X,ie,he,oe;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=(xe=(Ue=e==null?void 0:e.features)==null?void 0:Ue.reasoningDisplay)!=null?xe:{},s=o.expandable!==!1,a=s&&ds.has(n.id),i=t.status!=="complete",d=Ih(n,(Ie=o.previewMaxLines)!=null?Ie:3),c=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let m=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(_e=e==null?void 0:e.reasoning)!=null?_e:{},v=String((Se=t.startedAt)!=null?Se:Date.now()),x=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Ca(t),K},I=(ve=u.renderCollapsedSummary)==null?void 0:ve.call(u,{message:n,reasoning:t,defaultSummary:g,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ca(t),createElapsedElement:x});typeof I=="string"&&I.trim()?(f.textContent=I,m.appendChild(f)):I instanceof HTMLElement?m.appendChild(I):(f.textContent=g,m.appendChild(f));let M=b("span","persona-text-xs persona-text-persona-primary");M.textContent=mu(t),m.appendChild(M);let E=(re=o.loadingAnimation)!=null?re:"none",F=u.activeTextTemplate,L=u.completeTextTemplate,R=i?F:L,A=I instanceof HTMLElement,W=(K,te,qe)=>{let Y=qe;for(let le of te){let Pe=b("span","persona-tool-char");Pe.style.setProperty("--char-index",String(Y)),Pe.textContent=le===" "?"\xA0":le,K.appendChild(Pe),Y++}return Y},N=(K,te)=>{f.textContent="";let qe=Aa(K,""),Y=0;for(let le of qe){let Pe=le.styles.length>0?(()=>{let it=b("span",le.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return f.appendChild(it),it})():f;if(le.isDuration&&i)Pe.appendChild(x());else{let it=le.isDuration?Ca(t):le.text;te?Y=W(Pe,it,Y):Pe.appendChild(document.createTextNode(it))}}};if(!A&&R)if(M.style.display="none",f.style.display="",i&&E!=="none"){let K=(X=u.loadingAnimationDuration)!=null?X:2e3;f.setAttribute("data-preserve-animation","true"),E==="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-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),N(R,!0))}else N(R,!1);else if(!A&&i&&E!=="none"){f.style.display="";let K=(ie=u.loadingAnimationDuration)!=null?ie:2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let te=f.textContent||g;f.textContent="",W(f,te,0)}t.status==="complete"&&(f.style.display="none")}else A||(t.status==="complete"?f.style.display="none":f.style.display="");let D=null;if(s){D=b("div","persona-flex persona-items-center");let te=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);te?D.appendChild(te):D.textContent=a?"Hide":"Show";let qe=b("div","persona-flex persona-items-center persona-ml-auto");qe.append(D),c.append(m,qe)}else c.append(m);let k=b("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=(oe=(he=e==null?void 0:e.reasoning)==null?void 0:he.renderCollapsedPreview)==null?void 0:oe.call(he,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});Ph(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 j=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let V=t.chunks.join(""),ne=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(ne),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let te=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);te?D.appendChild(te):D.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,j),r};var ps=new Set,Wh=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Rh=(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
29
  `);let o=rs(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
28
- `):""},Gi=(n,e)=>{var t,r,o;n.style.backgroundColor=(t=e.codeBlockBackgroundColor)!=null?t:"var(--persona-container, #f3f4f6)",n.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",n.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Eh=(n,e)=>{var m,f,g,u,v;let t=n.toolCall,r=(m=e==null?void 0:e.features)==null?void 0:m.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=Mh(n,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?du(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(u=e==null?void 0:e.toolCall)!=null?u:{},c=a;return o==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ki(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ki(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},pm=(n,e,t)=>{var m;let r=ps.has(n),o=(m=t==null?void 0:t.toolCall)!=null?m:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=Ae(r?"chevron-up":"chevron-down",16,f,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Qi=(n,e)=>{var V,ne,Re,Ue,xe,Ie,_e,Se,ve;let t=n.toolCall,r=(V=e==null?void 0:e.toolCall)!=null?V:{},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=(Re=(ne=e==null?void 0:e.features)==null?void 0:ne.toolCallDisplay)!=null?Re:{},a=s.expandable!==!1,i=a&&ps.has(n.id),{summary:d,previewText:c,isActive:m}=Eh(n,e),f=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((Ue=t.startedAt)!=null?Ue:Date.now()),x=()=>{let re=b("span","");return re.setAttribute("data-tool-elapsed",v),re.textContent=Rs(t),re},I=(Ie=r.renderCollapsedSummary)==null?void 0:Ie.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(xe=s.collapsedMode)!=null?xe:"tool-call",isActive:m,config:e!=null?e:{},elapsed:Rs(t),createElapsedElement:x});typeof I=="string"&&I.trim()?(u.textContent=I,g.appendChild(u)):I instanceof HTMLElement?g.appendChild(I):(u.textContent=d,g.appendChild(u));let M=(_e=s.loadingAnimation)!=null?_e:"none",E=r.activeTextTemplate,F=r.completeTextTemplate,L=m?E:F,R=I instanceof HTMLElement,A=(re,X,ie)=>{let he=ie;for(let oe of X){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(he)),K.textContent=oe===" "?"\xA0":oe,re.appendChild(K),he++}return he},W=(re,X)=>{var K;u.textContent="";let ie=((K=t.name)==null?void 0:K.trim())||"tool",he=Aa(re,ie),oe=0;for(let te of he){let qe=te.styles.length>0?(()=>{let Y=b("span",te.styles.map(le=>`persona-tool-text-${le}`).join(" "));return u.appendChild(Y),Y})():u;if(te.isDuration&&m)qe.appendChild(x());else{let Y=te.isDuration?Rs(t):te.text;X?oe=A(qe,Y,oe):qe.appendChild(document.createTextNode(Y))}}};if(!R)if(m&&M!=="none"){let re=(Se=r.loadingAnimationDuration)!=null?Se:2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${re}ms`),L&&W(L,!1);else if(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${re}ms`),M==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),L)W(L,!0);else{let X=u.textContent||d;u.textContent="",A(u,X,0)}}else L&&W(L,!1);let N=null;if(a){N=b("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=Ae(i?"chevron-up":"chevron-down",16,re,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show";let ie=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(N),f.append(g,ie)}else f.append(g);let D=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&c){let re=(ve=r.renderCollapsedPreview)==null?void 0:ve.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:m,config:e!=null?e:{}});Th(D,re)||(D.textContent=c),D.style.display=""}if(!i&&m&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,D),o;let k=b("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),t.name){let re=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=t.name,k.appendChild(re)}if(t.args!==void 0){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let ie=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=rs(t.args),re.append(X,ie),k.appendChild(re)}if(t.chunks&&t.chunks.length){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let ie=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=t.chunks.join(""),re.append(X,ie),k.appendChild(re)}if(t.status==="complete"&&t.result!==void 0){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let ie=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=rs(t.result),re.append(X,ie),k.appendChild(re)}if(t.status==="complete"&&typeof t.duration=="number"){let re=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${t.duration}ms`,k.appendChild(re)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=Ae(i?"chevron-up":"chevron-down",16,re,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),o.append(f,D,k),o};var Ya=new Map,kh=n=>{let t=(n.startsWith(ko)?n.slice(ko.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)},um=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,mm=(n,e)=>{var r,o,s;let t=(o=(r=um(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ya.get(n))!=null?s:t==="expanded"},gm=(n,e,t)=>{var a,i;let r=um(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ae(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},fm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=mm(n,t);gm(r,s,t),o.style.display=s?"":"none"};var Za=(n,e)=>{var W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re;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=(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))",!t)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(D=r==null?void 0:r.titleColor)!=null?D:"currentColor",m=Ae(d,20,c,2);m&&i.appendChild(m);let f=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",g.appendChild(u),!o){let X=b("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",t.status),t.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"):t.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"):t.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"),g.appendChild(X)}f.appendChild(g);let x=t.toolType==="webmcp"||t.toolName.startsWith(ko)?yi(t.toolName):void 0,I=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),M=!t.toolName,E=I||(M?t.description:`The assistant wants to use \u201C${x!=null?x:kh(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=E,f.appendChild(F),t.reason){let X=b("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 ie=b("span","persona-font-medium");ie.textContent=`${(V=r==null?void 0:r.reasonLabel)!=null?V:"Agent's stated reason:"} `,X.appendChild(ie),X.appendChild(document.createTextNode(t.reason)),f.appendChild(X)}let L=(ne=r==null?void 0:r.detailsDisplay)!=null?ne:"collapsed",R=!!t.description&&!M,A=R||!!t.parameters;if(L!=="hidden"&&A){let X=mm(n.id,e),ie=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");ie.type="button",ie.setAttribute("data-expand-header","true"),ie.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let he=b("span");he.setAttribute("data-approval-details-label","true");let oe=b("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),ie.append(he,oe),gm(ie,X,e),f.appendChild(ie);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=X?"":"none",R){let te=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=t.description,K.appendChild(te)}if(t.parameters){let te=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&&(te.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.style.fontSize="0.75rem",te.style.lineHeight="1rem",te.textContent=rs(t.parameters),K.appendChild(te)}f.appendChild(K)}if(o){let X=b("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let ie=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");ie.type="button",ie.style.backgroundColor=(Re=r==null?void 0:r.approveButtonColor)!=null?Re:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(Ue=r==null?void 0:r.approveButtonTextColor)!=null?Ue:"#ffffff",ie.setAttribute("data-approval-action","approve");let he=Ae("shield-check",14,(xe=r==null?void 0:r.approveButtonTextColor)!=null?xe:"#ffffff",2);he&&(he.style.marginRight="4px",ie.appendChild(he));let oe=document.createTextNode((Ie=r==null?void 0:r.approveLabel)!=null?Ie:"Approve");ie.appendChild(oe);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=(_e=r==null?void 0:r.denyButtonColor)!=null?_e:"transparent",K.style.color=(Se=r==null?void 0:r.denyButtonTextColor)!=null?Se:"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 te=Ae("shield-x",14,(ve=r==null?void 0:r.denyButtonTextColor)!=null?ve:"var(--persona-feedback-error, #dc2626)",2);te&&(te.style.marginRight="4px",K.appendChild(te));let qe=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");K.appendChild(qe),X.append(ie,K),f.appendChild(X)}return a.append(i,f),s.appendChild(a),s};var hm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let m=(c==null?void 0:c.agentPushed)===!0;if(m||(t=null),!o||!o.length||!m&&(i!=null?i:s?s.getMessages():[]).some(I=>I.role==="user"))return;let f=document.createDocumentFragment(),g=s?s.isStreaming():!1,u=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(v=>{let x=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=u(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",m&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),e.push(x)}),n.appendChild(f),m){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Ys=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 Zs=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 Lh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ph=new Set(["step_start","execution_start"]),Ih=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Wh=new Set(["step_complete","agent_turn_complete"]),Rh=new Set(["flow_complete","agent_complete"]),ym=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),vm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Xn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Bo=(n,e)=>{let t=n[e];return vm(t)?t:void 0};function Xi(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function ei(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Hh(n,e){return typeof e.type=="string"?e.type:n}function Bh(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 Dh(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 bm(n){var r,o,s,a,i;let e=Bo(n,"result"),t=[Bo(n,"tokens"),Bo(n,"totalTokens"),e?Bo(e,"tokens"):void 0,Bo(n,"usage"),e?Bo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=Xn(d.output))!=null?r:Xn(d.outputTokens))!=null?o:Xn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Xn(n.outputTokens))!=null?s:Xn(n.completionTokens))!=null?i:e?(a=Xn(e.outputTokens))!=null?a:Xn(e.completionTokens):void 0}function Nh(n){var t,r,o,s,a;let e=Bo(n,"result");return(a=(o=(r=(t=Xn(n.executionTime))!=null?t:Xn(n.executionTimeMs))!=null?r:Xn(n.execution_time))!=null?o:Xn(n.duration))!=null?a:e?(s=Xn(e.executionTime))!=null?s:Xn(e.executionTimeMs):void 0}function Fh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ea=class{constructor(e=Fh){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:ei(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(!vm(t)){ym.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Hh(e,t),o=this.now();if(Lh.has(r)){this.startRun(o);return}if(Ph.has(r)){this.run||this.startRun(o);return}if(Ih.has(r)){if(!Dh(r,t))return;let a=Bh(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+Xi(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ei(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Wh.has(r)){if(!this.run)return;let a=this.run,i=bm(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Xi(a.visibleCharCount),m=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:ei(c,m),outputTokens:c,durationMs:m,source:d?"usage":"estimate"};return}if(Rh.has(r)){if(!this.run)return;let a=this.run,i=bm(t),d=i!=null?i:a.exactOutputTokens+Xi(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:ei(d,m),outputTokens:d,durationMs:m,source:c},this.run=null;return}if(ym.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=Nh(t);return s!=null?s:r-e.startedAt}};function us(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Oh={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)"}},_h={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},$h=["flowName","stepName","reasoningText","text","name","tool","toolName"],Uh=100;function qh(n,e){let t={...Oh,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return _h}function zh(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function jh(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 Vh(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 Kh(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 Gh(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 Qh(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Xh(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 Jh(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 Ji(n,e,t,r,o,s,a,i){var g;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");us(c,(g=r.classNames)==null?void 0:g.eventRow);let m=a.find(u=>u.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let u=m.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(u)return c.appendChild(u),c}return c.appendChild(f()),c;function f(){var V,ne;let u=b("div",""),v=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",n.id);let x=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),I=Ae(d?"chevron-down":"chevron-right","14px","currentColor",2);I&&x.appendChild(I);let M=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=(V=r.timestampFormat)!=null?V:"relative";M.textContent=E==="relative"?zh(n.timestamp,t):jh(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 L=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=L.bg,R.style.color=L.text,R.style.borderColor=L.text+"50",R.textContent=n.type;let A=(ne=r.descriptionFields)!=null?ne:$h,W=Vh(n.payload,A),N=null;W&&(N=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=W);let D=b("div","persona-flex-1 persona-min-w-0"),k=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"),j=Ae("clipboard","12px","currentColor",1.5);return j&&k.appendChild(j),k.addEventListener("click",async Re=>{Re.stopPropagation(),await Kh(Gh(n)),k.innerHTML="";let Ue=Ae("check","12px","currentColor",1.5);Ue&&k.appendChild(Ue),setTimeout(()=>{k.innerHTML="";let xe=Ae("clipboard","12px","currentColor",1.5);xe&&k.appendChild(xe)},1500)}),v.appendChild(x),v.appendChild(M),F&&v.appendChild(F),v.appendChild(R),N&&v.appendChild(N),v.appendChild(D),v.appendChild(k),u.appendChild(v),d&&u.appendChild(Jh(n,a,i)),u}}function xm(n){var v,x,I,M,E;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",m=(I=i==null?void 0:i.label)!=null?I:"",f=(E=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?E:{},g=s.find(F=>F.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let F=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>u().element,onClose:r});if(F)return{element:F,update:()=>{},destroy:()=>{}}}return u();function u(){let F=f.classNames,L=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");us(L,F==null?void 0:F.panel);let R=[],A="",W="",N=null,D=[],k={},j=0,V=Da(),ne=0,Re=0,Ue=!1,xe=null,Ie=!1,_e=0,Se=new Set,ve=new Map,re="",X="",ie=null,he,oe,K,te,qe,Y=null,le=null,Pe=null;function it(){let G=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),de=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");us(de,F==null?void 0:F.headerBar);let ke=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(ke.textContent="Events",he=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"),he.textContent="0",a){le=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let Jn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Jn.textContent="Throughput",Y=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"),Y.textContent="-- tok/s",Pe=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"),Pe.style.display="none",Pe.style.pointerEvents="none";let An=le,en=Pe,In=()=>{if(!en.textContent)return;let xt=An.getBoundingClientRect(),Nn=G.getBoundingClientRect();en.style.left=`${xt.left-Nn.left}px`,en.style.top=`${xt.bottom-Nn.top+4}px`,en.style.display="block"},yr=()=>{en.style.display="none"};le.addEventListener("mouseenter",In),le.addEventListener("mouseleave",yr),le.appendChild(Jn),le.appendChild(Y)}let vt=b("div","persona-flex-1");oe=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 Yt=b("option","");Yt.value="",Yt.textContent="All events",oe.appendChild(Yt),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 pn=Ae("clipboard-copy","12px","currentColor",1.5);pn&&K.appendChild(pn);let Ht=b("span","persona-text-xs");Ht.textContent="Copy All",K.appendChild(Ht),de.appendChild(ke),de.appendChild(he),le&&de.appendChild(le),de.appendChild(vt),de.appendChild(oe),de.appendChild(K);let et=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");us(et,F==null?void 0:F.searchBar);let Rt=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),ct=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");Rt&&ct.appendChild(Rt),te=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"),us(te,F==null?void 0:F.searchInput),te.type="text",te.placeholder="Search event payloads...",qe=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"),qe.type="button",qe.style.display="none";let Kt=Ae("x","12px","currentColor",2);return Kt&&qe.appendChild(Kt),et.appendChild(ct),et.appendChild(te),et.appendChild(qe),G.appendChild(de),G.appendChild(et),Pe&&G.appendChild(Pe),G}let lt,rt=s.find(G=>G.renderEventStreamToolbar);if(rt!=null&&rt.renderEventStreamToolbar&&o){let G=rt.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:e.getSize(),filteredCount:0,onFilterChange:de=>{A=de,It(),hn()},onSearchChange:de=>{W=de,It(),hn()}});lt=G!=null?G: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 pe(){if(!a||!Y||!le)return;let G=a();Y.textContent=Qh(G);let de=Xh(G);Pe&&(Pe.textContent=de,de||(Pe.style.display="none")),de?le.setAttribute("aria-label",de):le.removeAttribute("aria-label")}let Xe=b("div","persona-flex-1 persona-min-h-0 persona-relative"),J=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ce=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");us(ce,F==null?void 0:F.scrollIndicator),ce.style.display="none",ce.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let we=Ae(c,"14px","currentColor",2);we&&ce.appendChild(we);let je=b("span","");je.textContent=m,ce.appendChild(je);let Pt=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Pt.style.display="none",Xe.appendChild(J),Xe.appendChild(Pt),Xe.appendChild(ce),L.setAttribute("tabindex","0"),L.appendChild(lt),L.appendChild(Ee),L.appendChild(Xe);function Te(){let G=e.getAll(),de={};for(let Ht of G)de[Ht.type]=(de[Ht.type]||0)+1;let ke=Object.keys(de).sort(),vt=ke.length!==D.length||!ke.every((Ht,et)=>Ht===D[et]),Yt=!vt&&ke.some(Ht=>de[Ht]!==k[Ht]),Zt=G.length!==Object.values(k).reduce((Ht,et)=>Ht+et,0);if(!vt&&!Yt&&!Zt||(D=ke,k=de,!oe))return;let pn=oe.value;if(oe.options[0].textContent="All events",vt){for(;oe.options.length>1;)oe.remove(1);for(let Ht of ke){let et=b("option","");et.value=Ht,et.textContent=`${Ht} (${de[Ht]||0})`,oe.appendChild(et)}pn&&ke.includes(pn)?oe.value=pn:pn&&(oe.value="",A="")}else for(let Ht=1;Ht<oe.options.length;Ht++){let et=oe.options[Ht];et.textContent=`${et.value} (${de[et.value]||0})`}}function me(){let G=e.getAll();if(A&&(G=G.filter(de=>de.type===A)),W){let de=W.toLowerCase();G=G.filter(ke=>ke.type.toLowerCase().includes(de)||ke.payload.toLowerCase().includes(de))}return G}function fn(){return A!==""||W!==""}function It(){j=0,ne=0,V.resume(),ce.style.display="none"}function rn(G){Se.has(G)?Se.delete(G):Se.add(G),ie=G;let de=J.scrollTop,ke=V.isFollowing();Ie=!0,V.pause(),hn(),J.scrollTop=de,ke&&V.resume(),Ie=!1}function hr(){return Ro(J,50)}function hn(){Re=Date.now(),Ue=!1,pe(),Te();let G=e.getEvictedCount();G>0?(Ee.textContent=`${G.toLocaleString()} older events truncated`,Ee.style.display=""):Ee.style.display="none",R=me();let de=R.length,ke=e.getSize()>0;he&&(he.textContent=String(e.getSize())),de===0&&ke&&fn()?(Pt.textContent=W?`No events matching '${W}'`:"No events matching filter",Pt.style.display="",J.style.display="none"):(Pt.style.display="none",J.style.display=""),K&&(K.title=fn()?`Copy Filtered (${de})`:"Copy All"),d&&!V.isFollowing()&&de>j&&(ne+=de-j,je.textContent=m?`${m}${ne>0?` (${ne})`:""}`:"",ce.style.display=""),j=de;let vt=e.getAll(),Yt=vt.length>0?vt[0].timestamp:0,Zt=new Set(R.map(et=>et.id));for(let et of Se)Zt.has(et)||Se.delete(et);let pn=A!==re||W!==X,Ht=ve.size===0&&R.length>0;if(pn||Ht||R.length===0){J.innerHTML="",ve.clear();let et=document.createDocumentFragment();for(let Rt=0;Rt<R.length;Rt++){let ct=Ji(R[Rt],Rt,Yt,f,Se,rn,s,o);ve.set(R[Rt].id,ct),et.appendChild(ct)}J.appendChild(et),re=A,X=W,ie=null}else{if(ie!==null){let Rt=ve.get(ie);if(Rt&&Rt.parentNode===J){let ct=R.findIndex(Kt=>Kt.id===ie);if(ct>=0){let Kt=Ji(R[ct],ct,Yt,f,Se,rn,s,o);J.insertBefore(Kt,Rt),Rt.remove(),ve.set(ie,Kt)}}ie=null}let et=new Set(R.map(Rt=>Rt.id));for(let[Rt,ct]of ve)et.has(Rt)||(ct.remove(),ve.delete(Rt));for(let Rt=0;Rt<R.length;Rt++){let ct=R[Rt];if(!ve.has(ct.id)){let Kt=Ji(ct,Rt,Yt,f,Se,rn,s,o);ve.set(ct.id,Kt),J.appendChild(Kt)}}}V.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Ve(){if(Date.now()-Re>=Uh){xe!==null&&(cancelAnimationFrame(xe),xe=null),hn();return}Ue||(Ue=!0,xe=requestAnimationFrame(()=>{xe=null,hn()}))}let T=(G,de)=>{if(!K)return;K.innerHTML="";let ke=Ae(G,"12px","currentColor",1.5);ke&&K.appendChild(ke);let vt=b("span","persona-text-xs");vt.textContent="Copy All",K.appendChild(vt),setTimeout(()=>{K.innerHTML="";let Yt=Ae("clipboard-copy","12px","currentColor",1.5);Yt&&K.appendChild(Yt);let Zt=b("span","persona-text-xs");Zt.textContent="Copy All",K.appendChild(Zt),K.disabled=!1},de)},ue=async()=>{if(K){K.disabled=!0;try{let G;fn()?G=R:t?(G=await t(),G.length===0&&(G=e.getAll())):G=e.getAll();let de=G.map(ke=>{try{return JSON.parse(ke.payload)}catch{return ke.payload}});await navigator.clipboard.writeText(JSON.stringify(de,null,2)),T("check",1500)}catch{T("x",1500)}}},Le=()=>{oe&&(A=oe.value,It(),hn())},Me=()=>{!te||!qe||(qe.style.display=te.value?"":"none",N&&clearTimeout(N),N=setTimeout(()=>{W=te.value,It(),hn()},150))},He=()=>{!te||!qe||(te.value="",W="",qe.style.display="none",N&&clearTimeout(N),It(),hn())},Ze=()=>{if(Ie)return;let G=J.scrollTop,{action:de,nextLastScrollTop:ke}=Na({following:V.isFollowing(),currentScrollTop:G,lastScrollTop:_e,nearBottom:hr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});_e=ke,de==="resume"?(V.resume(),ne=0,ce.style.display="none"):de==="pause"&&(V.pause(),d&&(je.textContent=m,ce.style.display=""))},Ge=G=>{let de=Fa({following:V.isFollowing(),deltaY:G.deltaY,nearBottom:hr(),resumeWhenNearBottom:!0});de==="pause"?(V.pause(),d&&(je.textContent=m,ce.style.display="")):de==="resume"&&(V.resume(),ne=0,ce.style.display="none")},ut=()=>{d&&(J.scrollTop=J.scrollHeight,V.resume(),ne=0,ce.style.display="none")},Wt=G=>{let de=G.target;if(!de||de.closest("button"))return;let ke=de.closest("[data-event-id]");if(!ke)return;let vt=ke.getAttribute("data-event-id");vt&&rn(vt)},q=G=>{if((G.metaKey||G.ctrlKey)&&G.key==="f"){G.preventDefault(),te==null||te.focus(),te==null||te.select();return}G.key==="Escape"&&(te&&document.activeElement===te?(He(),te.blur(),L.focus()):r&&r())};K&&K.addEventListener("click",ue),oe&&oe.addEventListener("change",Le),te&&te.addEventListener("input",Me),qe&&qe.addEventListener("click",He),J.addEventListener("scroll",Ze),J.addEventListener("wheel",Ge,{passive:!0}),J.addEventListener("click",Wt),ce.addEventListener("click",ut),L.addEventListener("keydown",q);function ot(){N&&clearTimeout(N),xe!==null&&(cancelAnimationFrame(xe),xe=null),Ue=!1,ve.clear(),K&&K.removeEventListener("click",ue),oe&&oe.removeEventListener("change",Le),te&&te.removeEventListener("input",Me),qe&&qe.removeEventListener("click",He),J.removeEventListener("scroll",Ze),J.removeEventListener("wheel",Ge),J.removeEventListener("click",Wt),ce.removeEventListener("click",ut),L.removeEventListener("keydown",q)}return{element:L,update:Ve,destroy:ot}}}function wm(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=t;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(u)}else f.textContent=a;if(c.append(m,f),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${t}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Cm=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",m=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>wm(n,e)});if(m)return m}return wm(n,e)};var Yi=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)})}},Do=new Yi;Do.register("PersonaArtifactCard",Cm);function Yh(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 Am(n,e){var oe,K,te,qe;let t=(K=(oe=n.features)==null?void 0:oe.artifacts)==null?void 0:K.layout,o=((te=t==null?void 0:t.toolbarPreset)!=null?te:"default")==="document",s=(qe=t==null?void 0:t.panePadding)==null?void 0:qe.trim(),a=n.markdown?ga(n.markdown):null,i=fa(n.sanitize),d=Y=>{let le=a?a(Y):so(Y);return i?i(le):le},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let f=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let x="rendered",I=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Cn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Cn({icon:"eye",label:"Rendered view"}),E=o?Cn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Cn({icon:"code-2",label:"Source"}),F=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),L=(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),N=null,D,k=null,j=null;if(o&&(L||R)&&!W){if(D=L?$i({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Y=Ae("chevron-down",14,"currentColor",2);Y&&D.appendChild(Y)}}else o&&W?(N=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=L?$i({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Cn({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(D,k)):o?D=Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=Cn({icon:"copy",label:"Copy"});let V=o?Cn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"refresh-cw",label:"Refresh"}),ne=o?Cn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"x",label:"Close"}),Re=()=>{var lt,rt,Ee;let Y=(lt=ve.find(pe=>pe.id===re))!=null?lt:ve[ve.length-1],le=(rt=Y==null?void 0:Y.id)!=null?rt:null,Pe=(Y==null?void 0:Y.artifactType)==="markdown"&&(Ee=Y.markdown)!=null?Ee:"",it=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:Pe,jsonPayload:it,id:le}},Ue=async()=>{var lt;let{markdown:Y,jsonPayload:le}=Re(),Pe=(lt=ve.find(rt=>rt.id===re))!=null?lt:ve[ve.length-1],it=(Pe==null?void 0:Pe.artifactType)==="markdown"?Y:Pe?le:"";try{await navigator.clipboard.writeText(it)}catch{}};if(D.addEventListener("click",async()=>{let Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(Y&&W){let{markdown:le,jsonPayload:Pe,id:it}=Re();try{await Y({actionId:"primary",artifactId:it,markdown:le,jsonPayload:Pe})}catch{}return}await Ue()}),k&&(A!=null&&A.length)){let Y=()=>{var Pe;return(Pe=f.closest("[data-persona-root]"))!=null?Pe:document.body},le=()=>{j=cs({items:A.map(Pe=>({id:Pe.id,label:Pe.label})),onSelect:async Pe=>{let{markdown:it,jsonPayload:lt,id:rt}=Re(),Ee=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ee?await Ee({actionId:Pe,artifactId:rt,markdown:it,jsonPayload:lt}):Pe==="markdown"||Pe==="md"?await navigator.clipboard.writeText(it):Pe==="json"||Pe==="source"?await navigator.clipboard.writeText(lt):await navigator.clipboard.writeText(it||lt)}catch{}},anchor:N!=null?N:k,position:"bottom-right",portal:Y()})};f.isConnected?le():requestAnimationFrame(le),k.addEventListener("click",Pe=>{Pe.stopPropagation(),j==null||j.toggle()})}V.addEventListener("click",async()=>{var Y;try{await((Y=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Y.call(t))}catch{}ie()}),ne.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let xe=()=>{o&&(M.setAttribute("aria-pressed",x==="rendered"?"true":"false"),E.setAttribute("aria-pressed",x==="source"?"true":"false"))};M.addEventListener("click",()=>{x="rendered",xe(),ie()}),E.addEventListener("click",()=>{x="source",xe(),ie()});let Ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),I.append(M,E),N?F.append(N,V,ne):F.append(D,V,ne),g.append(I,Ie,F),xe()):(g.appendChild(u),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let _e=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Se=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(_e.style.paddingLeft=s,_e.style.paddingRight=s,Se.style.padding=s),f.appendChild(g),f.appendChild(_e),f.appendChild(Se);let ve=[],re=null,X=!1,ie=()=>{var it,lt,rt,Ee;let Y=o&&ve.length<=1;_e.classList.toggle("persona-hidden",Y),_e.replaceChildren();for(let pe of ve){let Xe=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Xe.type="button",Xe.textContent=pe.title||pe.id.slice(0,8),pe.id===re&&Xe.classList.add("persona-bg-persona-container","persona-border-persona-border"),Xe.addEventListener("click",()=>e.onSelect(pe.id)),_e.appendChild(Xe)}Se.replaceChildren();let le=re&&ve.find(pe=>pe.id===re)||ve[ve.length-1];if(!le)return;if(o){let pe=le.artifactType==="markdown"?"MD":(it=le.component)!=null?it:"Component",J=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${J} \xB7 ${pe}`}else u.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&x==="source"){let Xe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Xe.textContent=(lt=le.markdown)!=null?lt:"",Se.appendChild(Xe);return}let pe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");pe.innerHTML=d((rt=le.markdown)!=null?rt:""),Se.appendChild(pe);return}let Pe=le.component?Do.get(le.component):void 0;if(Pe){let Xe={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let J=Pe((Ee=le.props)!=null?Ee:{},Xe);if(J){Se.appendChild(J);return}}catch{}}Se.appendChild(Yh(le))},he=()=>{var le;let Y=ve.length>0;if(f.classList.toggle("persona-hidden",!Y),c){let Pe=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,lt=((le=Pe==null?void 0:Pe.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&lt&&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(Y){var le,Pe,it;ve=Y.artifacts,re=(it=(Pe=Y.selectedId)!=null?Pe:(le=Y.artifacts[Y.artifacts.length-1])==null?void 0:le.id)!=null?it:null,ve.length>0&&(X=!0),ie(),he()},setMobileOpen(Y){X=Y,!Y&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):he()}}}function ar(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 Sm(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"),!ar(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 Zh(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ti(n,e){var d,c,m,f,g,u,v,x,I,M;if(!ar(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"),Zh(n),Sm(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(m=t==null?void 0:t.splitGap)!=null?m:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=t==null?void 0:t.paneBackground)==null?void 0:u.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(I=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:I.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=t==null?void 0:t.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"),Sm(n,e)}var Tm=["panel","seamless"];function ni(n,e){var i,d,c,m,f,g;for(let u of Tm)n.classList.remove(`persona-artifact-appearance-${u}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!ar(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=Tm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(m=t==null?void 0:t.paneBorderRadius)==null?void 0:m.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let u=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;u&&n.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Mm(n,e){var t,r,o;return!e||!ar(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function ey(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 ty(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 ny(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function ry(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Em(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 km(n,e,t,r,o,s){let a=ey(o,200),i=ry(e,t,r,200);i=Math.max(a,i);let d=ty(s);return d!==null&&(i=Math.min(i,d)),ny(n,a,i)}var Lm={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"}},Zi=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,I;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Lm[a])!=null?x:Lm.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 M=b("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var A,W;let E=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");E.htmlFor=`${e.id}-${a}-${M.name}`;let F=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=M.label,E.appendChild(F);let L=(A=M.type)!=null?A:"text",R;L==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=L),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}-${M.name}`,R.name=M.name,R.placeholder=(W=M.placeholder)!=null?W:"",M.required&&(R.required=!0),E.appendChild(R),m.appendChild(E)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(I=i.submitLabel)!=null?I:"Submit",f.appendChild(g),f.appendChild(u),m.appendChild(f),s.replaceChildren(d,m),m.addEventListener("submit",async M=>{var R,A;M.preventDefault();let E=(R=t.formEndpoint)!=null?R:"/form",F=new FormData(m),L={};F.forEach((W,N)=>{L[N]=W}),L.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let N=await W.json();g.textContent=(A=N.message)!=null?A:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var el=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()}},tl=new el;var Pm=()=>{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 oy=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},sy=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},rl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=oy(n),t=sy(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}},nl=n=>typeof n=="string"?n:n==null?"":String(n),ta={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:nl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=nl(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:nl(t.text)}}},Im=n=>Array.isArray(n)?n.map(e=>String(e)):[],ol=n=>{let e=new Set(Im(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Im(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,m)=>c||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let m=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:m});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:t}};var ay=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}},iy=n=>n.map(e=>({...e,streaming:!1})),ly=n=>n.map(e=>({...e,status:"complete"})),Wm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?ay(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?iy(t.messages):void 0,artifacts:t.artifacts?ly(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 sl=require("partial-json");function Rm(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Do.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 Hm(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 Bm(n){let e=Hm(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 Dm(n){let e=Hm(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 cy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Nm(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=cy}=n,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,u.appendChild(x),g.appendChild(u);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];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=`
30
+ `):""},Gi=(n,e)=>{var t,r,o;n.style.backgroundColor=(t=e.codeBlockBackgroundColor)!=null?t:"var(--persona-container, #f3f4f6)",n.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",n.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Hh=(n,e)=>{var m,f,g,u,v;let t=n.toolCall,r=(m=e==null?void 0:e.features)==null?void 0:m.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=Rh(n,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?gu(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(u=e==null?void 0:e.toolCall)!=null?u:{},c=a;return o==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ki(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ki(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},fm=(n,e,t)=>{var m;let r=ps.has(n),o=(m=t==null?void 0:t.toolCall)!=null?m:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=Ae(r?"chevron-up":"chevron-down",16,f,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Qi=(n,e)=>{var V,ne,Re,Ue,xe,Ie,_e,Se,ve;let t=n.toolCall,r=(V=e==null?void 0:e.toolCall)!=null?V:{},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=(Re=(ne=e==null?void 0:e.features)==null?void 0:ne.toolCallDisplay)!=null?Re:{},a=s.expandable!==!1,i=a&&ps.has(n.id),{summary:d,previewText:c,isActive:m}=Hh(n,e),f=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((Ue=t.startedAt)!=null?Ue:Date.now()),x=()=>{let re=b("span","");return re.setAttribute("data-tool-elapsed",v),re.textContent=Rs(t),re},I=(Ie=r.renderCollapsedSummary)==null?void 0:Ie.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(xe=s.collapsedMode)!=null?xe:"tool-call",isActive:m,config:e!=null?e:{},elapsed:Rs(t),createElapsedElement:x});typeof I=="string"&&I.trim()?(u.textContent=I,g.appendChild(u)):I instanceof HTMLElement?g.appendChild(I):(u.textContent=d,g.appendChild(u));let M=(_e=s.loadingAnimation)!=null?_e:"none",E=r.activeTextTemplate,F=r.completeTextTemplate,L=m?E:F,R=I instanceof HTMLElement,A=(re,X,ie)=>{let he=ie;for(let oe of X){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(he)),K.textContent=oe===" "?"\xA0":oe,re.appendChild(K),he++}return he},W=(re,X)=>{var K;u.textContent="";let ie=((K=t.name)==null?void 0:K.trim())||"tool",he=Aa(re,ie),oe=0;for(let te of he){let qe=te.styles.length>0?(()=>{let Y=b("span",te.styles.map(le=>`persona-tool-text-${le}`).join(" "));return u.appendChild(Y),Y})():u;if(te.isDuration&&m)qe.appendChild(x());else{let Y=te.isDuration?Rs(t):te.text;X?oe=A(qe,Y,oe):qe.appendChild(document.createTextNode(Y))}}};if(!R)if(m&&M!=="none"){let re=(Se=r.loadingAnimationDuration)!=null?Se:2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${re}ms`),L&&W(L,!1);else if(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${re}ms`),M==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),L)W(L,!0);else{let X=u.textContent||d;u.textContent="",A(u,X,0)}}else L&&W(L,!1);let N=null;if(a){N=b("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=Ae(i?"chevron-up":"chevron-down",16,re,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show";let ie=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(N),f.append(g,ie)}else f.append(g);let D=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&c){let re=(ve=r.renderCollapsedPreview)==null?void 0:ve.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:m,config:e!=null?e:{}});Wh(D,re)||(D.textContent=c),D.style.display=""}if(!i&&m&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,D),o;let k=b("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),t.name){let re=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=t.name,k.appendChild(re)}if(t.args!==void 0){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let ie=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=rs(t.args),re.append(X,ie),k.appendChild(re)}if(t.chunks&&t.chunks.length){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let ie=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=t.chunks.join(""),re.append(X,ie),k.appendChild(re)}if(t.status==="complete"&&t.result!==void 0){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let ie=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=rs(t.result),re.append(X,ie),k.appendChild(re)}if(t.status==="complete"&&typeof t.duration=="number"){let re=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${t.duration}ms`,k.appendChild(re)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=Ae(i?"chevron-up":"chevron-down",16,re,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),o.append(f,D,k),o};var Ya=new Map,Bh=n=>{let t=(n.startsWith(ko)?n.slice(ko.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)},hm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,ym=(n,e)=>{var r,o,s;let t=(o=(r=hm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ya.get(n))!=null?s:t==="expanded"},bm=(n,e,t)=>{var a,i;let r=hm(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ae(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},vm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=ym(n,t);bm(r,s,t),o.style.display=s?"":"none"};var Za=(n,e)=>{var W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re;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=(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))",!t)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(D=r==null?void 0:r.titleColor)!=null?D:"currentColor",m=Ae(d,20,c,2);m&&i.appendChild(m);let f=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",g.appendChild(u),!o){let X=b("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",t.status),t.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"):t.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"):t.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"),g.appendChild(X)}f.appendChild(g);let x=t.toolType==="webmcp"||t.toolName.startsWith(ko)?yi(t.toolName):void 0,I=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),M=!t.toolName,E=I||(M?t.description:`The assistant wants to use \u201C${x!=null?x:Bh(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=E,f.appendChild(F),t.reason){let X=b("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 ie=b("span","persona-font-medium");ie.textContent=`${(V=r==null?void 0:r.reasonLabel)!=null?V:"Agent's stated reason:"} `,X.appendChild(ie),X.appendChild(document.createTextNode(t.reason)),f.appendChild(X)}let L=(ne=r==null?void 0:r.detailsDisplay)!=null?ne:"collapsed",R=!!t.description&&!M,A=R||!!t.parameters;if(L!=="hidden"&&A){let X=ym(n.id,e),ie=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");ie.type="button",ie.setAttribute("data-expand-header","true"),ie.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let he=b("span");he.setAttribute("data-approval-details-label","true");let oe=b("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),ie.append(he,oe),bm(ie,X,e),f.appendChild(ie);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=X?"":"none",R){let te=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=t.description,K.appendChild(te)}if(t.parameters){let te=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&&(te.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.style.fontSize="0.75rem",te.style.lineHeight="1rem",te.textContent=rs(t.parameters),K.appendChild(te)}f.appendChild(K)}if(o){let X=b("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let ie=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");ie.type="button",ie.style.backgroundColor=(Re=r==null?void 0:r.approveButtonColor)!=null?Re:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(Ue=r==null?void 0:r.approveButtonTextColor)!=null?Ue:"#ffffff",ie.setAttribute("data-approval-action","approve");let he=Ae("shield-check",14,(xe=r==null?void 0:r.approveButtonTextColor)!=null?xe:"#ffffff",2);he&&(he.style.marginRight="4px",ie.appendChild(he));let oe=document.createTextNode((Ie=r==null?void 0:r.approveLabel)!=null?Ie:"Approve");ie.appendChild(oe);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=(_e=r==null?void 0:r.denyButtonColor)!=null?_e:"transparent",K.style.color=(Se=r==null?void 0:r.denyButtonTextColor)!=null?Se:"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 te=Ae("shield-x",14,(ve=r==null?void 0:r.denyButtonTextColor)!=null?ve:"var(--persona-feedback-error, #dc2626)",2);te&&(te.style.marginRight="4px",K.appendChild(te));let qe=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");K.appendChild(qe),X.append(ie,K),f.appendChild(X)}return a.append(i,f),s.appendChild(a),s};var xm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let m=(c==null?void 0:c.agentPushed)===!0;if(m||(t=null),!o||!o.length||!m&&(i!=null?i:s?s.getMessages():[]).some(I=>I.role==="user"))return;let f=document.createDocumentFragment(),g=s?s.isStreaming():!1,u=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(v=>{let x=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=u(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",m&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),e.push(x)}),n.appendChild(f),m){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Ys=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 Zs=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 Dh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Nh=new Set(["step_start","execution_start"]),Fh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Oh=new Set(["step_complete","agent_turn_complete"]),_h=new Set(["flow_complete","agent_complete"]),wm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Am=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Xn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Bo=(n,e)=>{let t=n[e];return Am(t)?t:void 0};function Xi(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function ei(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function $h(n,e){return typeof e.type=="string"?e.type:n}function Uh(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 qh(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 Cm(n){var r,o,s,a,i;let e=Bo(n,"result"),t=[Bo(n,"tokens"),Bo(n,"totalTokens"),e?Bo(e,"tokens"):void 0,Bo(n,"usage"),e?Bo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=Xn(d.output))!=null?r:Xn(d.outputTokens))!=null?o:Xn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Xn(n.outputTokens))!=null?s:Xn(n.completionTokens))!=null?i:e?(a=Xn(e.outputTokens))!=null?a:Xn(e.completionTokens):void 0}function zh(n){var t,r,o,s,a;let e=Bo(n,"result");return(a=(o=(r=(t=Xn(n.executionTime))!=null?t:Xn(n.executionTimeMs))!=null?r:Xn(n.execution_time))!=null?o:Xn(n.duration))!=null?a:e?(s=Xn(e.executionTime))!=null?s:Xn(e.executionTimeMs):void 0}function jh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ea=class{constructor(e=jh){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:ei(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(!Am(t)){wm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=$h(e,t),o=this.now();if(Dh.has(r)){this.startRun(o);return}if(Nh.has(r)){this.run||this.startRun(o);return}if(Fh.has(r)){if(!qh(r,t))return;let a=Uh(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+Xi(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ei(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Oh.has(r)){if(!this.run)return;let a=this.run,i=Cm(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Xi(a.visibleCharCount),m=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:ei(c,m),outputTokens:c,durationMs:m,source:d?"usage":"estimate"};return}if(_h.has(r)){if(!this.run)return;let a=this.run,i=Cm(t),d=i!=null?i:a.exactOutputTokens+Xi(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:ei(d,m),outputTokens:d,durationMs:m,source:c},this.run=null;return}if(wm.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=zh(t);return s!=null?s:r-e.startedAt}};function us(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Vh={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)"}},Kh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Gh=["flowName","stepName","reasoningText","text","name","tool","toolName"],Qh=100;function Xh(n,e){let t={...Vh,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Kh}function Jh(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function Yh(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 Zh(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 ey(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 ty(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 ny(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function ry(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 oy(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 Ji(n,e,t,r,o,s,a,i){var g;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");us(c,(g=r.classNames)==null?void 0:g.eventRow);let m=a.find(u=>u.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let u=m.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(u)return c.appendChild(u),c}return c.appendChild(f()),c;function f(){var V,ne;let u=b("div",""),v=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",n.id);let x=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),I=Ae(d?"chevron-down":"chevron-right","14px","currentColor",2);I&&x.appendChild(I);let M=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=(V=r.timestampFormat)!=null?V:"relative";M.textContent=E==="relative"?Jh(n.timestamp,t):Yh(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 L=Xh(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=L.bg,R.style.color=L.text,R.style.borderColor=L.text+"50",R.textContent=n.type;let A=(ne=r.descriptionFields)!=null?ne:Gh,W=Zh(n.payload,A),N=null;W&&(N=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=W);let D=b("div","persona-flex-1 persona-min-w-0"),k=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"),j=Ae("clipboard","12px","currentColor",1.5);return j&&k.appendChild(j),k.addEventListener("click",async Re=>{Re.stopPropagation(),await ey(ty(n)),k.innerHTML="";let Ue=Ae("check","12px","currentColor",1.5);Ue&&k.appendChild(Ue),setTimeout(()=>{k.innerHTML="";let xe=Ae("clipboard","12px","currentColor",1.5);xe&&k.appendChild(xe)},1500)}),v.appendChild(x),v.appendChild(M),F&&v.appendChild(F),v.appendChild(R),N&&v.appendChild(N),v.appendChild(D),v.appendChild(k),u.appendChild(v),d&&u.appendChild(oy(n,a,i)),u}}function Sm(n){var v,x,I,M,E;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",m=(I=i==null?void 0:i.label)!=null?I:"",f=(E=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?E:{},g=s.find(F=>F.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let F=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>u().element,onClose:r});if(F)return{element:F,update:()=>{},destroy:()=>{}}}return u();function u(){let F=f.classNames,L=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");us(L,F==null?void 0:F.panel);let R=[],A="",W="",N=null,D=[],k={},j=0,V=Da(),ne=0,Re=0,Ue=!1,xe=null,Ie=!1,_e=0,Se=new Set,ve=new Map,re="",X="",ie=null,he,oe,K,te,qe,Y=null,le=null,Pe=null;function it(){let G=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),de=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");us(de,F==null?void 0:F.headerBar);let ke=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(ke.textContent="Events",he=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"),he.textContent="0",a){le=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let Jn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Jn.textContent="Throughput",Y=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"),Y.textContent="-- tok/s",Pe=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"),Pe.style.display="none",Pe.style.pointerEvents="none";let An=le,en=Pe,In=()=>{if(!en.textContent)return;let xt=An.getBoundingClientRect(),Nn=G.getBoundingClientRect();en.style.left=`${xt.left-Nn.left}px`,en.style.top=`${xt.bottom-Nn.top+4}px`,en.style.display="block"},yr=()=>{en.style.display="none"};le.addEventListener("mouseenter",In),le.addEventListener("mouseleave",yr),le.appendChild(Jn),le.appendChild(Y)}let vt=b("div","persona-flex-1");oe=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 Yt=b("option","");Yt.value="",Yt.textContent="All events",oe.appendChild(Yt),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 pn=Ae("clipboard-copy","12px","currentColor",1.5);pn&&K.appendChild(pn);let Ht=b("span","persona-text-xs");Ht.textContent="Copy All",K.appendChild(Ht),de.appendChild(ke),de.appendChild(he),le&&de.appendChild(le),de.appendChild(vt),de.appendChild(oe),de.appendChild(K);let et=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");us(et,F==null?void 0:F.searchBar);let Rt=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),ct=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");Rt&&ct.appendChild(Rt),te=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"),us(te,F==null?void 0:F.searchInput),te.type="text",te.placeholder="Search event payloads...",qe=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"),qe.type="button",qe.style.display="none";let Kt=Ae("x","12px","currentColor",2);return Kt&&qe.appendChild(Kt),et.appendChild(ct),et.appendChild(te),et.appendChild(qe),G.appendChild(de),G.appendChild(et),Pe&&G.appendChild(Pe),G}let lt,rt=s.find(G=>G.renderEventStreamToolbar);if(rt!=null&&rt.renderEventStreamToolbar&&o){let G=rt.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:e.getSize(),filteredCount:0,onFilterChange:de=>{A=de,It(),hn()},onSearchChange:de=>{W=de,It(),hn()}});lt=G!=null?G: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 pe(){if(!a||!Y||!le)return;let G=a();Y.textContent=ny(G);let de=ry(G);Pe&&(Pe.textContent=de,de||(Pe.style.display="none")),de?le.setAttribute("aria-label",de):le.removeAttribute("aria-label")}let Xe=b("div","persona-flex-1 persona-min-h-0 persona-relative"),J=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ce=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");us(ce,F==null?void 0:F.scrollIndicator),ce.style.display="none",ce.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let we=Ae(c,"14px","currentColor",2);we&&ce.appendChild(we);let je=b("span","");je.textContent=m,ce.appendChild(je);let Pt=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Pt.style.display="none",Xe.appendChild(J),Xe.appendChild(Pt),Xe.appendChild(ce),L.setAttribute("tabindex","0"),L.appendChild(lt),L.appendChild(Ee),L.appendChild(Xe);function Te(){let G=e.getAll(),de={};for(let Ht of G)de[Ht.type]=(de[Ht.type]||0)+1;let ke=Object.keys(de).sort(),vt=ke.length!==D.length||!ke.every((Ht,et)=>Ht===D[et]),Yt=!vt&&ke.some(Ht=>de[Ht]!==k[Ht]),Zt=G.length!==Object.values(k).reduce((Ht,et)=>Ht+et,0);if(!vt&&!Yt&&!Zt||(D=ke,k=de,!oe))return;let pn=oe.value;if(oe.options[0].textContent="All events",vt){for(;oe.options.length>1;)oe.remove(1);for(let Ht of ke){let et=b("option","");et.value=Ht,et.textContent=`${Ht} (${de[Ht]||0})`,oe.appendChild(et)}pn&&ke.includes(pn)?oe.value=pn:pn&&(oe.value="",A="")}else for(let Ht=1;Ht<oe.options.length;Ht++){let et=oe.options[Ht];et.textContent=`${et.value} (${de[et.value]||0})`}}function me(){let G=e.getAll();if(A&&(G=G.filter(de=>de.type===A)),W){let de=W.toLowerCase();G=G.filter(ke=>ke.type.toLowerCase().includes(de)||ke.payload.toLowerCase().includes(de))}return G}function fn(){return A!==""||W!==""}function It(){j=0,ne=0,V.resume(),ce.style.display="none"}function rn(G){Se.has(G)?Se.delete(G):Se.add(G),ie=G;let de=J.scrollTop,ke=V.isFollowing();Ie=!0,V.pause(),hn(),J.scrollTop=de,ke&&V.resume(),Ie=!1}function hr(){return Ro(J,50)}function hn(){Re=Date.now(),Ue=!1,pe(),Te();let G=e.getEvictedCount();G>0?(Ee.textContent=`${G.toLocaleString()} older events truncated`,Ee.style.display=""):Ee.style.display="none",R=me();let de=R.length,ke=e.getSize()>0;he&&(he.textContent=String(e.getSize())),de===0&&ke&&fn()?(Pt.textContent=W?`No events matching '${W}'`:"No events matching filter",Pt.style.display="",J.style.display="none"):(Pt.style.display="none",J.style.display=""),K&&(K.title=fn()?`Copy Filtered (${de})`:"Copy All"),d&&!V.isFollowing()&&de>j&&(ne+=de-j,je.textContent=m?`${m}${ne>0?` (${ne})`:""}`:"",ce.style.display=""),j=de;let vt=e.getAll(),Yt=vt.length>0?vt[0].timestamp:0,Zt=new Set(R.map(et=>et.id));for(let et of Se)Zt.has(et)||Se.delete(et);let pn=A!==re||W!==X,Ht=ve.size===0&&R.length>0;if(pn||Ht||R.length===0){J.innerHTML="",ve.clear();let et=document.createDocumentFragment();for(let Rt=0;Rt<R.length;Rt++){let ct=Ji(R[Rt],Rt,Yt,f,Se,rn,s,o);ve.set(R[Rt].id,ct),et.appendChild(ct)}J.appendChild(et),re=A,X=W,ie=null}else{if(ie!==null){let Rt=ve.get(ie);if(Rt&&Rt.parentNode===J){let ct=R.findIndex(Kt=>Kt.id===ie);if(ct>=0){let Kt=Ji(R[ct],ct,Yt,f,Se,rn,s,o);J.insertBefore(Kt,Rt),Rt.remove(),ve.set(ie,Kt)}}ie=null}let et=new Set(R.map(Rt=>Rt.id));for(let[Rt,ct]of ve)et.has(Rt)||(ct.remove(),ve.delete(Rt));for(let Rt=0;Rt<R.length;Rt++){let ct=R[Rt];if(!ve.has(ct.id)){let Kt=Ji(ct,Rt,Yt,f,Se,rn,s,o);ve.set(ct.id,Kt),J.appendChild(Kt)}}}V.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Ve(){if(Date.now()-Re>=Qh){xe!==null&&(cancelAnimationFrame(xe),xe=null),hn();return}Ue||(Ue=!0,xe=requestAnimationFrame(()=>{xe=null,hn()}))}let T=(G,de)=>{if(!K)return;K.innerHTML="";let ke=Ae(G,"12px","currentColor",1.5);ke&&K.appendChild(ke);let vt=b("span","persona-text-xs");vt.textContent="Copy All",K.appendChild(vt),setTimeout(()=>{K.innerHTML="";let Yt=Ae("clipboard-copy","12px","currentColor",1.5);Yt&&K.appendChild(Yt);let Zt=b("span","persona-text-xs");Zt.textContent="Copy All",K.appendChild(Zt),K.disabled=!1},de)},ue=async()=>{if(K){K.disabled=!0;try{let G;fn()?G=R:t?(G=await t(),G.length===0&&(G=e.getAll())):G=e.getAll();let de=G.map(ke=>{try{return JSON.parse(ke.payload)}catch{return ke.payload}});await navigator.clipboard.writeText(JSON.stringify(de,null,2)),T("check",1500)}catch{T("x",1500)}}},Le=()=>{oe&&(A=oe.value,It(),hn())},Me=()=>{!te||!qe||(qe.style.display=te.value?"":"none",N&&clearTimeout(N),N=setTimeout(()=>{W=te.value,It(),hn()},150))},He=()=>{!te||!qe||(te.value="",W="",qe.style.display="none",N&&clearTimeout(N),It(),hn())},Ze=()=>{if(Ie)return;let G=J.scrollTop,{action:de,nextLastScrollTop:ke}=Na({following:V.isFollowing(),currentScrollTop:G,lastScrollTop:_e,nearBottom:hr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});_e=ke,de==="resume"?(V.resume(),ne=0,ce.style.display="none"):de==="pause"&&(V.pause(),d&&(je.textContent=m,ce.style.display=""))},Ge=G=>{let de=Fa({following:V.isFollowing(),deltaY:G.deltaY,nearBottom:hr(),resumeWhenNearBottom:!0});de==="pause"?(V.pause(),d&&(je.textContent=m,ce.style.display="")):de==="resume"&&(V.resume(),ne=0,ce.style.display="none")},ut=()=>{d&&(J.scrollTop=J.scrollHeight,V.resume(),ne=0,ce.style.display="none")},Wt=G=>{let de=G.target;if(!de||de.closest("button"))return;let ke=de.closest("[data-event-id]");if(!ke)return;let vt=ke.getAttribute("data-event-id");vt&&rn(vt)},q=G=>{if((G.metaKey||G.ctrlKey)&&G.key==="f"){G.preventDefault(),te==null||te.focus(),te==null||te.select();return}G.key==="Escape"&&(te&&document.activeElement===te?(He(),te.blur(),L.focus()):r&&r())};K&&K.addEventListener("click",ue),oe&&oe.addEventListener("change",Le),te&&te.addEventListener("input",Me),qe&&qe.addEventListener("click",He),J.addEventListener("scroll",Ze),J.addEventListener("wheel",Ge,{passive:!0}),J.addEventListener("click",Wt),ce.addEventListener("click",ut),L.addEventListener("keydown",q);function ot(){N&&clearTimeout(N),xe!==null&&(cancelAnimationFrame(xe),xe=null),Ue=!1,ve.clear(),K&&K.removeEventListener("click",ue),oe&&oe.removeEventListener("change",Le),te&&te.removeEventListener("input",Me),qe&&qe.removeEventListener("click",He),J.removeEventListener("scroll",Ze),J.removeEventListener("wheel",Ge),J.removeEventListener("click",Wt),ce.removeEventListener("click",ut),L.removeEventListener("keydown",q)}return{element:L,update:Ve,destroy:ot}}}function Tm(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=t;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(u)}else f.textContent=a;if(c.append(m,f),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${t}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Mm=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",m=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Tm(n,e)});if(m)return m}return Tm(n,e)};var Yi=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)})}},Do=new Yi;Do.register("PersonaArtifactCard",Mm);function sy(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 Em(n,e){var oe,K,te,qe;let t=(K=(oe=n.features)==null?void 0:oe.artifacts)==null?void 0:K.layout,o=((te=t==null?void 0:t.toolbarPreset)!=null?te:"default")==="document",s=(qe=t==null?void 0:t.panePadding)==null?void 0:qe.trim(),a=n.markdown?ga(n.markdown):null,i=fa(n.sanitize),d=Y=>{let le=a?a(Y):so(Y);return i?i(le):le},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let f=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let x="rendered",I=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Cn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Cn({icon:"eye",label:"Rendered view"}),E=o?Cn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Cn({icon:"code-2",label:"Source"}),F=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),L=(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),N=null,D,k=null,j=null;if(o&&(L||R)&&!W){if(D=L?$i({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Y=Ae("chevron-down",14,"currentColor",2);Y&&D.appendChild(Y)}}else o&&W?(N=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=L?$i({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Cn({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(D,k)):o?D=Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=Cn({icon:"copy",label:"Copy"});let V=o?Cn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"refresh-cw",label:"Refresh"}),ne=o?Cn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"x",label:"Close"}),Re=()=>{var lt,rt,Ee;let Y=(lt=ve.find(pe=>pe.id===re))!=null?lt:ve[ve.length-1],le=(rt=Y==null?void 0:Y.id)!=null?rt:null,Pe=(Y==null?void 0:Y.artifactType)==="markdown"&&(Ee=Y.markdown)!=null?Ee:"",it=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:Pe,jsonPayload:it,id:le}},Ue=async()=>{var lt;let{markdown:Y,jsonPayload:le}=Re(),Pe=(lt=ve.find(rt=>rt.id===re))!=null?lt:ve[ve.length-1],it=(Pe==null?void 0:Pe.artifactType)==="markdown"?Y:Pe?le:"";try{await navigator.clipboard.writeText(it)}catch{}};if(D.addEventListener("click",async()=>{let Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(Y&&W){let{markdown:le,jsonPayload:Pe,id:it}=Re();try{await Y({actionId:"primary",artifactId:it,markdown:le,jsonPayload:Pe})}catch{}return}await Ue()}),k&&(A!=null&&A.length)){let Y=()=>{var Pe;return(Pe=f.closest("[data-persona-root]"))!=null?Pe:document.body},le=()=>{j=cs({items:A.map(Pe=>({id:Pe.id,label:Pe.label})),onSelect:async Pe=>{let{markdown:it,jsonPayload:lt,id:rt}=Re(),Ee=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ee?await Ee({actionId:Pe,artifactId:rt,markdown:it,jsonPayload:lt}):Pe==="markdown"||Pe==="md"?await navigator.clipboard.writeText(it):Pe==="json"||Pe==="source"?await navigator.clipboard.writeText(lt):await navigator.clipboard.writeText(it||lt)}catch{}},anchor:N!=null?N:k,position:"bottom-right",portal:Y()})};f.isConnected?le():requestAnimationFrame(le),k.addEventListener("click",Pe=>{Pe.stopPropagation(),j==null||j.toggle()})}V.addEventListener("click",async()=>{var Y;try{await((Y=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Y.call(t))}catch{}ie()}),ne.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let xe=()=>{o&&(M.setAttribute("aria-pressed",x==="rendered"?"true":"false"),E.setAttribute("aria-pressed",x==="source"?"true":"false"))};M.addEventListener("click",()=>{x="rendered",xe(),ie()}),E.addEventListener("click",()=>{x="source",xe(),ie()});let Ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),I.append(M,E),N?F.append(N,V,ne):F.append(D,V,ne),g.append(I,Ie,F),xe()):(g.appendChild(u),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let _e=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Se=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(_e.style.paddingLeft=s,_e.style.paddingRight=s,Se.style.padding=s),f.appendChild(g),f.appendChild(_e),f.appendChild(Se);let ve=[],re=null,X=!1,ie=()=>{var it,lt,rt,Ee;let Y=o&&ve.length<=1;_e.classList.toggle("persona-hidden",Y),_e.replaceChildren();for(let pe of ve){let Xe=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Xe.type="button",Xe.textContent=pe.title||pe.id.slice(0,8),pe.id===re&&Xe.classList.add("persona-bg-persona-container","persona-border-persona-border"),Xe.addEventListener("click",()=>e.onSelect(pe.id)),_e.appendChild(Xe)}Se.replaceChildren();let le=re&&ve.find(pe=>pe.id===re)||ve[ve.length-1];if(!le)return;if(o){let pe=le.artifactType==="markdown"?"MD":(it=le.component)!=null?it:"Component",J=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${J} \xB7 ${pe}`}else u.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&x==="source"){let Xe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Xe.textContent=(lt=le.markdown)!=null?lt:"",Se.appendChild(Xe);return}let pe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");pe.innerHTML=d((rt=le.markdown)!=null?rt:""),Se.appendChild(pe);return}let Pe=le.component?Do.get(le.component):void 0;if(Pe){let Xe={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let J=Pe((Ee=le.props)!=null?Ee:{},Xe);if(J){Se.appendChild(J);return}}catch{}}Se.appendChild(sy(le))},he=()=>{var le;let Y=ve.length>0;if(f.classList.toggle("persona-hidden",!Y),c){let Pe=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,lt=((le=Pe==null?void 0:Pe.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&lt&&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(Y){var le,Pe,it;ve=Y.artifacts,re=(it=(Pe=Y.selectedId)!=null?Pe:(le=Y.artifacts[Y.artifacts.length-1])==null?void 0:le.id)!=null?it:null,ve.length>0&&(X=!0),ie(),he()},setMobileOpen(Y){X=Y,!Y&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):he()}}}function ar(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 km(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"),!ar(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 ay(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ti(n,e){var d,c,m,f,g,u,v,x,I,M;if(!ar(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"),ay(n),km(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(m=t==null?void 0:t.splitGap)!=null?m:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=t==null?void 0:t.paneBackground)==null?void 0:u.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(I=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:I.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=t==null?void 0:t.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"),km(n,e)}var Lm=["panel","seamless"];function ni(n,e){var i,d,c,m,f,g;for(let u of Lm)n.classList.remove(`persona-artifact-appearance-${u}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!ar(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=Lm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(m=t==null?void 0:t.paneBorderRadius)==null?void 0:m.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let u=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;u&&n.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Pm(n,e){var t,r,o;return!e||!ar(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function iy(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 ly(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 cy(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function dy(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Im(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 Wm(n,e,t,r,o,s){let a=iy(o,200),i=dy(e,t,r,200);i=Math.max(a,i);let d=ly(s);return d!==null&&(i=Math.min(i,d)),cy(n,a,i)}var Rm={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"}},Zi=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,I;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Rm[a])!=null?x:Rm.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 M=b("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var A,W;let E=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");E.htmlFor=`${e.id}-${a}-${M.name}`;let F=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=M.label,E.appendChild(F);let L=(A=M.type)!=null?A:"text",R;L==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=L),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}-${M.name}`,R.name=M.name,R.placeholder=(W=M.placeholder)!=null?W:"",M.required&&(R.required=!0),E.appendChild(R),m.appendChild(E)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");u.type="submit",u.textContent=(I=i.submitLabel)!=null?I:"Submit",f.appendChild(g),f.appendChild(u),m.appendChild(f),s.replaceChildren(d,m),m.addEventListener("submit",async M=>{var R,A;M.preventDefault();let E=(R=t.formEndpoint)!=null?R:"/form",F=new FormData(m),L={};F.forEach((W,N)=>{L[N]=W}),L.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let N=await W.json();g.textContent=(A=N.message)!=null?A:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var el=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()}},tl=new el;var Hm=()=>{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 py=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},uy=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},rl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=py(n),t=uy(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}},nl=n=>typeof n=="string"?n:n==null?"":String(n),ta={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:nl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=nl(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:nl(t.text)}}},Bm=n=>Array.isArray(n)?n.map(e=>String(e)):[],ol=n=>{let e=new Set(Bm(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Bm(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,m)=>c||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let m=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:m});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:t}};var my=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}},gy=n=>n.map(e=>({...e,streaming:!1})),fy=n=>n.map(e=>({...e,status:"complete"})),Dm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?my(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?gy(t.messages):void 0,artifacts:t.artifacts?fy(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 sl=require("partial-json");function Nm(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Do.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 Fm(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 Om(n){let e=Fm(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 _m(n){let e=Fm(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 hy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function $m(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=hy}=n,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,u.appendChild(x),g.appendChild(u);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];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=`
29
31
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
30
32
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
31
33
  </svg>
32
- `,W.addEventListener("click",()=>{f=A,M.forEach((N,D)=>{let k=D<A;N.classList.toggle("selected",k),N.setAttribute("aria-checked",D===A-1?"true":"false")})}),M.push(W),I.appendChild(W)}g.appendChild(I);let E=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),A.appendChild(E),g.appendChild(A)}let F=document.createElement("div");F.className="persona-feedback-actions";let L=document.createElement("button");L.type="button",L.className="persona-feedback-btn persona-feedback-btn-skip",L.textContent=i,L.addEventListener("click",()=>{t==null||t(),m.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){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=(E==null?void 0:E.value.trim())||void 0;await e(f,A),m.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),F.appendChild(L),F.appendChild(R),g.appendChild(F),m.appendChild(g),m}function Fm(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:m="Very likely"}=n,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=o,v.appendChild(I),u.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 E=document.createElement("div");E.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let L=document.createElement("span");L.className="persona-feedback-label-high",L.textContent=m,E.appendChild(F),E.appendChild(L);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let j=0;j<=10;j++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${j} out of 10`),V.textContent=String(j),V.dataset.rating=String(j),j<=6?V.classList.add("persona-feedback-detractor"):j<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{g=j,A.forEach((ne,Re)=>{ne.classList.toggle("selected",Re===j),ne.setAttribute("aria-checked",Re===j?"true":"false")})}),A.push(V),R.appendChild(V)}M.appendChild(E),M.appendChild(R),u.appendChild(M);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),u.appendChild(j)}let N=document.createElement("div");N.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{t==null||t(),f.remove()});let 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(g===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await e(g,j),f.remove()}catch(j){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),N.appendChild(D),N.appendChild(k),u.appendChild(N),f.appendChild(u),f}var ms="persona-chat-history",dy=30*1e3,py={"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 uy(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=py[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 ri(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 my(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 gy(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var al=n=>!n||typeof n!="object"?{}:{...n},Om=n=>n.map(e=>({...e,streaming:!1})),_m=(n,e,t)=>{let r=n!=null&&n.markdown?ga(n.markdown):null,o=fa(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var m,f,g;let a=(m=s.text)!=null?m:"",i=(f=s.message.rawContent)!=null?f:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&t&&t())}let d=Eo()!==null,c;if(n!=null&&n.postprocessMessage){let u=n.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});c=o?o(u):u}else if(r){let u=r(a);c=o&&d?o(u):u}else c=so(a);return c}};function $m(n){var i,d,c,m;let e=b("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(m=n==null?void 0:n.iconStrokeWidth)!=null?m:.5,a=Ae(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let f=b("span","persona-drop-overlay-label");f.textContent=n.label,e.appendChild(f)}return e}var Um=(n,e,t)=>{var _l,$l,Ul,ql,zl,jl,Vl,Kl,Gl,Ql,Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=Bu(e),o=tl.getForInstance(r.plugins);r.components&&Do.registerAll(r.components);let s=Pm(),i=r.persistState===!1?null:(_l=r.storageAdapter)!=null?_l:Wm(),d={},c=null,m=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(m=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(d=al(h.metadata)),($l=h.messages)!=null&&$l.length&&(r={...r,initialMessages:h.messages}),(Ul=h.artifacts)!=null&&Ul.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(ql=h.selectedArtifactId)!=null?ql:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(zl=l.messages)!=null&&zl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>d,u=l=>{var h;d=(h=l({...d}))!=null?h:{},Zr()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ta.message,ta.messageAndClick],I=ol({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});I.syncFromMetadata();let M=(Vl=(jl=r.launcher)==null?void 0:jl.enabled)!=null?Vl:!0,E=(Gl=(Kl=r.launcher)==null?void 0:Kl.autoExpand)!=null?Gl:!1,F=(Ql=r.autoFocusInput)!=null?Ql:!1,L=E,R=M,A=(Jl=(Xl=r.layout)==null?void 0:Xl.header)==null?void 0:Jl.layout,W=!1,N=()=>Qs(r),D=()=>M||N(),k=N()?!1:M?E:!0,j=!1,V=null,ne=()=>{j=!0,V&&clearTimeout(V),V=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},Re=_m(r,I,ne),Ue=(Zl=(Yl=r.features)==null?void 0:Yl.showReasoning)!=null?Zl:!0,xe=(tc=(ec=r.features)==null?void 0:ec.showToolCalls)!=null?tc:!0,Ie=(rc=(nc=r.features)==null?void 0:nc.showEventStreamToggle)!=null?rc:!1,_e=(sc=(oc=r.features)==null?void 0:oc.scrollToBottom)!=null?sc:{},Se=(ic=(ac=r.features)==null?void 0:ac.scrollBehavior)!=null?ic:{},re=`${(cc=typeof r.persistState=="object"?(lc=r.persistState)==null?void 0:lc.keyPrefix:void 0)!=null?cc:"persona-"}event-stream`,X=Ie?new Zs(re):null,ie=(uc=(pc=(dc=r.features)==null?void 0:dc.eventStream)==null?void 0:pc.maxEvents)!=null?uc:2e3,he=Ie?new Ys(ie,X):null,oe=Ie?new ea:null,K=null,te=!1,qe=null,Y=0;X==null||X.open().then(()=>he==null?void 0:he.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let le={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)}},Pe=(mc=r.statusIndicator)!=null?mc:{},it=l=>{var p,h,y,S;return l==="idle"?(p=Pe.idleText)!=null?p:xn.idle:l==="connecting"?(h=Pe.connectingText)!=null?h:xn.connecting:l==="connected"?(y=Pe.connectedText)!=null?y:xn.connected:l==="error"?(S=Pe.errorText)!=null?S:xn.error:xn[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 rt=im({config:r,showClose:D()}),{wrapper:Ee,panel:pe,pillRoot:Xe}=rt.shell,J=rt.panelElements,{container:ce,body:we,messagesWrapper:je,suggestions:Pt,textarea:Te,sendButton:me,sendButtonWrapper:fn,composerForm:It,statusText:rn,introTitle:hr,introSubtitle:hn,closeButton:Ve,iconHolder:T,headerTitle:ue,headerSubtitle:Le,header:Me,footer:He,actionsRow:Ze,leftActions:Ge,rightActions:ut}=J,Wt=J.setSendButtonMode,q=J.micButton,ot=J.micButtonWrapper,G=J.attachmentButton,de=J.attachmentButtonWrapper,ke=J.attachmentInput,vt=J.attachmentPreviewsContainer;ce.classList.add("persona-relative"),we.classList.add("persona-relative");let Yt=12,Zt=()=>{var l;return(l=_e.label)!=null?l:""},pn=()=>{var l;return(l=_e.iconName)!=null?l:"arrow-down"},Ht=()=>_e.enabled!==!1,et=()=>{var l;return(l=Se.mode)!=null?l:"follow"},Rt=()=>{var l;return(l=Se.anchorTopOffset)!=null?l:16},ct=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");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let Kt=b("span","persona-flex persona-items-center"),Jn=b("span",""),An=b("span","");An.setAttribute("data-persona-scroll-to-bottom-count",""),An.style.display="none",ct.append(Kt,Jn,An),ce.appendChild(ct);let en=b("div","persona-stream-anchor-spacer");en.setAttribute("aria-hidden","true"),en.setAttribute("data-persona-anchor-spacer",""),en.style.flexShrink="0",en.style.pointerEvents="none",en.style.height="0px",we.appendChild(en);let In=()=>{let p=He.style.display==="none"?0:He.offsetHeight;ct.style.bottom=`${p+Yt}px`};In();let yr=()=>{let l=!!Zt();ct.setAttribute("aria-label",Zt()||"Jump to latest"),ct.title=Zt(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Kt.innerHTML="";let p=Ae(pn(),"14px","currentColor",2);p?(Kt.appendChild(p),Kt.style.display=""):Kt.style.display="none",Jn.textContent=Zt(),Jn.style.display=l?"":"none"};yr();let xt=null,Nn=null,br=o.find(l=>l.renderHeader);if(br!=null&&br.renderHeader){let l=br.renderHeader({config:r,defaultRenderer:()=>{let p=Ho({config:r,showClose:D()});return Xs(ce,p,r),p.header},onClose:()=>$t(!1,"user")});if(l){let p=ce.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Me=l,rt.header.element=l)}}let Pr=()=>{var p,h,y,S;if(!he)return;if(te=!0,!K&&he&&(K=xm({buffer:he,getFullHistory:()=>he.getAllFromStore(),onClose:()=>ir(),config:r,plugins:o,getThroughput:()=>{var H;return(H=oe==null?void 0:oe.getMetric())!=null?H:{status:"idle"}}})),K&&(we.style.display="none",(p=He.parentNode)==null||p.insertBefore(K.element,He),K.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Pn.actionIconColor}`;let H=(S=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:S.toggleButtonActive;H&&H.split(/\s+/).forEach(z=>z&&yt.classList.add(z))}let l=()=>{if(!te)return;let H=Date.now();H-Y>=200&&(K==null||K.update(),Y=H),qe=requestAnimationFrame(l)};Y=0,qe=requestAnimationFrame(l),Je(),s.emit("eventStream:opened",{timestamp:Date.now()})},ir=()=>{var l,p,h;if(te){if(te=!1,K&&K.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let y=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(S=>S&&yt.classList.remove(S))}qe!==null&&(cancelAnimationFrame(qe),qe=null),Je(),s.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(Ie){let l=(fc=(gc=r.features)==null?void 0:gc.eventStream)==null?void 0:fc.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=b("button",p),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=Ae("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let y=J.clearChatButtonWrapper,S=J.closeButtonWrapper,H=y||S;H&&H.parentNode===Me?Me.insertBefore(yt,H):Me.appendChild(yt),yt.addEventListener("click",()=>{te?ir():Pr()})}let uo=l=>{var S,H,z,O,B;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=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 se=l.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(h,se):l.insertBefore(h,l.firstChild)}if(!((H=l.querySelector("[data-persona-composer-attachment-input]"))!=null?H:l.querySelector('input[type="file"]'))){let se=b("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((z=p.allowedTypes)!=null?z:Ur).join(","),se.multiple=((O=p.maxFiles)!=null?O:4)>1,se.style.display="none",se.setAttribute("aria-label",(B=p.buttonTooltipText)!=null?B:"Attach files"),l.appendChild(se)}},vr=o.find(l=>l.renderComposer);if(vr!=null&&vr.renderComposer){let l=r.composer,p=vr.renderComposer({config:r,defaultRenderer:()=>Ja({config:r}).footer,onSubmit:h=>{var z;if(!_||_.isStreaming())return;let y=h.trim(),S=(z=xt==null?void 0:xt.hasAttachments())!=null?z:!1;if(!y&&!S)return;yl();let H;S&&(H=[],H.push(...xt.getContentParts()),y&&H.push(Pi(y))),_.sendMessage(y,{contentParts:H}),S&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ke==null||ke.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:((hc=r.voiceRecognition)==null?void 0:hc.enabled)===!0?()=>{Nn==null||Nn()}:void 0});p&&(rt.replaceComposer(p),He=rt.composer.footer)}let mo=l=>{let p=(...ae)=>{for(let Z of ae){let be=l.querySelector(Z);if(be)return be}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),H=l.querySelector("[data-persona-composer-mic]"),z=l.querySelector("[data-persona-composer-status]");h&&(It=h),y&&(Te=y),S&&(me=S),H&&(q=H,ot=H.parentElement),z&&(rn=z);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Pt=O);let B=p("[data-persona-composer-attachment-button]",".persona-attachment-button");B&&(G=B,de=B.parentElement),ke=p("[data-persona-composer-attachment-input]",'input[type="file"]'),vt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(Ze=se)};uo(He),mo(He);let Wn=(wc=(yc=r.layout)==null?void 0:yc.contentMaxWidth)!=null?wc:N()?(xc=(vc=(bc=r.launcher)==null?void 0:bc.composerBar)==null?void 0:vc.contentMaxWidth)!=null?xc:"720px":void 0;if(Wn&&(je.style.maxWidth=Wn,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%"),Wn&&It&&!N()&&(It.style.maxWidth=Wn,It.style.marginLeft="auto",It.style.marginRight="auto"),Wn&&Pt&&!N()&&(Pt.style.maxWidth=Wn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Wn&&vt&&!N()&&(vt.style.maxWidth=Wn,vt.style.marginLeft="auto",vt.style.marginRight="auto"),(Cc=r.attachments)!=null&&Cc.enabled&&ke&&vt){xt=$s.fromConfig(r.attachments),xt.setPreviewsContainer(vt),ke.addEventListener("change",h=>{let y=h.target;xt==null||xt.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=$m(l);ce.appendChild(p)}(()=>{var y,S;let l=(S=(y=r.layout)==null?void 0:y.slots)!=null?S:{},p=H=>{switch(H){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return je;case"footer-top":return Pt;case"composer":return It;case"footer-bottom":return rn;default:return null}},h=(H,z)=>{var O;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")Me.insertBefore(z,Me.firstChild);else if(H==="header-right")Me.appendChild(z);else{let B=Me.querySelector(".persona-flex-col");B?(O=B.parentNode)==null||O.insertBefore(z,B.nextSibling):Me.appendChild(z)}break;case"body-top":{let B=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(z):we.insertBefore(z,we.firstChild);break}case"body-bottom":we.appendChild(z);break;case"footer-top":Pt.replaceWith(z);break;case"footer-bottom":rn.replaceWith(z);break;default:break}};for(let[H,z]of Object.entries(l))if(z)try{let O=z({config:r,defaultContent:()=>p(H)});O&&h(H,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,O)}})();let jr=l=>{var z,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 H=h.getAttribute("data-bubble-type");if(H==="reasoning")ds.has(S)?ds.delete(S):ds.add(S),dm(S,y);else if(H==="tool")ps.has(S)?ps.delete(S):ps.add(S),pm(S,y,r);else if(H==="approval"){let B=r.approval!==!1?r.approval:void 0,se=((z=B==null?void 0:B.detailsDisplay)!=null?z:"collapsed")==="expanded",ae=(O=Ya.get(S))!=null?O:se;Ya.set(S,!ae),fm(S,y,r)}Sr.delete(S)};je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),jr(l))}),je.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),jr(l))}),je.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let h=je.getRootNode(),y=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let S=y.toString(),H=Uu(S);!H||H===S||(p.setData("text/plain",H),l.preventDefault())});let Ir=new Map,Vr=null,Kr="idle",go={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},fo=(l,p)=>{let{icon:h,label:y}=go[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=Ae(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Gr=()=>{je.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var H;let h=p.closest("[data-actions-for]"),y=(H=h==null?void 0:h.getAttribute("data-actions-for"))!=null?H:null;fo(p,y&&y===Vr?Kr:"idle")})};je.addEventListener("click",l=>{var z;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 H=h.getAttribute("data-action");if(H==="copy"){let B=_.getMessages().find(se=>se.id===S);if(B&&le.onCopy){let se=B.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let ae=Ae("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Ae("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),le.onCopy(B)}}else if(H==="read-aloud")_.toggleReadAloud(S);else if(H==="upvote"||H==="downvote"){let B=((z=Ir.get(S))!=null?z:null)===H,se=H==="upvote"?"thumbs-up":"thumbs-down";if(B){Ir.delete(S),h.classList.remove("persona-message-action-active");let ae=Ae(se,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=H==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${ae}"]`);if(Z){Z.classList.remove("persona-message-action-active");let $e=Ae(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Z.innerHTML="",Z.appendChild($e))}Ir.set(S,H),h.classList.add("persona-message-action-active");let be=Ae(se,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=_.getMessages().find(nt=>nt.id===S);Ce&&le.onFeedback&&le.onFeedback({type:H,messageId:Ce.id,message:Ce})}}}),je.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let H=h.getAttribute("data-approval-action");if(!H)return;let z=H==="approve"?"approved":"denied",B=_.getMessages().find(ae=>ae.id===S);if(!(B!=null&&B.approval))return;let se=y.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,z):_.resolveApproval(B.approval,z)});let Ct=null,Fn=null,On={artifacts:[],selectedId:null},Sn=!1,St={current:null};je.addEventListener("click",l=>{var Z,be,Fe,Ce,nt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Fe=(be=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Fe.call(be,{type:"download",artifactId:y}))===!0)return;let H=_.getArtifactById(y),z=H==null?void 0:H.markdown,O=(H==null?void 0:H.title)||"artifact";if(!z){let $e=h.closest("[data-open-artifact]"),gt=$e==null?void 0:$e.closest("[data-message-id]"),st=gt==null?void 0:gt.getAttribute("data-message-id");if(st){let We=_.getMessages().find(ze=>ze.id===st);if(We!=null&&We.rawContent)try{let ze=JSON.parse(We.rawContent);z=(Ce=ze==null?void 0:ze.props)==null?void 0:Ce.markdown,O=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||O}catch{}}}if(!z)return;let B=new Blob([z],{type:"text/markdown"}),se=URL.createObjectURL(B),ae=document.createElement("a");ae.href=se,ae.download=`${O}.md`,ae.click(),URL.revokeObjectURL(se)}),je.addEventListener("click",l=>{var H,z,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((O=(z=(H=r.features)==null?void 0:H.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:O.call(z,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),Sn=!1,_.selectArtifact(y),Un())}),je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Yn=J.composerOverlay,Zn=(l,p,h)=>{var O,B,se,ae;let y=p.trim();if(!y||!St.current)return;let S=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",H=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:y,answers:h.structured,values:(B=h.values)!=null?B:h.source==="multi"?y.split(", "):[y],isFreeText:H,source:h.source},bubbles:!0,composed:!0})),ts(Yn,S);let z=St.current.getMessages().find(Z=>{var be;return((be=Z.toolCall)==null?void 0:be.id)===S});(se=z==null?void 0:z.agentMetadata)!=null&&se.awaitingLocalTool?St.current.resolveAskUserQuestion(z,(ae=h.structured)!=null?ae:y):St.current.sendMessage(y)},_n=l=>{var S;let p=St.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",y=p.getMessages().find(H=>{var z;return((z=H.toolCall)==null?void 0:z.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:ba(l,y),currentIndex:sr(l)})},Qr=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Wr=l=>{var S,H,z;if(((H=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:H.groupedAutoAdvance)===!1)return;let p=sr(l),h=es(l);if(p>=h-1)return;let y=(z=St.current)==null?void 0:z.getMessages().find(O=>{var B;return((B=O.toolCall)==null?void 0:B.id)===l.getAttribute("data-tool-call-id")});y&&(xa(l,y,r,p+1),_n(l))};Yn.addEventListener("click",l=>{var H,z,O,B,se,ae,Z,be,Fe,Ce,nt,$e,gt,st;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 Be=(H=y.getAttribute("data-tool-call-id"))!=null?H:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ts(Yn,Be);let We=(z=St.current)==null?void 0:z.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Be});(O=We==null?void 0:We.agentMetadata)!=null&&O.awaitingLocalTool&&((B=St.current)==null||B.markAskUserQuestionResolved(We),(se=St.current)==null||se.resolveAskUserQuestion(We,"(dismissed)"));return}if(S==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let We=y.getAttribute("data-multi-select")==="true",ze=io(y);if(ze&&We){let Ke=Po(y)[sr(y)],bt=new Set(Array.isArray(Ke)?Ke:[]);bt.has(Be)?bt.delete(Be):bt.add(Be),lo(y,Array.from(bt)),_n(y);return}if(ze){lo(y,Be),_n(y),Wr(y);return}if(We){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let bt=y.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=Si(y).length===0);return}Zn(y,Be,{source:"pick",values:[Be]});return}if(S==="submit-multi"){let Be=Si(y);if(Be.length===0)return;Zn(y,Be.join(", "),{source:"multi",values:Be});return}if(S==="open-free-text"){let Be=y.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let We=Be.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus()}return}if(S==="focus-free-text"){let Be=y.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(S==="submit-free-text"){let Be=y.querySelector('[data-ask-free-text-input="true"]'),We=(ae=Be==null?void 0:Be.value)!=null?ae:"";if(!We.trim())return;if(io(y)){lo(y,We.trim()),_n(y),Wr(y);return}Zn(y,We,{source:"free-text"});return}if(S==="next"||S==="back"){if(!St.current)return;let Be=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",We=St.current.getMessages().find(Ne=>{var De;return((De=Ne.toolCall)==null?void 0:De.id)===Be});if(!We)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ke=(Fe=(be=ze==null?void 0:ze.value)==null?void 0:be.trim())!=null?Fe:"";if(Ke){let Ne=Po(y)[sr(y)];(typeof Ne!="string"||Ne!==Ke)&&lo(y,Ke)}let bt=S==="next"?1:-1,P=sr(y)+bt;xa(y,We,r,P),_n(y);return}if(S==="submit-all"){if(!St.current)return;let Be=(Ce=y.getAttribute("data-tool-call-id"))!=null?Ce:"",We=St.current.getMessages().find(Ne=>{var De;return((De=Ne.toolCall)==null?void 0:De.id)===Be});if(!We)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ke=($e=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?$e:"";Ke&&lo(y,Ke);let bt=ba(y,We);St.current.persistAskUserQuestionProgress(We,{answers:bt,currentIndex:sr(y)});let P=Qr(bt);Zn(y,P||"(submitted)",{source:"submit-all",structured:bt});return}if(S==="skip"){if(!St.current)return;let Be=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",We=St.current.getMessages().find(De=>{var ge;return((ge=De.toolCall)==null?void 0:ge.id)===Be});if(!We)return;let ze=io(y),Ke=sr(y),bt=es(y),P=Ke>=bt-1;if(!ze){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ts(Yn,Be),(st=We.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(We),St.current.resolveAskUserQuestion(We,"(dismissed)"));return}lo(y,"");let Ne=y.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),P){let De=ba(y,We),ge=Qr(De);Zn(y,ge||"(skipped)",{source:"submit-all",structured:De});return}xa(y,We,r,Ke+1),_n(y);return}}),Yn.addEventListener("keydown",l=>{var H;if(l.key!=="Enter")return;let h=l.target;if(!((H=h.matches)!=null&&H.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let S=h.value;if(S.trim()){if(io(y)){lo(y,S.trim()),_n(y),Wr(y);return}Zn(y,S,{source:"free-text"})}});let Xr=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=Yn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),H=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];H&&(l.preventDefault(),H.click())};document.addEventListener("keydown",Xr);let $n=null,Bt=null,Tn=null,er=null,Jr=()=>{};function Rr(){er==null||er(),er=null}let Yr=()=>{var z;if(!$n||!Bt)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((z=n.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let y=$n.firstElementChild;if(!y||y===Bt)return;let S=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${S}px`,Bt.style.zIndex="5";let H=y.offsetWidth-S/2;Bt.style.left=`${Math.max(0,H)}px`},xr=()=>{},Un=()=>{var h,y,S,H,z;if(!Ct||!ar(r))return;ti(n,r),ni(n,r),xr();let l=(H=(S=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:S.narrowHostMaxWidth)!=null?H:520,p=pe.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),Ct.update(On),Sn?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(z=Ct.backdrop)==null||z.classList.add("persona-hidden")):On.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),Jr()};if(ar(r)){pe.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(ce),Ct=Am(r,{onSelect:h=>{var y;return(y=St.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Sn=!0,Un()}}),Ct.element.classList.add("persona-hidden"),$n=p,p.appendChild(l),p.appendChild(Ct.element),Ct.backdrop&&pe.appendChild(Ct.backdrop),pe.appendChild(p),Jr=()=>{var y,S,H,z;if(!$n||!Ct)return;if(!(((H=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:H.resizable)===!0)){Tn==null||Tn(),Tn=null,Rr(),Bt&&(Bt.remove(),Bt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Bt){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 B=n.ownerDocument,se=(z=B.defaultView)!=null?z:window,ae=Z=>{var gt,st;if(!Ct||Z.button!==0||n.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Rr();let be=Z.clientX,Fe=Ct.element.getBoundingClientRect().width,Ce=(st=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:st.layout,nt=Be=>{let We=$n.getBoundingClientRect().width,ze=n.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Em($n,se),bt=ze?0:O.getBoundingClientRect().width||6,P=Fe-(Be.clientX-be),Ne=km(P,We,Ke,bt,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);Ct.element.style.width=`${Ne}px`,Ct.element.style.maxWidth="none",Yr()},$e=()=>{B.removeEventListener("pointermove",nt),B.removeEventListener("pointerup",$e),B.removeEventListener("pointercancel",$e),er=null;try{O.releasePointerCapture(Z.pointerId)}catch{}};er=$e,B.addEventListener("pointermove",nt),B.addEventListener("pointerup",$e),B.addEventListener("pointercancel",$e);try{O.setPointerCapture(Z.pointerId)}catch{}};O.addEventListener("pointerdown",ae),Bt=O,$n.insertBefore(O,Ct.element),Tn=()=>{O.removeEventListener("pointerdown",ae)}}if(Bt){let O=On.artifacts.length>0&&!Sn;Bt.classList.toggle("persona-hidden",!O),Yr()}},xr=()=>{var se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We,ze,Ke;if(!M||!Ct||((ae=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?ae:!1)||gn(r)&&gr(r).reveal==="emerge")return;let y=(Z=n.ownerDocument.defaultView)!=null?Z:window,S=(Fe=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Fe:!0,H=(nt=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?nt:640;if(S&&y.innerWidth<=H||!Mm(r,M))return;let z=(st=(gt=($e=r.launcher)==null?void 0:$e.width)!=null?gt:r.launcherWidth)!=null?st:qr,O=(Ke=(ze=(We=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:We.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Sn?(pe.style.width=O,pe.style.maxWidth=O):(pe.style.width=z,pe.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Un()}),Fn.observe(pe))}else pe.appendChild(ce),N()&&Xe&&(J.peekBanner&&Xe.appendChild(J.peekBanner),Xe.appendChild(He));n.appendChild(Ee),Xe&&n.appendChild(Xe);let ye=()=>{var Ne,De,ge,Ft,Dt,zt,wt,Ut,Kn,Jt,Qe,kt,nn,or,Gn,xo,wo,Go,Qo,jt,Co,ro,oo,_r,Ao,pr,Ye,an;if(N()){pe.style.width="100%",pe.style.maxWidth="100%";let _t=(De=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?De:{},Ot=Ee.dataset.state==="expanded",ft=(ge=_t.expandedSize)!=null?ge:"anchored";if(!(Ot&&ft!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let At=(Dt=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Dt.panel,bn=Ra(r),Mn=(kn,So)=>{var Ss;return kn==null||kn===""?So:(Ss=is(bn,kn))!=null?Ss:kn},kr="1px solid var(--persona-border)",dn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",En="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=Mn(At==null?void 0:At.border,kr),ce.style.borderRadius=Mn(At==null?void 0:At.borderRadius,En),ce.style.boxShadow=Mn(At==null?void 0:At.shadow,dn),ce.style.overflow="hidden";return}let l=gn(r),p=(wt=(zt=r.launcher)==null?void 0:zt.sidebarMode)!=null?wt:!1,h=l||p||((Kn=(Ut=r.launcher)==null?void 0:Ut.fullHeight)!=null?Kn:!1),y=((Jt=r.launcher)==null?void 0:Jt.enabled)===!1,S=(kt=(Qe=r.theme)==null?void 0:Qe.components)==null?void 0:kt.panel,H=Ra(r),z=(_t,Ot)=>{var ft;return _t==null||_t===""?Ot:(ft=is(H,_t))!=null?ft:_t},O=(nn=n.ownerDocument.defaultView)!=null?nn:window,B=(Gn=(or=r.launcher)==null?void 0:or.mobileFullscreen)!=null?Gn:!0,se=(wo=(xo=r.launcher)==null?void 0:xo.mobileBreakpoint)!=null?wo:640,ae=O.innerWidth<=se,Z=B&&ae&&M,be=(Qo=(Go=r.launcher)==null?void 0:Go.position)!=null?Qo:"bottom-left",Fe=be==="bottom-left"||be==="top-left",Ce=(Co=(jt=r.launcher)==null?void 0:jt.zIndex)!=null?Co:wn,nt=p||Z?"none":"1px solid var(--persona-border)",$e=Z?"none":p?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&($e="none",nt="none");let gt=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=z(S==null?void 0:S.border,nt),Be=z(S==null?void 0:S.shadow,$e),We=z(S==null?void 0:S.borderRadius,gt),ze=we.scrollTop;n.style.cssText="",Ee.style.cssText="",pe.style.cssText="",ce.style.cssText="",we.style.cssText="",He.style.cssText="";let Ke=()=>{var Ot;if(ze<=0)return;((Ot=we.ownerDocument.defaultView)!=null?Ot:window).requestAnimationFrame(()=>{if(we.scrollTop===ze)return;let ft=we.scrollHeight-we.clientHeight;ft<=0||(we.scrollTop=Math.min(ze,ft))})};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=`
34
+ `,W.addEventListener("click",()=>{f=A,M.forEach((N,D)=>{let k=D<A;N.classList.toggle("selected",k),N.setAttribute("aria-checked",D===A-1?"true":"false")})}),M.push(W),I.appendChild(W)}g.appendChild(I);let E=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),A.appendChild(E),g.appendChild(A)}let F=document.createElement("div");F.className="persona-feedback-actions";let L=document.createElement("button");L.type="button",L.className="persona-feedback-btn persona-feedback-btn-skip",L.textContent=i,L.addEventListener("click",()=>{t==null||t(),m.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){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=(E==null?void 0:E.value.trim())||void 0;await e(f,A),m.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),F.appendChild(L),F.appendChild(R),g.appendChild(F),m.appendChild(g),m}function Um(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:m="Very likely"}=n,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=o,v.appendChild(I),u.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 E=document.createElement("div");E.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let L=document.createElement("span");L.className="persona-feedback-label-high",L.textContent=m,E.appendChild(F),E.appendChild(L);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let j=0;j<=10;j++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${j} out of 10`),V.textContent=String(j),V.dataset.rating=String(j),j<=6?V.classList.add("persona-feedback-detractor"):j<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{g=j,A.forEach((ne,Re)=>{ne.classList.toggle("selected",Re===j),ne.setAttribute("aria-checked",Re===j?"true":"false")})}),A.push(V),R.appendChild(V)}M.appendChild(E),M.appendChild(R),u.appendChild(M);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),u.appendChild(j)}let N=document.createElement("div");N.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{t==null||t(),f.remove()});let 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(g===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await e(g,j),f.remove()}catch(j){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),N.appendChild(D),N.appendChild(k),u.appendChild(N),f.appendChild(u),f}var ms="persona-chat-history",yy=30*1e3,by={"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 vy(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=by[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 ri(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 xy(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 wy(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var al=n=>!n||typeof n!="object"?{}:{...n},qm=n=>n.map(e=>({...e,streaming:!1})),zm=(n,e,t)=>{let r=n!=null&&n.markdown?ga(n.markdown):null,o=fa(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var m,f,g;let a=(m=s.text)!=null?m:"",i=(f=s.message.rawContent)!=null?f:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&t&&t())}let d=Eo()!==null,c;if(n!=null&&n.postprocessMessage){let u=n.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});c=o?o(u):u}else if(r){let u=s.streaming?Vp(a):a,v=r(u);c=o&&d?o(v):v}else c=so(a);return c}};function jm(n){var i,d,c,m;let e=b("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(m=n==null?void 0:n.iconStrokeWidth)!=null?m:.5,a=Ae(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let f=b("span","persona-drop-overlay-label");f.textContent=n.label,e.appendChild(f)}return e}var Vm=(n,e,t)=>{var _l,$l,Ul,ql,zl,jl,Vl,Kl,Gl,Ql,Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=Ou(e),o=tl.getForInstance(r.plugins);r.components&&Do.registerAll(r.components);let s=Hm(),i=r.persistState===!1?null:(_l=r.storageAdapter)!=null?_l:Dm(),d={},c=null,m=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(m=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(d=al(h.metadata)),($l=h.messages)!=null&&$l.length&&(r={...r,initialMessages:h.messages}),(Ul=h.artifacts)!=null&&Ul.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(ql=h.selectedArtifactId)!=null?ql:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(zl=l.messages)!=null&&zl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>d,u=l=>{var h;d=(h=l({...d}))!=null?h:{},Zr()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ta.message,ta.messageAndClick],I=ol({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});I.syncFromMetadata();let M=(Vl=(jl=r.launcher)==null?void 0:jl.enabled)!=null?Vl:!0,E=(Gl=(Kl=r.launcher)==null?void 0:Kl.autoExpand)!=null?Gl:!1,F=(Ql=r.autoFocusInput)!=null?Ql:!1,L=E,R=M,A=(Jl=(Xl=r.layout)==null?void 0:Xl.header)==null?void 0:Jl.layout,W=!1,N=()=>Qs(r),D=()=>M||N(),k=N()?!1:M?E:!0,j=!1,V=null,ne=()=>{j=!0,V&&clearTimeout(V),V=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},Re=zm(r,I,ne),Ue=(Zl=(Yl=r.features)==null?void 0:Yl.showReasoning)!=null?Zl:!0,xe=(tc=(ec=r.features)==null?void 0:ec.showToolCalls)!=null?tc:!0,Ie=(rc=(nc=r.features)==null?void 0:nc.showEventStreamToggle)!=null?rc:!1,_e=(sc=(oc=r.features)==null?void 0:oc.scrollToBottom)!=null?sc:{},Se=(ic=(ac=r.features)==null?void 0:ac.scrollBehavior)!=null?ic:{},re=`${(cc=typeof r.persistState=="object"?(lc=r.persistState)==null?void 0:lc.keyPrefix:void 0)!=null?cc:"persona-"}event-stream`,X=Ie?new Zs(re):null,ie=(uc=(pc=(dc=r.features)==null?void 0:dc.eventStream)==null?void 0:pc.maxEvents)!=null?uc:2e3,he=Ie?new Ys(ie,X):null,oe=Ie?new ea:null,K=null,te=!1,qe=null,Y=0;X==null||X.open().then(()=>he==null?void 0:he.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let le={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)}},Pe=(mc=r.statusIndicator)!=null?mc:{},it=l=>{var p,h,y,S;return l==="idle"?(p=Pe.idleText)!=null?p:xn.idle:l==="connecting"?(h=Pe.connectingText)!=null?h:xn.connecting:l==="connected"?(y=Pe.connectedText)!=null?y:xn.connected:l==="error"?(S=Pe.errorText)!=null?S:xn.error:xn[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 rt=pm({config:r,showClose:D()}),{wrapper:Ee,panel:pe,pillRoot:Xe}=rt.shell,J=rt.panelElements,{container:ce,body:we,messagesWrapper:je,suggestions:Pt,textarea:Te,sendButton:me,sendButtonWrapper:fn,composerForm:It,statusText:rn,introTitle:hr,introSubtitle:hn,closeButton:Ve,iconHolder:T,headerTitle:ue,headerSubtitle:Le,header:Me,footer:He,actionsRow:Ze,leftActions:Ge,rightActions:ut}=J,Wt=J.setSendButtonMode,q=J.micButton,ot=J.micButtonWrapper,G=J.attachmentButton,de=J.attachmentButtonWrapper,ke=J.attachmentInput,vt=J.attachmentPreviewsContainer;ce.classList.add("persona-relative"),we.classList.add("persona-relative");let Yt=12,Zt=()=>{var l;return(l=_e.label)!=null?l:""},pn=()=>{var l;return(l=_e.iconName)!=null?l:"arrow-down"},Ht=()=>_e.enabled!==!1,et=()=>{var l;return(l=Se.mode)!=null?l:"follow"},Rt=()=>{var l;return(l=Se.anchorTopOffset)!=null?l:16},ct=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");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let Kt=b("span","persona-flex persona-items-center"),Jn=b("span",""),An=b("span","");An.setAttribute("data-persona-scroll-to-bottom-count",""),An.style.display="none",ct.append(Kt,Jn,An),ce.appendChild(ct);let en=b("div","persona-stream-anchor-spacer");en.setAttribute("aria-hidden","true"),en.setAttribute("data-persona-anchor-spacer",""),en.style.flexShrink="0",en.style.pointerEvents="none",en.style.height="0px",we.appendChild(en);let In=()=>{let p=He.style.display==="none"?0:He.offsetHeight;ct.style.bottom=`${p+Yt}px`};In();let yr=()=>{let l=!!Zt();ct.setAttribute("aria-label",Zt()||"Jump to latest"),ct.title=Zt(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Kt.innerHTML="";let p=Ae(pn(),"14px","currentColor",2);p?(Kt.appendChild(p),Kt.style.display=""):Kt.style.display="none",Jn.textContent=Zt(),Jn.style.display=l?"":"none"};yr();let xt=null,Nn=null,br=o.find(l=>l.renderHeader);if(br!=null&&br.renderHeader){let l=br.renderHeader({config:r,defaultRenderer:()=>{let p=Ho({config:r,showClose:D()});return Xs(ce,p,r),p.header},onClose:()=>$t(!1,"user")});if(l){let p=ce.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Me=l,rt.header.element=l)}}let Pr=()=>{var p,h,y,S;if(!he)return;if(te=!0,!K&&he&&(K=Sm({buffer:he,getFullHistory:()=>he.getAllFromStore(),onClose:()=>ir(),config:r,plugins:o,getThroughput:()=>{var H;return(H=oe==null?void 0:oe.getMetric())!=null?H:{status:"idle"}}})),K&&(we.style.display="none",(p=He.parentNode)==null||p.insertBefore(K.element,He),K.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Pn.actionIconColor}`;let H=(S=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:S.toggleButtonActive;H&&H.split(/\s+/).forEach(z=>z&&yt.classList.add(z))}let l=()=>{if(!te)return;let H=Date.now();H-Y>=200&&(K==null||K.update(),Y=H),qe=requestAnimationFrame(l)};Y=0,qe=requestAnimationFrame(l),Je(),s.emit("eventStream:opened",{timestamp:Date.now()})},ir=()=>{var l,p,h;if(te){if(te=!1,K&&K.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let y=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(S=>S&&yt.classList.remove(S))}qe!==null&&(cancelAnimationFrame(qe),qe=null),Je(),s.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(Ie){let l=(fc=(gc=r.features)==null?void 0:gc.eventStream)==null?void 0:fc.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=b("button",p),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=Ae("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let y=J.clearChatButtonWrapper,S=J.closeButtonWrapper,H=y||S;H&&H.parentNode===Me?Me.insertBefore(yt,H):Me.appendChild(yt),yt.addEventListener("click",()=>{te?ir():Pr()})}let uo=l=>{var S,H,z,O,B;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=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 se=l.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(h,se):l.insertBefore(h,l.firstChild)}if(!((H=l.querySelector("[data-persona-composer-attachment-input]"))!=null?H:l.querySelector('input[type="file"]'))){let se=b("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((z=p.allowedTypes)!=null?z:Ur).join(","),se.multiple=((O=p.maxFiles)!=null?O:4)>1,se.style.display="none",se.setAttribute("aria-label",(B=p.buttonTooltipText)!=null?B:"Attach files"),l.appendChild(se)}},vr=o.find(l=>l.renderComposer);if(vr!=null&&vr.renderComposer){let l=r.composer,p=vr.renderComposer({config:r,defaultRenderer:()=>Ja({config:r}).footer,onSubmit:h=>{var z;if(!_||_.isStreaming())return;let y=h.trim(),S=(z=xt==null?void 0:xt.hasAttachments())!=null?z:!1;if(!y&&!S)return;yl();let H;S&&(H=[],H.push(...xt.getContentParts()),y&&H.push(Pi(y))),_.sendMessage(y,{contentParts:H}),S&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ke==null||ke.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:((hc=r.voiceRecognition)==null?void 0:hc.enabled)===!0?()=>{Nn==null||Nn()}:void 0});p&&(rt.replaceComposer(p),He=rt.composer.footer)}let mo=l=>{let p=(...ae)=>{for(let Z of ae){let be=l.querySelector(Z);if(be)return be}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),H=l.querySelector("[data-persona-composer-mic]"),z=l.querySelector("[data-persona-composer-status]");h&&(It=h),y&&(Te=y),S&&(me=S),H&&(q=H,ot=H.parentElement),z&&(rn=z);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Pt=O);let B=p("[data-persona-composer-attachment-button]",".persona-attachment-button");B&&(G=B,de=B.parentElement),ke=p("[data-persona-composer-attachment-input]",'input[type="file"]'),vt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(Ze=se)};uo(He),mo(He);let Wn=(wc=(yc=r.layout)==null?void 0:yc.contentMaxWidth)!=null?wc:N()?(xc=(vc=(bc=r.launcher)==null?void 0:bc.composerBar)==null?void 0:vc.contentMaxWidth)!=null?xc:"720px":void 0;if(Wn&&(je.style.maxWidth=Wn,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%"),Wn&&It&&!N()&&(It.style.maxWidth=Wn,It.style.marginLeft="auto",It.style.marginRight="auto"),Wn&&Pt&&!N()&&(Pt.style.maxWidth=Wn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Wn&&vt&&!N()&&(vt.style.maxWidth=Wn,vt.style.marginLeft="auto",vt.style.marginRight="auto"),(Cc=r.attachments)!=null&&Cc.enabled&&ke&&vt){xt=$s.fromConfig(r.attachments),xt.setPreviewsContainer(vt),ke.addEventListener("change",h=>{let y=h.target;xt==null||xt.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=jm(l);ce.appendChild(p)}(()=>{var y,S;let l=(S=(y=r.layout)==null?void 0:y.slots)!=null?S:{},p=H=>{switch(H){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return je;case"footer-top":return Pt;case"composer":return It;case"footer-bottom":return rn;default:return null}},h=(H,z)=>{var O;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")Me.insertBefore(z,Me.firstChild);else if(H==="header-right")Me.appendChild(z);else{let B=Me.querySelector(".persona-flex-col");B?(O=B.parentNode)==null||O.insertBefore(z,B.nextSibling):Me.appendChild(z)}break;case"body-top":{let B=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(z):we.insertBefore(z,we.firstChild);break}case"body-bottom":we.appendChild(z);break;case"footer-top":Pt.replaceWith(z);break;case"footer-bottom":rn.replaceWith(z);break;default:break}};for(let[H,z]of Object.entries(l))if(z)try{let O=z({config:r,defaultContent:()=>p(H)});O&&h(H,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,O)}})();let jr=l=>{var z,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 H=h.getAttribute("data-bubble-type");if(H==="reasoning")ds.has(S)?ds.delete(S):ds.add(S),gm(S,y);else if(H==="tool")ps.has(S)?ps.delete(S):ps.add(S),fm(S,y,r);else if(H==="approval"){let B=r.approval!==!1?r.approval:void 0,se=((z=B==null?void 0:B.detailsDisplay)!=null?z:"collapsed")==="expanded",ae=(O=Ya.get(S))!=null?O:se;Ya.set(S,!ae),vm(S,y,r)}Sr.delete(S)};je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),jr(l))}),je.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),jr(l))}),je.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let h=je.getRootNode(),y=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let S=y.toString(),H=Vu(S);!H||H===S||(p.setData("text/plain",H),l.preventDefault())});let Ir=new Map,Vr=null,Kr="idle",go={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},fo=(l,p)=>{let{icon:h,label:y}=go[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=Ae(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Gr=()=>{je.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var H;let h=p.closest("[data-actions-for]"),y=(H=h==null?void 0:h.getAttribute("data-actions-for"))!=null?H:null;fo(p,y&&y===Vr?Kr:"idle")})};je.addEventListener("click",l=>{var z;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 H=h.getAttribute("data-action");if(H==="copy"){let B=_.getMessages().find(se=>se.id===S);if(B&&le.onCopy){let se=B.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let ae=Ae("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Ae("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),le.onCopy(B)}}else if(H==="read-aloud")_.toggleReadAloud(S);else if(H==="upvote"||H==="downvote"){let B=((z=Ir.get(S))!=null?z:null)===H,se=H==="upvote"?"thumbs-up":"thumbs-down";if(B){Ir.delete(S),h.classList.remove("persona-message-action-active");let ae=Ae(se,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=H==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${ae}"]`);if(Z){Z.classList.remove("persona-message-action-active");let $e=Ae(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Z.innerHTML="",Z.appendChild($e))}Ir.set(S,H),h.classList.add("persona-message-action-active");let be=Ae(se,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=_.getMessages().find(nt=>nt.id===S);Ce&&le.onFeedback&&le.onFeedback({type:H,messageId:Ce.id,message:Ce})}}}),je.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let H=h.getAttribute("data-approval-action");if(!H)return;let z=H==="approve"?"approved":"denied",B=_.getMessages().find(ae=>ae.id===S);if(!(B!=null&&B.approval))return;let se=y.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,z):_.resolveApproval(B.approval,z)});let Ct=null,Fn=null,On={artifacts:[],selectedId:null},Sn=!1,St={current:null};je.addEventListener("click",l=>{var Z,be,Fe,Ce,nt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Fe=(be=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Fe.call(be,{type:"download",artifactId:y}))===!0)return;let H=_.getArtifactById(y),z=H==null?void 0:H.markdown,O=(H==null?void 0:H.title)||"artifact";if(!z){let $e=h.closest("[data-open-artifact]"),gt=$e==null?void 0:$e.closest("[data-message-id]"),st=gt==null?void 0:gt.getAttribute("data-message-id");if(st){let We=_.getMessages().find(ze=>ze.id===st);if(We!=null&&We.rawContent)try{let ze=JSON.parse(We.rawContent);z=(Ce=ze==null?void 0:ze.props)==null?void 0:Ce.markdown,O=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||O}catch{}}}if(!z)return;let B=new Blob([z],{type:"text/markdown"}),se=URL.createObjectURL(B),ae=document.createElement("a");ae.href=se,ae.download=`${O}.md`,ae.click(),URL.revokeObjectURL(se)}),je.addEventListener("click",l=>{var H,z,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((O=(z=(H=r.features)==null?void 0:H.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:O.call(z,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),Sn=!1,_.selectArtifact(y),Un())}),je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Yn=J.composerOverlay,Zn=(l,p,h)=>{var O,B,se,ae;let y=p.trim();if(!y||!St.current)return;let S=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",H=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:y,answers:h.structured,values:(B=h.values)!=null?B:h.source==="multi"?y.split(", "):[y],isFreeText:H,source:h.source},bubbles:!0,composed:!0})),ts(Yn,S);let z=St.current.getMessages().find(Z=>{var be;return((be=Z.toolCall)==null?void 0:be.id)===S});(se=z==null?void 0:z.agentMetadata)!=null&&se.awaitingLocalTool?St.current.resolveAskUserQuestion(z,(ae=h.structured)!=null?ae:y):St.current.sendMessage(y)},_n=l=>{var S;let p=St.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",y=p.getMessages().find(H=>{var z;return((z=H.toolCall)==null?void 0:z.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:ba(l,y),currentIndex:sr(l)})},Qr=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Wr=l=>{var S,H,z;if(((H=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:H.groupedAutoAdvance)===!1)return;let p=sr(l),h=es(l);if(p>=h-1)return;let y=(z=St.current)==null?void 0:z.getMessages().find(O=>{var B;return((B=O.toolCall)==null?void 0:B.id)===l.getAttribute("data-tool-call-id")});y&&(xa(l,y,r,p+1),_n(l))};Yn.addEventListener("click",l=>{var H,z,O,B,se,ae,Z,be,Fe,Ce,nt,$e,gt,st;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 Be=(H=y.getAttribute("data-tool-call-id"))!=null?H:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ts(Yn,Be);let We=(z=St.current)==null?void 0:z.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Be});(O=We==null?void 0:We.agentMetadata)!=null&&O.awaitingLocalTool&&((B=St.current)==null||B.markAskUserQuestionResolved(We),(se=St.current)==null||se.resolveAskUserQuestion(We,"(dismissed)"));return}if(S==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let We=y.getAttribute("data-multi-select")==="true",ze=io(y);if(ze&&We){let Ke=Po(y)[sr(y)],bt=new Set(Array.isArray(Ke)?Ke:[]);bt.has(Be)?bt.delete(Be):bt.add(Be),lo(y,Array.from(bt)),_n(y);return}if(ze){lo(y,Be),_n(y),Wr(y);return}if(We){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let bt=y.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=Si(y).length===0);return}Zn(y,Be,{source:"pick",values:[Be]});return}if(S==="submit-multi"){let Be=Si(y);if(Be.length===0)return;Zn(y,Be.join(", "),{source:"multi",values:Be});return}if(S==="open-free-text"){let Be=y.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let We=Be.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus()}return}if(S==="focus-free-text"){let Be=y.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(S==="submit-free-text"){let Be=y.querySelector('[data-ask-free-text-input="true"]'),We=(ae=Be==null?void 0:Be.value)!=null?ae:"";if(!We.trim())return;if(io(y)){lo(y,We.trim()),_n(y),Wr(y);return}Zn(y,We,{source:"free-text"});return}if(S==="next"||S==="back"){if(!St.current)return;let Be=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",We=St.current.getMessages().find(Ne=>{var De;return((De=Ne.toolCall)==null?void 0:De.id)===Be});if(!We)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ke=(Fe=(be=ze==null?void 0:ze.value)==null?void 0:be.trim())!=null?Fe:"";if(Ke){let Ne=Po(y)[sr(y)];(typeof Ne!="string"||Ne!==Ke)&&lo(y,Ke)}let bt=S==="next"?1:-1,P=sr(y)+bt;xa(y,We,r,P),_n(y);return}if(S==="submit-all"){if(!St.current)return;let Be=(Ce=y.getAttribute("data-tool-call-id"))!=null?Ce:"",We=St.current.getMessages().find(Ne=>{var De;return((De=Ne.toolCall)==null?void 0:De.id)===Be});if(!We)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ke=($e=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?$e:"";Ke&&lo(y,Ke);let bt=ba(y,We);St.current.persistAskUserQuestionProgress(We,{answers:bt,currentIndex:sr(y)});let P=Qr(bt);Zn(y,P||"(submitted)",{source:"submit-all",structured:bt});return}if(S==="skip"){if(!St.current)return;let Be=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",We=St.current.getMessages().find(De=>{var ge;return((ge=De.toolCall)==null?void 0:ge.id)===Be});if(!We)return;let ze=io(y),Ke=sr(y),bt=es(y),P=Ke>=bt-1;if(!ze){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ts(Yn,Be),(st=We.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(We),St.current.resolveAskUserQuestion(We,"(dismissed)"));return}lo(y,"");let Ne=y.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),P){let De=ba(y,We),ge=Qr(De);Zn(y,ge||"(skipped)",{source:"submit-all",structured:De});return}xa(y,We,r,Ke+1),_n(y);return}}),Yn.addEventListener("keydown",l=>{var H;if(l.key!=="Enter")return;let h=l.target;if(!((H=h.matches)!=null&&H.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let S=h.value;if(S.trim()){if(io(y)){lo(y,S.trim()),_n(y),Wr(y);return}Zn(y,S,{source:"free-text"})}});let Xr=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=Yn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),H=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];H&&(l.preventDefault(),H.click())};document.addEventListener("keydown",Xr);let $n=null,Bt=null,Tn=null,er=null,Jr=()=>{};function Rr(){er==null||er(),er=null}let Yr=()=>{var z;if(!$n||!Bt)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((z=n.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let y=$n.firstElementChild;if(!y||y===Bt)return;let S=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${S}px`,Bt.style.zIndex="5";let H=y.offsetWidth-S/2;Bt.style.left=`${Math.max(0,H)}px`},xr=()=>{},Un=()=>{var h,y,S,H,z;if(!Ct||!ar(r))return;ti(n,r),ni(n,r),xr();let l=(H=(S=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:S.narrowHostMaxWidth)!=null?H:520,p=pe.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),Ct.update(On),Sn?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(z=Ct.backdrop)==null||z.classList.add("persona-hidden")):On.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),Jr()};if(ar(r)){pe.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(ce),Ct=Em(r,{onSelect:h=>{var y;return(y=St.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Sn=!0,Un()}}),Ct.element.classList.add("persona-hidden"),$n=p,p.appendChild(l),p.appendChild(Ct.element),Ct.backdrop&&pe.appendChild(Ct.backdrop),pe.appendChild(p),Jr=()=>{var y,S,H,z;if(!$n||!Ct)return;if(!(((H=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:H.resizable)===!0)){Tn==null||Tn(),Tn=null,Rr(),Bt&&(Bt.remove(),Bt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Bt){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 B=n.ownerDocument,se=(z=B.defaultView)!=null?z:window,ae=Z=>{var gt,st;if(!Ct||Z.button!==0||n.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Rr();let be=Z.clientX,Fe=Ct.element.getBoundingClientRect().width,Ce=(st=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:st.layout,nt=Be=>{let We=$n.getBoundingClientRect().width,ze=n.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Im($n,se),bt=ze?0:O.getBoundingClientRect().width||6,P=Fe-(Be.clientX-be),Ne=Wm(P,We,Ke,bt,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);Ct.element.style.width=`${Ne}px`,Ct.element.style.maxWidth="none",Yr()},$e=()=>{B.removeEventListener("pointermove",nt),B.removeEventListener("pointerup",$e),B.removeEventListener("pointercancel",$e),er=null;try{O.releasePointerCapture(Z.pointerId)}catch{}};er=$e,B.addEventListener("pointermove",nt),B.addEventListener("pointerup",$e),B.addEventListener("pointercancel",$e);try{O.setPointerCapture(Z.pointerId)}catch{}};O.addEventListener("pointerdown",ae),Bt=O,$n.insertBefore(O,Ct.element),Tn=()=>{O.removeEventListener("pointerdown",ae)}}if(Bt){let O=On.artifacts.length>0&&!Sn;Bt.classList.toggle("persona-hidden",!O),Yr()}},xr=()=>{var se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We,ze,Ke;if(!M||!Ct||((ae=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?ae:!1)||gn(r)&&gr(r).reveal==="emerge")return;let y=(Z=n.ownerDocument.defaultView)!=null?Z:window,S=(Fe=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Fe:!0,H=(nt=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?nt:640;if(S&&y.innerWidth<=H||!Pm(r,M))return;let z=(st=(gt=($e=r.launcher)==null?void 0:$e.width)!=null?gt:r.launcherWidth)!=null?st:qr,O=(Ke=(ze=(We=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:We.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Sn?(pe.style.width=O,pe.style.maxWidth=O):(pe.style.width=z,pe.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Un()}),Fn.observe(pe))}else pe.appendChild(ce),N()&&Xe&&(J.peekBanner&&Xe.appendChild(J.peekBanner),Xe.appendChild(He));n.appendChild(Ee),Xe&&n.appendChild(Xe);let ye=()=>{var Ne,De,ge,Ft,Dt,zt,wt,Ut,Kn,Jt,Qe,kt,nn,or,Gn,xo,wo,Go,Qo,jt,Co,ro,oo,_r,Ao,pr,Ye,an;if(N()){pe.style.width="100%",pe.style.maxWidth="100%";let _t=(De=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?De:{},Ot=Ee.dataset.state==="expanded",ft=(ge=_t.expandedSize)!=null?ge:"anchored";if(!(Ot&&ft!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let At=(Dt=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Dt.panel,bn=Ra(r),Mn=(kn,So)=>{var Ss;return kn==null||kn===""?So:(Ss=is(bn,kn))!=null?Ss:kn},kr="1px solid var(--persona-border)",dn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",En="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=Mn(At==null?void 0:At.border,kr),ce.style.borderRadius=Mn(At==null?void 0:At.borderRadius,En),ce.style.boxShadow=Mn(At==null?void 0:At.shadow,dn),ce.style.overflow="hidden";return}let l=gn(r),p=(wt=(zt=r.launcher)==null?void 0:zt.sidebarMode)!=null?wt:!1,h=l||p||((Kn=(Ut=r.launcher)==null?void 0:Ut.fullHeight)!=null?Kn:!1),y=((Jt=r.launcher)==null?void 0:Jt.enabled)===!1,S=(kt=(Qe=r.theme)==null?void 0:Qe.components)==null?void 0:kt.panel,H=Ra(r),z=(_t,Ot)=>{var ft;return _t==null||_t===""?Ot:(ft=is(H,_t))!=null?ft:_t},O=(nn=n.ownerDocument.defaultView)!=null?nn:window,B=(Gn=(or=r.launcher)==null?void 0:or.mobileFullscreen)!=null?Gn:!0,se=(wo=(xo=r.launcher)==null?void 0:xo.mobileBreakpoint)!=null?wo:640,ae=O.innerWidth<=se,Z=B&&ae&&M,be=(Qo=(Go=r.launcher)==null?void 0:Go.position)!=null?Qo:"bottom-left",Fe=be==="bottom-left"||be==="top-left",Ce=(Co=(jt=r.launcher)==null?void 0:jt.zIndex)!=null?Co:wn,nt=p||Z?"none":"1px solid var(--persona-border)",$e=Z?"none":p?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&($e="none",nt="none");let gt=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=z(S==null?void 0:S.border,nt),Be=z(S==null?void 0:S.shadow,$e),We=z(S==null?void 0:S.borderRadius,gt),ze=we.scrollTop;n.style.cssText="",Ee.style.cssText="",pe.style.cssText="",ce.style.cssText="",we.style.cssText="",He.style.cssText="";let Ke=()=>{var Ot;if(ze<=0)return;((Ot=we.ownerDocument.defaultView)!=null?Ot:window).requestAnimationFrame(()=>{if(we.scrollTop===ze)return;let ft=we.scrollHeight-we.clientHeight;ft<=0||(we.scrollTop=Math.min(ze,ft))})};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=`
33
35
  position: fixed !important;
34
36
  inset: 0 !important;
35
37
  width: 100% !important;
@@ -106,7 +108,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
106
108
  flex-shrink: 0 !important;
107
109
  border-top: none !important;
108
110
  padding: 8px 16px 12px 16px !important;
109
- `}if(!y&&!l){let _t="max-height: -moz-available !important; max-height: stretch !important;",Ot=p?"":"padding-top: 1.25em !important;",ft=p?"":`z-index: ${(an=(Ye=r.launcher)==null?void 0:Ye.zIndex)!=null?an:wn} !important;`;Ee.style.cssText+=_t+Ot+ft}Ke()};ye(),ls(n,r),ti(n,r),ni(n,r);let dt=[];dt.push(()=>{document.removeEventListener("keydown",Xr)});let Qt=null,on=null;dt.push(()=>{Qt==null||Qt(),Qt=null,on==null||on(),on=null}),Fn&&dt.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),dt.push(()=>{Tn==null||Tn(),Tn=null,Rr(),Bt&&(Bt.remove(),Bt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Ie&&dt.push(()=>{qe!==null&&(cancelAnimationFrame(qe),qe=null),K==null||K.destroy(),K=null,he==null||he.destroy(),he=null,X=null});let wr=null,fs=()=>{wr&&(wr(),wr=null),r.colorScheme==="auto"&&(wr=_u(()=>{ls(n,r)}))};fs(),dt.push(()=>{wr&&(wr(),wr=null)});let Hr=(Ac=r.features)==null?void 0:Ac.streamAnimation;if(Hr!=null&&Hr.type&&Hr.type!=="none"){let l=zs(Hr.type,Hr.plugins);l&&(Fi(l,n),dt.push(()=>em(n)))}let ho=hm(Pt),Cr=null,_,Fo=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?au(p):null;h?ho.render(h,_,Te,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(H=>H.role==="user")?ho.render([],_,Te,p):ho.render(r.suggestionChips,_,Te,p,r.suggestionChipsConfig)},Ar=!1,Sr=ju(),Br=new Map,Tr=new Map,lr=new Map,Oo=0,ra=Eo()!==null,qn=Da(),zn=0,cr=null,dr=!1,yo=!1,Dr=0,yn=null,Mr=null,_o=!1,bo=!1,$o=null,oa=4,Uo=24,sa=80,qo=new Map,ht={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},hs=(Tc=(Sc=r.voiceRecognition)==null?void 0:Sc.autoResume)!=null?Tc:!1,tr=l=>{s.emit("voice:state",{active:ht.active,source:l,timestamp:Date.now()})},Rn=()=>{u(l=>({...l,voiceState:{active:ht.active,timestamp:Date.now(),manuallyDeactivated:ht.manuallyDeactivated}}))},aa=()=>{var y,S;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=al(d.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);ht.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<dy&&setTimeout(()=>{var H,z;ht.active||(ht.manuallyDeactivated=!1,((z=(H=r.voiceRecognition)==null?void 0:H.provider)==null?void 0:z.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("restore"),_.isVoiceActive()&&Vo()}):ca("restore"))},1e3)},ia=()=>_?Om(_.getMessages()).filter(l=>!l.__skipPersist):[];function Zr(l){if(!(i!=null&&i.save))return;let h={messages:l?Om(l):_?ia():[],metadata:d,artifacts:On.artifacts,selectedArtifactId:On.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 tt=null,w=()=>Ee.querySelector("#persona-scroll-container")||we,U=()=>{tt!==null&&(cancelAnimationFrame(tt),tt=null),dr=!1},$=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),yo=!1,U()},Q=()=>{Dr>0?(An.textContent=String(Dr),An.style.display="",ct.setAttribute("aria-label",`${Zt()||"Jump to latest"} (${Dr} new)`)):(An.textContent="",An.style.display="none",ct.setAttribute("aria-label",Zt()||"Jump to latest"))},fe=()=>{Dr!==0&&(Dr=0,Q())},Oe=()=>et()==="follow"?!qn.isFollowing():!Ro(we,Uo),Je=()=>{if(!Ht()||te){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==ce&&ce.appendChild(ct),In();let p=zr(we)>0&&Oe();p||fe(),ct.style.display=p?"":"none"},Et=()=>{qn.pause()&&($(),Je())},Nr=()=>{qn.resume(),fe(),Je()},Hn=(l=!1)=>{et()==="follow"&&qn.isFollowing()&&(!l&&!Ar||(cr!==null&&(cancelAnimationFrame(cr),cr=null),yo=!0,cr=requestAnimationFrame(()=>{cr=null,yo=!1,qn.isFollowing()&&un(w(),l?220:140)})))},jn=(l,p,h,y=()=>!0)=>{let S=l.scrollTop,H=p(),z=H-S;U();let O=performance.now();dr=!0;let B=ae=>1-Math.pow(1-ae,3),se=ae=>{if(!y()){U();return}let Z=p();Z!==H&&(H=Z,z=H-S);let be=ae-O,Fe=Math.min(be/h,1),Ce=B(Fe),nt=S+z*Ce;l.scrollTop=nt,zn=l.scrollTop,Fe<1?tt=requestAnimationFrame(se):(l.scrollTop=H,zn=l.scrollTop,tt=null,dr=!1)};tt=requestAnimationFrame(se)},un=(l,p=500)=>{let h=zr(l)-l.scrollTop;if(Math.abs(h)<1){zn=l.scrollTop;return}if(Math.abs(h)>=sa){U(),dr=!0,l.scrollTop=zr(l),zn=l.scrollTop,dr=!1;return}jn(l,()=>zr(l),p,()=>qn.isFollowing())},eo=()=>{let l=w();dr=!0,l.scrollTop=zr(l),zn=l.scrollTop,dr=!1,Je()},Fr=l=>{en.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},mn=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),U(),yn=null,en.style.height="0px"},Bn=l=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var se;Mr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,S=h;for(;S&&S!==we;)y+=S.offsetTop,S=S.offsetParent;let H=(se=yn==null?void 0:yn.spacerHeight)!=null?se:0,z=we.scrollHeight-H,{targetScrollTop:O,spacerHeight:B}=Xu({anchorOffsetTop:y,topOffset:Rt(),viewportHeight:we.clientHeight,contentHeight:z});yn={initialSpacerHeight:B,contentHeightAtAnchor:z,spacerHeight:B},Fr(B),jn(we,()=>O,220)})},Vn=()=>{if(et()==="follow"){if(!qn.isFollowing()||Ro(we,1))return;Hn(!Ar);return}if(yn&&yn.initialSpacerHeight>0){let l=we.scrollHeight-yn.spacerHeight,p=Ju({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});p!==yn.spacerHeight&&Fr(p)}Je()},eg=l=>{let p=et();p==="follow"?(Nr(),Hn(!0)):p==="anchor-top"&&Bn(l)},tg=l=>{let p=new Map;l.forEach(h=>{let y=qo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!bo&&et()!=="anchor-top"&&Oe()&&(Dr+=1,Q(),Je())),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}))}),qo.clear(),p.forEach((h,y)=>{qo.set(y,h)})},ng=(l,p,h)=>{var st,Be,We,ze,Ke,bt;let y=document.createElement("div"),H=(()=>{var Ne;let P=o.find(De=>De.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),z=(P,Ne)=>Ne==null?!1:typeof Ne=="string"?(P.textContent=Ne,!0):(P.appendChild(Ne),!0),O=new Set,B=new Set,se=o.some(P=>P.renderAskUserQuestion),ae=[],Z=[],be=r.enableComponentStreaming!==!1,Fe=o.some(P=>P.renderApproval)&&r.approval!==!1,Ce=[];if(p.forEach(P=>{var Qe,kt,nn,or,Gn,xo,wo,Go,Qo,jt,Co,ro,oo,_r,Ao,pr;O.add(P.id);let Ne=se&&Lo(P),De=Fe&&P.variant==="approval"&&!!P.approval,ge=!Ne&&P.role==="assistant"&&!P.variant&&be&&Bm(P);if(!De&&lr.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),lr.delete(P.id)}if(!ge&&Tr.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),Tr.delete(P.id)}let Ft=Lo(P)?`:${(Qe=P.agentMetadata)!=null&&Qe.askUserQuestionAnswered?"a":"u"}:${(kt=P.agentMetadata)!=null&&kt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=zu(P,Oo)+Ft,zt=Ne||De||ge?null:Vu(Sr,P.id,Dt);if(zt){y.appendChild(zt.cloneNode(!0)),Lo(P)&&((nn=P.toolCall)!=null&&nn.id)&&((or=P.agentMetadata)==null?void 0:or.awaitingLocalTool)===!0&&!((Gn=P.agentMetadata)!=null&&Gn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}let wt=null,Ut=o.find(Ye=>!!(P.variant==="reasoning"&&Ye.renderReasoning||P.variant==="tool"&&Ye.renderToolCall||!P.variant&&Ye.renderMessage)),Kn=(xo=r.layout)==null?void 0:xo.messages;if(Lo(P)&&((wo=P.agentMetadata)==null?void 0:wo.askUserQuestionAnswered)===!0){Br.delete(P.id);let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime");return}if(Mi(P)&&((Qo=(Go=r.features)==null?void 0:Go.suggestReplies)==null?void 0:Qo.enabled)!==!1)return;if(Lo(P)&&((Co=(jt=r.features)==null?void 0:jt.askUserQuestion)==null?void 0:Co.enabled)!==!1){let Ye=o.find(an=>typeof an.renderAskUserQuestion=="function");if(Ye&&St.current){let an=Br.get(P.id),_t=an!==Dt,Ot=null;if(_t){let{payload:At,complete:bn}=Zo(P),Mn=P.id,kr=()=>{var dn;return(dn=St.current)==null?void 0:dn.getMessages().find(En=>En.id===Mn)};Ot=Ye.renderAskUserQuestion({message:P,payload:At,complete:bn,resolve:dn=>{var kn;let En=kr();En&&((kn=St.current)==null||kn.resolveAskUserQuestion(En,dn))},dismiss:()=>{var En,kn,So;let dn=kr();(En=dn==null?void 0:dn.agentMetadata)!=null&&En.awaitingLocalTool&&((kn=St.current)==null||kn.markAskUserQuestionResolved(dn),(So=St.current)==null||So.resolveAskUserQuestion(dn,"(dismissed)"))},config:r})}let ft=an!=null;if(_t&&Ot===null&&!ft){((ro=P.agentMetadata)==null?void 0:ro.awaitingLocalTool)===!0&&!((oo=P.agentMetadata)!=null&&oo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${P.id}`,Vt.setAttribute("data-wrapper-id",P.id),Vt.setAttribute("data-ask-plugin-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),y.appendChild(Vt),ae.push({messageId:P.id,fingerprint:Dt,bubble:Ot});return}else{((_r=P.agentMetadata)==null?void 0:_r.awaitingLocalTool)===!0&&!((Ao=P.agentMetadata)!=null&&Ao.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}}else if(De){let Ye=o.find(ft=>typeof ft.renderApproval=="function"),_t=lr.get(P.id)!==Dt,Ot=null;if(_t&&(Ye!=null&&Ye.renderApproval)){let ft=P.id,Vt=(At,bn)=>{var kr,dn,En;let Mn=(kr=St.current)==null?void 0:kr.getMessages().find(kn=>kn.id===ft);Mn!=null&&Mn.approval&&(Mn.approval.toolType==="webmcp"?(dn=St.current)==null||dn.resolveWebMcpApproval(Mn.id,At):(En=St.current)==null||En.resolveApproval(Mn.approval,At,bn))};Ot=Ye.renderApproval({message:P,defaultRenderer:()=>Za(P,r),config:r,approve:At=>Vt("approved",At),deny:At=>Vt("denied",At)})}if(_t&&Ot===null){let ft=l.querySelector(`#wrapper-${P.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),lr.delete(P.id),wt=Za(P,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${P.id}`,ft.setAttribute("data-wrapper-id",P.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),Ce.push({messageId:P.id,fingerprint:Dt,bubble:Ot});return}}else if(Ut)if(P.variant==="reasoning"&&P.reasoning&&Ut.renderReasoning){if(!Ue)return;wt=Ut.renderReasoning({message:P,defaultRenderer:()=>Ki(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&Ut.renderToolCall){if(!xe)return;wt=Ut.renderToolCall({message:P,defaultRenderer:()=>Qi(P,r),config:r})}else Ut.renderMessage&&(wt=Ut.renderMessage({message:P,defaultRenderer:()=>{let Ye=Vi(P,h,Kn,r.messageActions,le,{loadingIndicatorRenderer:H,widgetConfig:r});return P.role!=="user"&&Zi(Ye,P,r,_),Ye},config:r}));if(!wt&&ge){let Ye=Dm(P);if(Ye){let an=Tr.get(P.id),_t=an!==Dt,Ot=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(_t){let Vt=Rm(Ye,{config:r,message:P,transform:h});if(Vt)if(Ot){let At=document.createElement("div");if(At.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let bn=document.createElement("div");bn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",bn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(bn)}At.appendChild(Vt),ft=At}else{let At=document.createElement("div");if(At.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),At.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let bn=document.createElement("div");bn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",bn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(bn)}At.appendChild(Vt),ft=At}}if(ft||an!=null){let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${P.id}`,Vt.setAttribute("data-wrapper-id",P.id),Vt.setAttribute("data-component-directive-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),Ot||Vt.classList.add("persona-w-full"),y.appendChild(Vt),Z.push({messageId:P.id,fingerprint:Dt,bubble:ft});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ue)return;wt=Ki(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!xe)return;wt=Qi(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=Za(P,r)}else{let Ye=(pr=r.layout)==null?void 0:pr.messages;Ye!=null&&Ye.renderUserMessage&&P.role==="user"?wt=Ye.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):Ye!=null&&Ye.renderAssistantMessage&&P.role==="assistant"?wt=Ye.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=Vi(P,h,Ye,r.messageActions,le,{loadingIndicatorRenderer:H,widgetConfig:r}),P.role!=="user"&&wt&&Zi(wt,P,r,_)}let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id=`wrapper-${P.id}`,Jt.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Jt.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Jt.classList.add("persona-w-full"),Jt.appendChild(wt),Ku(Sr,P.id,Dt,Jt),y.appendChild(Jt)}),J.composerOverlay&&J.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let De=Ne.getAttribute("data-persona-ask-sheet-for");De&&!B.has(De)&&ts(J.composerOverlay,De)}),(Be=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&Be.grouped){let P=[],Ne=[];p.forEach(De=>{if(De.variant==="tool"&&De.toolCall&&xe){Ne.push(De);return}Ne.length>1&&P.push(Ne),Ne=[]}),Ne.length>1&&P.push(Ne),P.forEach((De,ge)=>{var Qe,kt;let Ft=De.map(nn=>Array.from(y.children).find(or=>or instanceof HTMLElement&&or.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Ft.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${ge}-${De[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${ge}-${De[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.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 Ut=`Called ${De.length} tools`,Kn=(kt=(Qe=r.toolCall)==null?void 0:Qe.renderGroupedSummary)==null?void 0:kt.call(Qe,{messages:De,toolCalls:De.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:Ut,config:r});z(wt,Kn)||(wt.textContent=Ut);let Jt=document.createElement("div");Jt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(wt,Jt),Dt.appendChild(zt),Ft[0].before(Dt),Ft.forEach((nn,or)=>{let Gn=document.createElement("div");Gn.className="persona-tool-group-item persona-relative",Gn.setAttribute("data-persona-tool-group-item","true"),or<Ft.length-1&&Gn.setAttribute("data-persona-tool-group-connector","true"),Gn.appendChild(nn),Jt.appendChild(Gn)})})}Gu(Sr,O);let nt=p.some(P=>P.role==="assistant"&&P.streaming),$e=p[p.length-1],gt=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ar&&p.some(P=>P.role==="user")&&!nt&&!gt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:Js},Ne=o.find(ge=>ge.renderLoadingIndicator),De=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(De=Ne.renderLoadingIndicator(P)),De===null&&((We=r.loadingIndicator)!=null&&We.render)&&(De=r.loadingIndicator.render(P)),De===null&&(De=Js()),De){let ge=document.createElement("div"),Ft=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ge.className=Ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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 Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(ge),y.appendChild(Dt)}}if(!Ar&&p.length>0){let P=p[p.length-1],Ne={config:r,lastMessage:P,messageCount:p.length},De=o.find(Ft=>Ft.renderIdleIndicator),ge=null;if(De!=null&&De.renderIdleIndicator&&(ge=De.renderIdleIndicator(Ne)),ge===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(ge=r.loadingIndicator.renderIdle(Ne)),ge){let Ft=document.createElement("div"),Dt=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Ft.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(ge);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Ft),y.appendChild(zt)}}if(Ha(l,y),ae.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of ae){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),Br.set(P,Ne))}if(Br.size>0)for(let P of Br.keys())O.has(P)||Br.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of Z){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),Tr.set(P,Ne))}if(Tr.size>0)for(let P of Tr.keys())O.has(P)||Tr.delete(P);if(Ce.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of Ce){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),lr.set(P,Ne))}if(lr.size>0)for(let P of lr.keys())O.has(P)||lr.delete(P)},ys=(l,p,h)=>{ng(l,p,h),Gr()},bs=null,rg=()=>{var h;if(bs)return;let l=y=>{let S=y.composedPath();S.includes(Ee)||Xe&&S.includes(Xe)||$t(!1,"user")};bs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},ml=()=>{var p;if(!bs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",bs,!0),bs=null};dt.push(()=>ml());let vs=null,og=()=>{var h;if(vs)return;let l=y=>{y.key==="Escape"&&(y.isComposing||$t(!1,"user"))};vs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},gl=()=>{var p;if(!vs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",vs,!0),vs=null};dt.push(()=>gl());let xs=!1,fl=new Set,sg=()=>{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)},zo=()=>{var gt,st,Be,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=(gt=_==null?void 0:_.getMessages())!=null?gt:[],y;for(let ze=h.length-1;ze>=0;ze--){let Ke=h[ze];if(Ke.role==="assistant"&&Ke.content){y=Ke;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let S=y.content,H=!!y.streaming,z=sg(),O=Oa(z),B=O.type!=="none"?zs(O.type,z==null?void 0:z.plugins):null,se=((st=B==null?void 0:B.isAnimating)==null?void 0:st.call(B,y))===!0,ae=B!==null&&(H||se);ae&&B&&!fl.has(B.name)&&(Fi(B,n),fl.add(B.name));let Z=ae&&(B!=null&&B.containerClass)?B.containerClass:null,be=(Be=p.dataset.personaPeekStreamClass)!=null?Be:null;be&&be!==Z&&(p.classList.remove(be),delete p.dataset.personaPeekStreamClass),Z&&be!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),ae?(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 Fe=ae?_a(S,O.buffer,B,y,H):S;if(ae&&O.placeholder==="skeleton"&&H&&(!Fe||!Fe.trim())){let ze=document.createElement("div"),Ke=Vs();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),Ha(p,ze)}else{let ze=Math.max(0,Fe.length-100),Ke=Fe.length>100?Fe.slice(-100):Fe,bt=so(Ke);if(!ae||!B){let P=Fe.length>100?`\u2026${Ke}`:Ke;p.textContent!==P&&(p.textContent=P)}else{let P=bt;(B.wrap==="char"||B.wrap==="word")&&(P=js(bt,B.wrap,`peek-${y.id}`,{skipTags:B.skipTags,startIndex:ze}));let Ne=document.createElement("div");if(Ne.innerHTML=P,B.useCaret&&Ke.length>0){let De=$a(),ge=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=ge[ge.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(De,Ft.nextSibling):Ne.appendChild(De)}Ha(p,Ne),(We=B.onAfterRender)==null||We.call(B,{container:p,bubble:l,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let $e=Ar||xs;l.classList.toggle("persona-pill-peek--visible",$e)};if(N()){let l=J.peekBanner;if(l){let y=S=>{S.preventDefault(),S.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",y),dt.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{xs||(xs=!0,zo())},h=()=>{xs&&(xs=!1,zo())};pe.addEventListener("pointerenter",p),pe.addEventListener("pointerleave",h),dt.push(()=>{pe.removeEventListener("pointerenter",p),pe.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),dt.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let ag=l=>{var be,Fe,Ce,nt,$e,gt,st,Be;let p=(Fe=(be=r.launcher)==null?void 0:be.composerBar)!=null?Fe:{},h=(Ce=p.expandedSize)!=null?Ce:"anchored",y=(nt=p.bottomOffset)!=null?nt:"16px",S=p.collapsedMaxWidth,H=($e=p.expandedMaxWidth)!=null?$e:"880px",z=(gt=p.expandedTopOffset)!=null?gt:"5vh",O=(st=p.modalMaxWidth)!=null?st:"880px",B=(Be=p.modalMaxHeight)!=null?Be:"min(90vh, 800px)",se="calc(100vw - 32px)",ae="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="",Xe){let We=Xe.style;We.bottom=y,We.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=se,Z.maxHeight=B,Z.height=B;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${ae})`,Z.top=z,Z.width=H,Z.maxWidth=se}},ws=()=>{var B,se,ae,Z,be,Fe,Ce,nt;if(!D())return;if(N()){let gt=(ae=((se=(B=r.launcher)==null?void 0:B.composerBar)!=null?se:{}).expandedSize)!=null?ae:"anchored",st=k?"expanded":"collapsed";Ee.dataset.state=st,Ee.dataset.expandedSize=gt,Xe&&(Xe.dataset.state=st,Xe.dataset.expandedSize=gt),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ag(k),ce.style.display=k?"flex":"none",ye(),k?(rg(),og()):(ml(),gl()),zo();return}let l=gn(r),p=(Z=n.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(be=r.launcher)==null?void 0:be.mobileBreakpoint)!=null?Fe:640,y=(nt=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?nt:!0,S=p.innerWidth<=h,H=y&&S&&M,z=gr(r).reveal;k?(Ee.style.removeProperty("display"),Ee.style.display=l?"flex":"",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),Xt?Xt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(z==="overlay"||z==="push")&&!H?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.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"),pe.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"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),Xt?Xt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},$t=(l,p="user")=>{var H,z;if(!D()||k===l)return;let h=k;k=l,ws();let y=(()=>{var Ce,nt,$e,gt,st,Be,We,ze,Ke,bt;let O=(nt=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?nt:!1,B=($e=n.ownerDocument.defaultView)!=null?$e:window,se=(st=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?st:!0,ae=(We=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?We:640,Z=B.innerWidth<=ae,be=gn(r)&&se&&Z,Fe=N()&&((bt=(Ke=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return O||se&&Z&&M||be||Fe})();if(k&&y){if(!Qt){let O=n.getRootNode(),B=O instanceof ShadowRoot?O.host:n.closest(".persona-host");B&&(Qt=Oi(B,(z=(H=r.launcher)==null?void 0:H.zIndex)!=null?z:wn))}on||(on=_i(n.ownerDocument))}else k||(Qt==null||Qt(),Qt=null,on==null||on(),on=null);k&&(Cs(),et()==="follow"?Hn(!0):eo());let S={open:k,source:p,timestamp:Date.now()};k&&!h?s.emit("widget:opened",S):!k&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:k,launcherEnabled:M,voiceActive:ht.active,streaming:_.isStreaming()})},si=l=>{Wt(l?"stop":"send"),q&&(q.disabled=l),ho.buttons.forEach(p=>{p.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},ai=()=>{ht.active||Te&&Te.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ai(),200)});let hl=()=>{var h,y,S,H,z,O,B,se,ae,Z,be;hr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",hn.textContent=(H=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",Te.placeholder=(O=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?O:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Fe=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((ae=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&ae)&&!(_!=null&&_.isStreaming())&&(me.textContent=(be=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?be:"Send"),Te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{u(p=>({...p,sessionId:l}))}});let vo=null,ig=()=>{vo==null&&(vo=setInterval(()=>{let l=je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(vo),vo=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=wa(p-y))})},100))};_=new Ia(r,{onMessagesChanged(l){var y;ys(je,l,Re),ig(),Fo(l),Hn(!Ar),tg(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&mn(),!_o||bo?(_o=!0,$o=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==$o&&($o=p.id,eg(p.id));let h=ht.lastUserMessageId;p&&p.id!==h&&(ht.lastUserMessageId=p.id,s.emit("user:message",p)),ht.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Zr(l),zo()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};lt(rn,(S=>{var H,z,O,B;return S==="idle"?(H=p.idleText)!=null?H:xn.idle:S==="connecting"?(z=p.connectingText)!=null?z:xn.connecting:S==="connected"?(O=p.connectedText)!=null?O:xn.connected:S==="error"?(B=p.errorText)!=null?B:xn.error:xn[S]})(l),p,l)},onStreamingChanged(l){Ar=l,si(l),_&&ys(je,_.getMessages(),Re),l||Hn(!0),zo()},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":Or(),Vo();break;case"processing":Or(),ug();break;case"speaking":Or(),mg();break;default:l==="idle"&&_.isBargeInActive()?(Or(),Vo(),q==null||q.setAttribute("aria-label","End voice session")):(ht.active=!1,Or(),tr("system"),Rn());break}},onArtifactsState(l){On=l,Un(),Zr()}}),St.current=_;let ii=null;if(_.onReadAloudChange((l,p)=>{var S;Vr=l,Kr=p,Gr();let h=l!=null?l:ii;l&&(ii=l);let y=h&&(S=_.getMessages().find(H=>H.id===h))!=null?S:null;s.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(ii=null)}),_o=!0,((Ec=(Mc=r.voiceRecognition)==null?void 0:Mc.provider)==null?void 0:Ec.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)}),(he||r.onSSEEvent)&&_.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),oe==null||oe.processEvent(l,p),he==null||he.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=al(l.metadata),I.syncFromMetadata()),(p=l.messages)!=null&&p.length){bo=!0;try{_.hydrateMessages(l.messages)}finally{bo=!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 yl=()=>{var p,h,y;!N()||k||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||$t(!0,"auto")},bl=l=>{var S;if(l.preventDefault(),_.isStreaming()){_.cancel(),oe==null||oe.reset(),K==null||K.update();return}let p=Te.value.trim(),h=(S=xt==null?void 0:xt.hasAttachments())!=null?S:!1;if(!p&&!h)return;yl();let y;h&&(y=[],y.push(...xt.getContentParts()),p&&y.push(Pi(p))),Te.value="",Te.style.height="auto",la(),_.sendMessage(p,{contentParts:y}),h&&xt.clearAttachments()},lg=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},li={...Ba},ci=!1,la=()=>{li={...Ba}},cg=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),dg=l=>{if(!Te)return;ci=!0,Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),ci=!1;let p=Te.value.length;Te.setSelectionRange(p,p)},vl=()=>{ci||la()},xl=l=>{if(Te){if(lg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Te.selectionStart===0&&Te.selectionEnd===0,h=qu({direction:l.key==="ArrowUp"?"up":"down",history:cg(),currentValue:Te.value,atStart:p,state:li});if(li=h.state,h.handled){l.preventDefault(),h.value!==void 0&&dg(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}la(),l.preventDefault(),me.click()}}},wl=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ce)&&(_.cancel(),oe==null||oe.reset(),K==null||K.update(),la(),l.preventDefault(),l.stopImmediatePropagation())},Cl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!xt)return;let p=uy(l.clipboardData);p.length!==0&&(l.preventDefault(),await xt.handleFiles(p))},nr=null,Er=!1,jo=null,mt=null,Al=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ca=(l="user")=>{var H,z,O,B,se,ae,Z;if(Er||_.isStreaming())return;let p=Al();if(!p)return;nr=new p;let y=(z=((H=r.voiceRecognition)!=null?H:{}).pauseDuration)!=null?z:2e3;nr.continuous=!0,nr.interimResults=!0,nr.lang="en-US";let S=Te.value;nr.onresult=be=>{let Fe="",Ce="";for(let $e=0;$e<be.results.length;$e++){let gt=be.results[$e],st=gt[0].transcript;gt.isFinal?Fe+=st+" ":Ce=st}let nt=S+Fe+Ce;Te.value=nt,jo&&clearTimeout(jo),(Fe||Ce)&&(jo=window.setTimeout(()=>{let $e=Te.value.trim();$e&&nr&&Er&&(to(),Te.value="",Te.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},y))},nr.onerror=be=>{be.error!=="no-speech"&&to()},nr.onend=()=>{if(Er){let be=Te.value.trim();be&&be!==S.trim()&&(Te.value="",Te.style.height="auto",_.sendMessage(be,{viaVoice:!0})),to()}};try{if(nr.start(),Er=!0,ht.active=!0,l!=="system"&&(ht.manuallyDeactivated=!1),tr(l),Rn(),q){let be=(O=r.voiceRecognition)!=null?O:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(B=be.iconName)!=null?B:"mic",iconSize:parseFloat((Z=(ae=be.iconSize)!=null?ae:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Fe=be.recordingBackgroundColor,Ce=be.recordingIconColor,nt=be.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let $e=q.querySelector("svg");$e&&$e.setAttribute("stroke",Ce)}nt&&(q.style.borderColor=nt),q.setAttribute("aria-label","Stop voice recognition")}}catch{to("system")}},to=(l="user")=>{if(Er){if(Er=!1,jo&&(clearTimeout(jo),jo=null),nr){try{nr.stop()}catch{}nr=null}if(ht.active=!1,tr(l),Rn(),q){if(q.classList.remove("persona-voice-recording"),mt){q.style.backgroundColor=mt.backgroundColor,q.style.color=mt.color,q.style.borderColor=mt.borderColor;let p=q.querySelector("svg");p&&p.setAttribute("stroke",mt.color||"currentColor"),mt=null}q.setAttribute("aria-label","Start voice recognition")}}},pg=(l,p)=>{var st,Be,We,ze,Ke,bt,P,Ne,De;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",S=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||y||S))return null;let z=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 B=(We=l==null?void 0:l.iconName)!=null?We:"mic",se=(ze=p==null?void 0:p.size)!=null?ze:"40px",ae=(Ke=l==null?void 0:l.iconSize)!=null?Ke:se,Z=parseFloat(ae)||24,be=(bt=l==null?void 0:l.backgroundColor)!=null?bt:p==null?void 0:p.backgroundColor,Fe=(P=l==null?void 0:l.iconColor)!=null?P:p==null?void 0:p.textColor;O.style.width=ae,O.style.height=ae,O.style.minWidth=ae,O.style.minHeight=ae,O.style.fontSize="18px",O.style.lineHeight="1",Fe?O.style.color=Fe:O.style.color="var(--persona-text, #111827)";let nt=Ae(B,Z,Fe||"currentColor",1.5);nt?O.appendChild(nt):O.textContent="\u{1F3A4}",be?O.style.backgroundColor=be:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),z.appendChild(O);let $e=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((De=l==null?void 0:l.showTooltip)!=null?De:!1)&&$e){let ge=b("div","persona-send-button-tooltip");ge.textContent=$e,z.appendChild(ge)}return{micButton:O,micButtonWrapper:z}},di=()=>{var p,h,y,S,H;if(!q||mt)return;let l=(p=r.voiceRecognition)!=null?p:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((H=(S=l.iconSize)!=null?S:(y=r.sendButton)==null?void 0:y.size)!=null?H:"40")||24}},pi=(l,p)=>{var H,z,O,B,se;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(se=mt==null?void 0:mt.iconSize)!=null?se:parseFloat((B=(O=(H=r.voiceRecognition)==null?void 0:H.iconSize)!=null?O:(z=r.sendButton)==null?void 0:z.size)!=null?B:"40")||24,S=Ae(l,y,p,1.5);S&&q.appendChild(S)},da=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Vo=()=>{var S;if(!q)return;di();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(da(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let H=q.querySelector("svg");H&&H.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},ug=()=>{var O,B,se,ae,Z,be,Fe,Ce;if(!q)return;di();let l=(O=r.voiceRecognition)!=null?O:{},p=_.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",y=(ae=(se=l.processingIconColor)!=null?se:mt==null?void 0:mt.color)!=null?ae:"",S=(be=(Z=l.processingBackgroundColor)!=null?Z:mt==null?void 0:mt.backgroundColor)!=null?be:"",H=(Ce=(Fe=l.processingBorderColor)!=null?Fe:mt==null?void 0:mt.borderColor)!=null?Ce:"";da(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=S,q.style.borderColor=H;let z=y||"currentColor";q.style.color=z,pi(h,z),q.setAttribute("aria-label","Processing voice input"),p==="none"&&(q.style.cursor="default")},mg=()=>{var se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We;if(!q)return;di();let l=(se=r.voiceRecognition)!=null?se:{},p=_.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ae=l.speakingIconName)!=null?ae:h,S=(Ce=l.speakingIconColor)!=null?Ce:p==="barge-in"?(be=(Z=l.recordingIconColor)!=null?Z:mt==null?void 0:mt.color)!=null?be:"":(Fe=mt==null?void 0:mt.color)!=null?Fe:"",H=(gt=l.speakingBackgroundColor)!=null?gt:p==="barge-in"?(nt=l.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":($e=mt==null?void 0:mt.backgroundColor)!=null?$e:"",z=(We=l.speakingBorderColor)!=null?We:p==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Be=mt==null?void 0:mt.borderColor)!=null?Be:"";da(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=H,q.style.borderColor=z;let O=S||"currentColor";q.style.color=O,pi(y,O);let B=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",B),p==="none"&&(q.style.cursor="default"),p==="barge-in"&&q.classList.add("persona-voice-recording")},Or=()=>{var l,p,h;q&&(da(),mt&&(q.style.backgroundColor=(l=mt.backgroundColor)!=null?l:"",q.style.color=(p=mt.color)!=null?p:"",q.style.borderColor=(h=mt.borderColor)!=null?h:"",pi(mt.iconName,mt.color||"currentColor"),mt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},pa=()=>{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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Rn(),tr("user"),Or()});return}_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),ht.manuallyDeactivated=!_.isVoiceActive(),Rn(),tr("user"),_.isVoiceActive()?Vo():Or()});return}if(Er){let h=Te.value.trim();ht.manuallyDeactivated=!0,Rn(),to("user"),h&&(Te.value="",Te.style.height="auto",_.sendMessage(h))}else ht.manuallyDeactivated=!1,Rn(),ca("user")};Nn=pa,q&&(q.addEventListener("click",pa),dt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Or()):to("system"),q&&q.removeEventListener("click",pa)}));let gg=s.on("assistant:complete",()=>{hs&&(ht.active||ht.manuallyDeactivated||hs==="assistant"&&!ht.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!ht.active&&!ht.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("auto"),_.isVoiceActive()&&Vo()}):ca("auto"))},600))});dt.push(gg);let fg=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(fg);let Sl=()=>{$t(!k,"user")},Xt=null,sn=null;if(M&&!N()){let{instance:l,element:p}=qi({config:r,plugins:o,onToggle:Sl});Xt=l,l||(sn=p)}Xt?n.appendChild(Xt.element):sn&&n.appendChild(sn),ws(),Fo(),hl(),si(_.isStreaming()),et()==="follow"?Hn(!0):eo(),aa(),F&&(!M||N()?setTimeout(()=>ai(),0):k&&setTimeout(()=>ai(),200));let Cs=()=>{var B,se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We,ze,Ke,bt,P,Ne,De,ge,Ft,Dt;if(N()){In(),ws();return}let l=gn(r),p=(se=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?se:!1,h=l||p||((Z=(ae=r.launcher)==null?void 0:ae.fullHeight)!=null?Z:!1),y=(be=n.ownerDocument.defaultView)!=null?be:window,S=(Ce=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ce:!0,H=($e=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?$e:640,z=y.innerWidth<=H,O=S&&z&&M;try{if(O){ye(),ls(n,r);return}if(W&&(W=!1,ye(),ls(n,r)),!M&&!l){pe.style.height="",pe.style.width="";return}if(!p&&!l){let zt=(st=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?st:r==null?void 0:r.launcherWidth,wt=zt!=null?zt:qr;pe.style.width=wt,pe.style.maxWidth=wt}if(xr(),!h){let zt=y.innerHeight,wt=64,Ut=(We=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?We:0,Kn=Math.max(200,zt-wt),Jt=Math.min(640,Kn),Qe=Math.max(200,Jt-Ut);pe.style.height=`${Qe}px`}}finally{if(In(),ws(),k&&M){let wt=((ze=n.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?bt:640),Ut=(Ne=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Ne:!1,Kn=(ge=(De=r.launcher)==null?void 0:De.mobileFullscreen)!=null?ge:!0,Jt=gn(r)&&Kn&&wt,Qe=Ut||Kn&&wt&&M||Jt;if(Qe&&!on){let kt=n.getRootNode(),nn=kt instanceof ShadowRoot?kt.host:n.closest(".persona-host");nn&&!Qt&&(Qt=Oi(nn,(Dt=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Dt:wn)),on=_i(n.ownerDocument)}else Qe||(Qt==null||Qt(),Qt=null,on==null||on(),on=null)}}};Cs();let Tl=(kc=n.ownerDocument.defaultView)!=null?kc:window;if(Tl.addEventListener("resize",Cs),dt.push(()=>Tl.removeEventListener("resize",Cs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{In()});l.observe(He),dt.push(()=>l.disconnect())}zn=we.scrollTop;let Ml=zr(we),hg=()=>{let l=we.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:we.ownerDocument.getSelection()},ui=()=>Qu(hg(),we),El=()=>{let l=we.scrollTop,p=zr(we),h=p<Ml;if(Ml=p,et()!=="follow"){zn=l,Je();return}let{action:y,nextLastScrollTop:S}=Na({following:qn.isFollowing(),currentScrollTop:l,lastScrollTop:zn,nearBottom:Ro(we,Uo),userScrollThreshold:oa,isAutoScrolling:dr||yo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(zn=S,y==="resume"){ui()||Nr();return}y==="pause"&&Et()};if(we.addEventListener("scroll",El,{passive:!0}),dt.push(()=>we.removeEventListener("scroll",El)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Vn()});l.observe(je),l.observe(we),dt.push(()=>l.disconnect())}let kl=()=>{et()==="follow"&&qn.isFollowing()&&ui()&&Et()},Ll=we.ownerDocument;Ll.addEventListener("selectionchange",kl),dt.push(()=>{Ll.removeEventListener("selectionchange",kl)});let Pl=l=>{if(et()!=="follow")return;let p=Fa({following:qn.isFollowing(),deltaY:l.deltaY,nearBottom:Ro(we,Uo),resumeWhenNearBottom:!0});p==="pause"?Et():p==="resume"&&!ui()&&Nr()};we.addEventListener("wheel",Pl,{passive:!0}),dt.push(()=>we.removeEventListener("wheel",Pl)),ct.addEventListener("click",()=>{mn(),we.scrollTop=we.scrollHeight,zn=we.scrollTop,Nr(),Hn(!0),Je()}),dt.push(()=>ct.remove()),dt.push(()=>{$(),mn()});let Il=()=>{Ve&&(Cr&&(Ve.removeEventListener("click",Cr),Cr=null),D()?(Ve.style.display="",Cr=()=>{$t(!1,"user")},Ve.addEventListener("click",Cr)):Ve.style.display="none")};Il(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{_.clearMessages(),Sr.clear(),Nr(),ts(J.composerOverlay);try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let 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={},I.syncFromMetadata(),he==null||he.clear(),oe==null||oe.reset(),K==null||K.update()})})(),It&&It.addEventListener("submit",bl),Te==null||Te.addEventListener("keydown",xl),Te==null||Te.addEventListener("input",vl),Te==null||Te.addEventListener("paste",Cl);let Wl=(Lc=n.ownerDocument)!=null?Lc:document;Wl.addEventListener("keydown",wl,!0);let Rl="persona-attachment-drop-active",As=0,mi=()=>{As=0,ce.classList.remove(Rl)},Ko=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&xt!==null},Hl=l=>{!ri(l.dataTransfer)||!Ko()||(As++,As===1&&ce.classList.add(Rl))},Bl=l=>{!ri(l.dataTransfer)||!Ko()||(As--,As<=0&&mi())},Dl=l=>{!ri(l.dataTransfer)||!Ko()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Nl=l=>{var h;if(!ri(l.dataTransfer)||!Ko())return;l.preventDefault(),l.stopPropagation(),mi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&xt.handleFiles(p)},no=!0;ce.addEventListener("dragenter",Hl,no),ce.addEventListener("dragleave",Bl,no),n.addEventListener("dragover",Dl,no),n.addEventListener("drop",Nl,no);let ua=n.ownerDocument,Fl=l=>{Ko()&&l.preventDefault()},Ol=l=>{Ko()&&l.preventDefault()};ua.addEventListener("dragover",Fl),ua.addEventListener("drop",Ol),dt.push(()=>{It&&It.removeEventListener("submit",bl),Te==null||Te.removeEventListener("keydown",xl),Te==null||Te.removeEventListener("input",vl),Te==null||Te.removeEventListener("paste",Cl),Wl.removeEventListener("keydown",wl,!0)}),dt.push(()=>{ce.removeEventListener("dragenter",Hl,no),ce.removeEventListener("dragleave",Bl,no),n.removeEventListener("dragover",Dl,no),n.removeEventListener("drop",Nl,no),ua.removeEventListener("dragover",Fl),ua.removeEventListener("drop",Ol),mi()}),dt.push(()=>{_.cancel()}),Xt?dt.push(()=>{Xt==null||Xt.destroy()}):sn&&dt.push(()=>{sn==null||sn.remove()});let tn={update(l){var bn,Mn,kr,dn,En,kn,So,Ss,Dc,Nc,Fc,Oc,_c,$c,Uc,qc,zc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,qd,zd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Mp,Ep,kp,Lp,Pp,Ip,Wp,Rp,Hp;let p=r.toolCall,h=r.messageActions,y=(bn=r.layout)==null?void 0:bn.messages,S=r.colorScheme,H=r.loadingIndicator,z=r.iterationDisplay,O=(Mn=r.features)==null?void 0:Mn.showReasoning,B=(kr=r.features)==null?void 0:kr.showToolCalls,se=(dn=r.features)==null?void 0:dn.toolCallDisplay,ae=(En=r.features)==null?void 0:En.reasoningDisplay;r={...r,...l},ye(),ls(n,r),ti(n,r),ni(n,r),Un(),r.colorScheme!==S&&fs();let Z=tl.getForInstance(r.plugins);o.length=0,o.push(...Z),M=(So=(kn=r.launcher)==null?void 0:kn.enabled)!=null?So:!0,E=(Dc=(Ss=r.launcher)==null?void 0:Ss.autoExpand)!=null?Dc:!1,Ue=(Fc=(Nc=r.features)==null?void 0:Nc.showReasoning)!=null?Fc:!0,xe=(_c=(Oc=r.features)==null?void 0:Oc.showToolCalls)!=null?_c:!0,_e=(Uc=($c=r.features)==null?void 0:$c.scrollToBottom)!=null?Uc:{};let be=et();Se=(zc=(qc=r.features)==null?void 0:qc.scrollBehavior)!=null?zc:{},be!==et()&&(mn(),Nr()),yr(),Je();let Fe=Ie;if(Ie=(Vc=(jc=r.features)==null?void 0:jc.showEventStreamToggle)!=null?Vc:!1,Ie&&!Fe){if(he||(X=new Zs(re),he=new Ys(ie,X),oe=oe!=null?oe:new ea,X.open().then(()=>he==null?void 0:he.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Tt)=>{var qt;(qt=r.onSSEEvent)==null||qt.call(r,ee,Tt),oe==null||oe.processEvent(ee,Tt),he.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&Me){let ee=(Gc=(Kc=r.features)==null?void 0:Kc.eventStream)==null?void 0:Gc.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");yt=b("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let qt=Ae("activity","18px","currentColor",1.5);qt&&yt.appendChild(qt);let at=J.clearChatButtonWrapper,Lt=J.closeButtonWrapper,ln=at||Lt;ln&&ln.parentNode===Me?Me.insertBefore(yt,ln):Me.appendChild(yt),yt.addEventListener("click",()=>{te?ir():Pr()})}}else!Ie&&Fe&&(ir(),yt&&(yt.remove(),yt=null),he==null||he.clear(),X==null||X.destroy(),he=null,X=null,oe==null||oe.reset(),oe=null);if(((Qc=r.launcher)==null?void 0:Qc.enabled)===!1&&Xt&&(Xt.destroy(),Xt=null),((Xc=r.launcher)==null?void 0:Xc.enabled)===!1&&sn&&(sn.remove(),sn=null),((Jc=r.launcher)==null?void 0:Jc.enabled)!==!1&&!Xt&&!sn){let{instance:ee,element:Tt}=qi({config:r,plugins:o,onToggle:Sl});Xt=ee,ee||(sn=Tt),n.appendChild(Tt)}Xt&&Xt.update(r),ue&&((Yc=r.launcher)==null?void 0:Yc.title)!==void 0&&(ue.textContent=r.launcher.title),Le&&((Zc=r.launcher)==null?void 0:Zc.subtitle)!==void 0&&(Le.textContent=r.launcher.subtitle);let Ce=(ed=r.layout)==null?void 0:ed.header;if((Ce==null?void 0:Ce.layout)!==A&&Me){let ee=Ce?za(r,Ce,{showClose:D(),onClose:()=>$t(!1,"user")}):Ho({config:r,showClose:D(),onClose:()=>$t(!1,"user")});rt.replaceHeader(ee),Me=rt.header.element,T=rt.header.iconHolder,ue=rt.header.headerTitle,Le=rt.header.headerSubtitle,Ve=rt.header.closeButton,A=Ce==null?void 0:Ce.layout}else if(Ce&&(T&&(T.style.display=Ce.showIcon===!1?"none":""),ue&&(ue.style.display=Ce.showTitle===!1?"none":""),Le&&(Le.style.display=Ce.showSubtitle===!1?"none":""),Ve&&(Ve.style.display=Ce.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let ee=Ce.showClearChat;if(ee!==void 0){J.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Tt}=J;Tt&&!Tt.classList.contains("persona-absolute")&&(ee?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let $e=((td=r.layout)==null?void 0:td.showHeader)!==!1;Me&&(Me.style.display=$e?"":"none");let gt=((nd=r.layout)==null?void 0:nd.showFooter)!==!1;He&&(He.style.display=gt?"":"none"),In(),Je(),M!==R?M?$t(E,"auto"):(k=!0,ws()):E!==L&&$t(E,"auto"),L=E,R=M,Cs(),Il();let We=JSON.stringify(l.toolCall)!==JSON.stringify(p),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((rd=r.layout)==null?void 0:rd.messages)!==JSON.stringify(y),bt=((od=r.loadingIndicator)==null?void 0:od.render)!==(H==null?void 0:H.render)||((sd=r.loadingIndicator)==null?void 0:sd.renderIdle)!==(H==null?void 0:H.renderIdle)||((ad=r.loadingIndicator)==null?void 0:ad.showBubble)!==(H==null?void 0:H.showBubble),P=r.iterationDisplay!==z,Ne=((ld=(id=r.features)==null?void 0:id.showReasoning)!=null?ld:!0)!==(O!=null?O:!0)||((dd=(cd=r.features)==null?void 0:cd.showToolCalls)!=null?dd:!0)!==(B!=null?B:!0)||JSON.stringify((pd=r.features)==null?void 0:pd.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((ud=r.features)==null?void 0:ud.reasoningDisplay)!==JSON.stringify(ae);(We||ze||Ke||bt||P||Ne)&&_&&(Oo++,ys(je,_.getMessages(),Re));let ge=(md=r.launcher)!=null?md:{},Ft=(gd=ge.headerIconHidden)!=null?gd:!1,Dt=(hd=(fd=r.layout)==null?void 0:fd.header)==null?void 0:hd.showIcon,zt=Ft||Dt===!1,wt=ge.headerIconName,Ut=(yd=ge.headerIconSize)!=null?yd:"48px";if(T){let ee=ce.querySelector(".persona-border-b-persona-divider"),Tt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(zt)T.style.display="none",ee&&Tt&&!ee.contains(Tt)&&ee.insertBefore(Tt,ee.firstChild);else{if(T.style.display="",T.style.height=Ut,T.style.width=Ut,ee&&Tt&&(ee.contains(T)?T.nextSibling!==Tt&&(T.remove(),ee.insertBefore(T,Tt)):ee.insertBefore(T,Tt)),wt){let at=parseFloat(Ut)||24,Lt=Ae(wt,at*.6,"currentColor",1);Lt?T.replaceChildren(Lt):T.textContent=(bd=ge.agentIconText)!=null?bd:"\u{1F4AC}"}else if(ge.iconUrl){let at=T.querySelector("img");if(at)at.src=ge.iconUrl,at.style.height=Ut,at.style.width=Ut;else{let Lt=document.createElement("img");Lt.src=ge.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Ut,Lt.style.width=Ut,T.replaceChildren(Lt)}}else{let at=T.querySelector("svg"),Lt=T.querySelector("img");(at||Lt)&&T.replaceChildren(),T.textContent=(vd=ge.agentIconText)!=null?vd:"\u{1F4AC}"}let qt=T.querySelector("img");qt&&(qt.style.height=Ut,qt.style.width=Ut)}}let Kn=(wd=(xd=r.layout)==null?void 0:xd.header)==null?void 0:wd.showTitle,Jt=(Ad=(Cd=r.layout)==null?void 0:Cd.header)==null?void 0:Ad.showSubtitle;if(ue&&(ue.style.display=Kn===!1?"none":""),Le&&(Le.style.display=Jt===!1?"none":""),Ve){((Td=(Sd=r.layout)==null?void 0:Sd.header)==null?void 0:Td.showCloseButton)===!1?Ve.style.display="none":Ve.style.display="";let Tt=(Md=ge.closeButtonSize)!=null?Md:"32px",qt=(Ed=ge.closeButtonPlacement)!=null?Ed:"inline";Ve.style.height=Tt,Ve.style.width=Tt;let{closeButtonWrapper:at}=J,Lt=qt==="top-right",ln=at==null?void 0:at.classList.contains("persona-absolute");if(at&&Lt!==ln)if(at.remove(),Lt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(at);else{let pt=(Ld=(kd=ge.clearChat)==null?void 0:kd.placement)!=null?Ld:"inline",cn=(Id=(Pd=ge.clearChat)==null?void 0:Pd.enabled)!=null?Id:!0;at.className=cn&&pt==="inline"?"":"persona-ml-auto";let Dn=ce.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(at)}if(Ve.style.color=ge.closeButtonColor||Pn.actionIconColor,ge.closeButtonBackgroundColor?(Ve.style.backgroundColor=ge.closeButtonBackgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let pt=ge.closeButtonBorderWidth||"0px",cn=ge.closeButtonBorderColor||"transparent";Ve.style.border=`${pt} solid ${cn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");ge.closeButtonBorderRadius?(Ve.style.borderRadius=ge.closeButtonBorderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(Ve.style.paddingLeft=ge.closeButtonPaddingX,Ve.style.paddingRight=ge.closeButtonPaddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),ge.closeButtonPaddingY?(Ve.style.paddingTop=ge.closeButtonPaddingY,Ve.style.paddingBottom=ge.closeButtonPaddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let vn=(Wd=ge.closeButtonIconName)!=null?Wd:"x",ur=(Rd=ge.closeButtonIconText)!=null?Rd:"\xD7";Ve.innerHTML="";let Ln=Ae(vn,"28px","currentColor",1);Ln?Ve.appendChild(Ln):Ve.textContent=ur;let Gt=(Hd=ge.closeButtonTooltipText)!=null?Hd:"Close chat",Qn=(Bd=ge.closeButtonShowTooltip)!=null?Bd:!0;if(Ve.setAttribute("aria-label",Gt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Qn&&Gt)){let pt=null,cn=()=>{if(pt||!Ve)return;let To=Ve.ownerDocument,Ts=To.body;if(!Ts)return;pt=Lr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Gt;let Ms=Lr(To,"div");Ms.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ms);let Mo=Ve.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(co),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ts.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};at.addEventListener("mouseenter",cn),at.addEventListener("mouseleave",Dn),Ve.addEventListener("focus",cn),Ve.addEventListener("blur",Dn),at._cleanupTooltip=()=>{Dn(),at&&(at.removeEventListener("mouseenter",cn),at.removeEventListener("mouseleave",Dn)),Ve&&(Ve.removeEventListener("focus",cn),Ve.removeEventListener("blur",Dn))}}}let{clearChatButton:Qe,clearChatButtonWrapper:kt}=J;if(Qe){let ee=(Dd=ge.clearChat)!=null?Dd:{},Tt=(Nd=ee.enabled)!=null?Nd:!0,qt=(Od=(Fd=r.layout)==null?void 0:Fd.header)==null?void 0:Od.showClearChat,at=qt!==void 0?qt:Tt,Lt=(_d=ee.placement)!=null?_d:"inline";if(kt){kt.style.display=at?"":"none";let{closeButtonWrapper:ln}=J;!N()&&ln&&!ln.classList.contains("persona-absolute")&&(at?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let vn=Lt==="top-right",ur=kt.classList.contains("persona-absolute");if(!N()&&vn!==ur&&at){if(kt.remove(),vn)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",ce.style.position="relative",ce.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let Gt=ce.querySelector(".persona-border-b-persona-divider"),Qn=J.closeButtonWrapper;Gt&&Qn&&Qn.parentElement===Gt?Gt.insertBefore(kt,Qn):Gt&&Gt.appendChild(kt)}let Ln=J.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(vn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(at){if(!N()){let pt=($d=ee.size)!=null?$d:"32px";Qe.style.height=pt,Qe.style.width=pt}let ln=(Ud=ee.iconName)!=null?Ud:"refresh-cw",vn=(qd=ee.iconColor)!=null?qd:"";Qe.style.color=vn||Pn.actionIconColor,Qe.innerHTML="";let ur=N()?"14px":"20px",Ln=Ae(ln,ur,"currentColor",2);if(Ln&&Qe.appendChild(Ln),ee.backgroundColor?(Qe.style.backgroundColor=ee.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let pt=ee.borderWidth||"0px",cn=ee.borderColor||"transparent";Qe.style.border=`${pt} solid ${cn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");ee.borderRadius?(Qe.style.borderRadius=ee.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),ee.paddingX?(Qe.style.paddingLeft=ee.paddingX,Qe.style.paddingRight=ee.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),ee.paddingY?(Qe.style.paddingTop=ee.paddingY,Qe.style.paddingBottom=ee.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Gt=(zd=ee.tooltipText)!=null?zd:"Clear chat",Qn=(jd=ee.showTooltip)!=null?jd:!0;if(Qe.setAttribute("aria-label",Gt),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),Qn&&Gt)){let pt=null,cn=()=>{if(pt||!Qe)return;let To=Qe.ownerDocument,Ts=To.body;if(!Ts)return;pt=Lr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Gt;let Ms=Lr(To,"div");Ms.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ms);let Mo=Qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(co),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ts.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};kt.addEventListener("mouseenter",cn),kt.addEventListener("mouseleave",Dn),Qe.addEventListener("focus",cn),Qe.addEventListener("blur",Dn),kt._cleanupTooltip=()=>{Dn(),kt&&(kt.removeEventListener("mouseenter",cn),kt.removeEventListener("mouseleave",Dn)),Qe&&(Qe.removeEventListener("focus",cn),Qe.removeEventListener("blur",Dn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rl],or=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ta.message,ta.messageAndClick];I=ol({parsers:nn,handlers:or,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Re=_m(r,I,ne),_.updateConfig(r),ys(je,_.getMessages(),Re),Fo(),hl(),si(_.isStreaming());let Gn=((Vd=r.voiceRecognition)==null?void 0:Vd.enabled)===!0,xo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),wo=((Gd=(Kd=r.voiceRecognition)==null?void 0:Kd.provider)==null?void 0:Gd.type)==="runtype";if(Gn&&(xo||wo))if(!q||!ot){let ee=pg(r.voiceRecognition,r.sendButton);ee&&(q=ee.micButton,ot=ee.micButtonWrapper,ut.insertBefore(ot,fn),q.addEventListener("click",pa),q.disabled=_.isStreaming())}else{let ee=(Qd=r.voiceRecognition)!=null?Qd:{},Tt=(Xd=r.sendButton)!=null?Xd:{},qt=(Jd=ee.iconName)!=null?Jd:"mic",at=(Yd=Tt.size)!=null?Yd:"40px",Lt=(Zd=ee.iconSize)!=null?Zd:at,ln=parseFloat(Lt)||24;q.style.width=Lt,q.style.height=Lt,q.style.minWidth=Lt,q.style.minHeight=Lt;let vn=(tp=(ep=ee.iconColor)!=null?ep:Tt.textColor)!=null?tp:"currentColor";q.innerHTML="";let ur=Ae(qt,ln,vn,2);ur?q.appendChild(ur):q.textContent="\u{1F3A4}";let Ln=(np=ee.backgroundColor)!=null?np:Tt.backgroundColor;Ln?q.style.backgroundColor=Ln:q.style.backgroundColor="",vn?q.style.color=vn:q.style.color="var(--persona-text, #111827)",ee.borderWidth?(q.style.borderWidth=ee.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),ee.borderColor?q.style.borderColor=ee.borderColor:q.style.borderColor="",ee.paddingX?(q.style.paddingLeft=ee.paddingX,q.style.paddingRight=ee.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),ee.paddingY?(q.style.paddingTop=ee.paddingY,q.style.paddingBottom=ee.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Gt=ot==null?void 0:ot.querySelector(".persona-send-button-tooltip"),Qn=(rp=ee.tooltipText)!=null?rp:"Start voice recognition";if(((op=ee.showTooltip)!=null?op:!1)&&Qn)if(Gt)Gt.textContent=Qn,Gt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Qn,ot==null||ot.insertBefore(cn,q)}else Gt&&(Gt.style.display="none");ot.style.display="",q.disabled=_.isStreaming()}else q&&ot&&(ot.style.display="none",((ap=(sp=r.voiceRecognition)==null?void 0:sp.provider)==null?void 0:ap.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Er&&to());if(((ip=r.attachments)==null?void 0:ip.enabled)===!0)if(!de||!G){let ee=(lp=r.attachments)!=null?lp:{},qt=(dp=((cp=r.sendButton)!=null?cp:{}).size)!=null?dp:"40px";vt||(vt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),vt.style.display="none",It.insertBefore(vt,Te)),ke||(ke=document.createElement("input"),ke.type="file",ke.accept=((pp=ee.allowedTypes)!=null?pp:Ur).join(","),ke.multiple=((up=ee.maxFiles)!=null?up:4)>1,ke.style.display="none",ke.setAttribute("aria-label","Attach files"),It.insertBefore(ke,Te)),de=b("div","persona-send-button-wrapper"),G=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),G.type="button",G.setAttribute("aria-label",(mp=ee.buttonTooltipText)!=null?mp:"Attach file");let at=(gp=ee.buttonIconName)!=null?gp:"paperclip",Lt=qt,ln=parseFloat(Lt)||40,vn=Math.round(ln*.6);G.style.width=Lt,G.style.height=Lt,G.style.minWidth=Lt,G.style.minHeight=Lt,G.style.fontSize="18px",G.style.lineHeight="1",G.style.backgroundColor="transparent",G.style.color="var(--persona-primary, #111827)",G.style.border="none",G.style.borderRadius="6px",G.style.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 ur=Ae(at,vn,"currentColor",1.5);ur?G.appendChild(ur):G.textContent="\u{1F4CE}",G.addEventListener("click",Qn=>{Qn.preventDefault(),ke==null||ke.click()}),de.appendChild(G);let Ln=(fp=ee.buttonTooltipText)!=null?fp:"Attach file",Gt=b("div","persona-send-button-tooltip");Gt.textContent=Ln,de.appendChild(Gt),Ge.append(de),!xt&&ke&&vt&&(xt=$s.fromConfig(ee),xt.setPreviewsContainer(vt),ke.addEventListener("change",async()=>{xt&&(ke!=null&&ke.files)&&(await xt.handleFileSelect(ke.files),ke.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild($m(ee.dropOverlay))}else{de.style.display="";let ee=(hp=r.attachments)!=null?hp:{};ke&&(ke.accept=((yp=ee.allowedTypes)!=null?yp:Ur).join(","),ke.multiple=((bp=ee.maxFiles)!=null?bp:4)>1),xt&&xt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else de&&(de.style.display="none"),xt&&xt.clearAttachments(),(vp=ce.querySelector(".persona-attachment-drop-overlay"))==null||vp.remove();let jt=(xp=r.sendButton)!=null?xp:{},Co=(wp=jt.useIcon)!=null?wp:!1,ro=(Cp=jt.iconText)!=null?Cp:"\u2191",oo=jt.iconName,_r=(Ap=jt.tooltipText)!=null?Ap:"Send message",Ao=(Sp=jt.showTooltip)!=null?Sp:!1,pr=(Tp=jt.size)!=null?Tp:"40px",Ye=jt.backgroundColor,an=jt.textColor;if(Co){if(me.style.width=pr,me.style.height=pr,me.style.minWidth=pr,me.style.minHeight=pr,me.style.fontSize="18px",me.style.lineHeight="1",me.innerHTML="",an?me.style.color=an:me.style.color="var(--persona-button-primary-fg, #ffffff)",oo){let ee=parseFloat(pr)||24,Tt=(an==null?void 0:an.trim())||"currentColor",qt=Ae(oo,ee,Tt,2);qt?me.appendChild(qt):me.textContent=ro}else me.textContent=ro;me.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ye?(me.style.backgroundColor=Ye,me.classList.remove("persona-bg-persona-primary")):(me.style.backgroundColor="",me.classList.add("persona-bg-persona-primary"))}else me.textContent=(Ep=(Mp=r.copy)==null?void 0:Mp.sendButtonLabel)!=null?Ep:"Send",me.style.width="",me.style.height="",me.style.minWidth="",me.style.minHeight="",me.style.fontSize="",me.style.lineHeight="",me.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Ye?(me.style.backgroundColor=Ye,me.classList.remove("persona-bg-persona-accent")):me.classList.add("persona-bg-persona-accent"),an?me.style.color=an:me.classList.add("persona-text-white");jt.borderWidth?(me.style.borderWidth=jt.borderWidth,me.style.borderStyle="solid"):(me.style.borderWidth="",me.style.borderStyle=""),jt.borderColor?me.style.borderColor=jt.borderColor:me.style.borderColor="",jt.paddingX?(me.style.paddingLeft=jt.paddingX,me.style.paddingRight=jt.paddingX):(me.style.paddingLeft="",me.style.paddingRight=""),jt.paddingY?(me.style.paddingTop=jt.paddingY,me.style.paddingBottom=jt.paddingY):(me.style.paddingTop="",me.style.paddingBottom="");let _t=fn==null?void 0:fn.querySelector(".persona-send-button-tooltip");if(Ao&&_r)if(_t)_t.textContent=_r,_t.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=_r,fn==null||fn.insertBefore(ee,me)}else _t&&(_t.style.display="none");let Ot=(Wp=(kp=r.layout)==null?void 0:kp.contentMaxWidth)!=null?Wp:N()?(Ip=(Pp=(Lp=r.launcher)==null?void 0:Lp.composerBar)==null?void 0:Pp.contentMaxWidth)!=null?Ip:"720px":void 0;Ot?(je.style.maxWidth=Ot,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%",It&&(It.style.maxWidth=Ot,It.style.marginLeft="auto",It.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Ot,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(je.style.maxWidth="",je.style.marginLeft="",je.style.marginRight="",je.style.width="",It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let ft=(Rp=r.statusIndicator)!=null?Rp:{},Vt=(Hp=ft.visible)!=null?Hp:!0;if(rn.style.display=Vt?"":"none",_){let ee=_.getStatus();lt(rn,(qt=>{var at,Lt,ln,vn;return qt==="idle"?(at=ft.idleText)!=null?at:xn.idle:qt==="connecting"?(Lt=ft.connectingText)!=null?Lt:xn.connecting:qt==="connected"?(ln=ft.connectedText)!=null?ln:xn.connected:qt==="error"?(vn=ft.errorText)!=null?vn:xn.error:xn[qt]})(ee),ft,ee)}rn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let At=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";rn.classList.add(At)},open(){D()&&$t(!0,"api")},close(){D()&&$t(!1,"api")},toggle(){D()&&$t(!k,"api")},clearChat(){Sn=!1,_.clearMessages(),Sr.clear(),Nr();try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)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={},I.syncFromMetadata(),he==null||he.clear(),oe==null||oe.reset(),K==null||K.update()},setMessage(l){return!Te||_.isStreaming()?!1:(!k&&D()&&$t(!0,"system"),Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Te.value.trim();return p?(!k&&D()&&$t(!0,"system"),Te.value="",Te.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()||(!k&&D()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Rn(),_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("user"),_.isVoiceActive()&&Vo()})),!0):Er?!0:Al()?(!k&&D()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Rn(),ca("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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Rn(),tr("user"),Or()}),!0):!1:Er?(ht.manuallyDeactivated=!0,Rn(),to("user"),!0):!1},injectMessage(l){return!k&&D()&&$t(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&D()&&$t(!0,"system");let p=_.injectAssistantMessage(l);return j&&(j=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(l){return!k&&D()&&$t(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&D()&&$t(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&D()&&$t(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&D()&&$t(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&D()&&$t(!0,"system"),_.injectTestEvent(l)},async connectStream(l,p){return _.connectStream(l,p)},__pushEventStreamEvent(l){he&&(oe==null||oe.processEvent(l.type,l.payload),he.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ie||!he||Pr()},hideEventStream(){te&&ir()},isEventStreamVisible(){return te},showArtifacts(){ar(r)&&(Sn=!1,Un(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){ar(r)&&(Sn=!0,Un())},upsertArtifact(l){return ar(r)?(Sn=!1,_.upsertArtifact(l)):null},selectArtifact(l){ar(r)&&_.selectArtifact(l)},clearArtifacts(){ar(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 M&&!k&&!N()||!Te?!1:(Te.focus(),!0)},async resolveApproval(l,p,h){let S=_.getMessages().find(H=>{var z;return H.variant==="approval"&&((z=H.approval)==null?void 0:z.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){u(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return D()&&k},isVoiceActive(){return ht.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:D()&&k,launcherEnabled:M,voiceActive:ht.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&D()&&$t(!0,"system");let p=je.querySelector(".persona-feedback-container");p&&p.remove();let h=Nm({onSubmit:async(y,S)=>{var H;_.isClientTokenMode()&&await _.submitCSATFeedback(y,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&D()&&$t(!0,"system");let p=je.querySelector(".persona-feedback-container");p&&p.remove();let h=Fm({onSubmit:async(y,S)=>{var H;_.isClientTokenMode()&&await _.submitNPSFeedback(y,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});je.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(){vo!=null&&(clearInterval(vo),vo=null),dt.forEach(l=>l()),Ee.remove(),Xe==null||Xe.remove(),Xt==null||Xt.destroy(),sn==null||sn.remove(),Cr&&Ve.removeEventListener("click",Cr)}};if((((Pc=t==null?void 0:t.debugTools)!=null?Pc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,dt.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 B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",p),dt.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ie){let O=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&tn.showEventStream()},B=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",B),dt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",B)})}let h=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.showArtifacts()},y=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.hideArtifacts()},S=O=>{let B=O.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&tn.upsertArtifact(B.artifact)},H=O=>{let B=O.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&tn.selectArtifact(B.id)},z=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",z),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",z)})}let rr=my(r.persistState);if(rr&&D()){let l=gy(rr.storage),p=`${rr.keyPrefix}widget-open`,h=`${rr.keyPrefix}widget-voice`,y=`${rr.keyPrefix}widget-voice-mode`;if(l){let S=((Ic=rr.persist)==null?void 0:Ic.openState)&&l.getItem(p)==="true",H=((Wc=rr.persist)==null?void 0:Wc.voiceState)&&l.getItem(h)==="true",z=((Rc=rr.persist)==null?void 0:Rc.voiceState)&&l.getItem(y)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var O;if(H||z)tn.startVoiceRecognition();else if((O=rr.persist)!=null&&O.focusInput){let B=n.querySelector("textarea");B&&B.focus()}},100)},0),(Hc=rr.persist)!=null&&Hc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Bc=rr.persist)!=null&&Bc.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")})),rr.clearOnChatClear){let O=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},B=()=>O();window.addEventListener("persona:clear-chat",B),dt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return m&&D()&&setTimeout(()=>{tn.open()},0),zo(),ra||Up().then(()=>{_&&(Oo++,Sr.clear(),ys(je,_.getMessages(),Re))}).catch(()=>{}),tn};var fy=(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},hy=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},yy=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},by=(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.")},qm=(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"},dl=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=""},zm=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",dl(n)},il=n=>{n.style.transition=""},ll=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},cl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},oi=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},vy=(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))},xy=(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)},jm=(n,e,t,r,o,s,a)=>{var v,x,I,M,E,F;let i=gr(s),d=i.reveal==="push";vy(n,e,t,r,d),xy(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,m=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(M=(I=s==null?void 0:s.launcher)==null?void 0:I.mobileBreakpoint)!=null?M:640,g=c!=null?c.innerWidth<=f:!1;if(m&&g&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),ll(e),il(r),zm(r),cl(t),oi(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=(E=s==null?void 0:s.launcher)==null?void 0:E.zIndex)!=null?F:wn),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"),zm(r),hy(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",ll(e),il(r),cl(t),oi(o,r);let L=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=L,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",il(r),dl(r),oi(o,r);let L=fy(i.width,n.clientWidth),R=Math.max(0,n.clientWidth),A=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-L:0:a?0:-L;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+L}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="",ll(e),dl(r),cl(t),oi(o,r);let L=i.reveal==="emerge";L?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",yy(r,i.maxHeight),r.style.overflow=L||W?"hidden":"visible",r.style.transition=A,L&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},wy=(n,e)=>{let t=n.ownerDocument.createElement("div");return qm(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){qm(t,r)},destroy(){t.remove()}}},Cy=(n,e)=>{var F,L,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"),m=t.createElement("div"),f=(L=(F=e==null?void 0:e.launcher)==null?void 0:F.enabled)==null||L?(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",m.dataset.personaDockRole="host",c.appendChild(m),r.insertBefore(a,n),d.appendChild(n);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),gr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{jm(a,i,d,c,m,e,f)}),g.observe(a))},x=!1,I=()=>{jm(a,i,d,c,m,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,by(a,gr(e)))},M=a.ownerDocument.defaultView,E=()=>{I()};return M==null||M.addEventListener("resize",E),gr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),I(),{mode:"docked",host:m,shell:a,syncWidgetState(W){let N=W.launcherEnabled?W.open:!0;f!==N&&(f=N,I())},updateConfig(W){var N,D;e=W,((D=(N=e==null?void 0:e.launcher)==null?void 0:N.enabled)!=null?D:!0)===!1&&(f=!0),I()},destroy(){M==null||M.removeEventListener("resize",E),u(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},Vm=(n,e)=>gn(e)?Cy(n,e):wy(n,e);var na={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Km=.15,Gm=1.5,pl="persona-preview-shell-theme",Ay={load:()=>null,save:()=>{},clear:()=>{}},Sy=["How do I get started?","Pricing & plans","Talk to support"];function ul(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ty(n){return n==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Qm(n){let e=Ty(n);return`* { box-sizing: border-box; }
111
+ `}if(!y&&!l){let _t="max-height: -moz-available !important; max-height: stretch !important;",Ot=p?"":"padding-top: 1.25em !important;",ft=p?"":`z-index: ${(an=(Ye=r.launcher)==null?void 0:Ye.zIndex)!=null?an:wn} !important;`;Ee.style.cssText+=_t+Ot+ft}Ke()};ye(),ls(n,r),ti(n,r),ni(n,r);let dt=[];dt.push(()=>{document.removeEventListener("keydown",Xr)});let Qt=null,on=null;dt.push(()=>{Qt==null||Qt(),Qt=null,on==null||on(),on=null}),Fn&&dt.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),dt.push(()=>{Tn==null||Tn(),Tn=null,Rr(),Bt&&(Bt.remove(),Bt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Ie&&dt.push(()=>{qe!==null&&(cancelAnimationFrame(qe),qe=null),K==null||K.destroy(),K=null,he==null||he.destroy(),he=null,X=null});let wr=null,fs=()=>{wr&&(wr(),wr=null),r.colorScheme==="auto"&&(wr=zu(()=>{ls(n,r)}))};fs(),dt.push(()=>{wr&&(wr(),wr=null)});let Hr=(Ac=r.features)==null?void 0:Ac.streamAnimation;if(Hr!=null&&Hr.type&&Hr.type!=="none"){let l=zs(Hr.type,Hr.plugins);l&&(Fi(l,n),dt.push(()=>om(n)))}let ho=xm(Pt),Cr=null,_,Fo=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?du(p):null;h?ho.render(h,_,Te,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(H=>H.role==="user")?ho.render([],_,Te,p):ho.render(r.suggestionChips,_,Te,p,r.suggestionChipsConfig)},Ar=!1,Sr=Qu(),Br=new Map,Tr=new Map,lr=new Map,Oo=0,ra=Eo()!==null,qn=Da(),zn=0,cr=null,dr=!1,yo=!1,Dr=0,yn=null,Mr=null,_o=!1,bo=!1,$o=null,oa=4,Uo=24,sa=80,qo=new Map,ht={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},hs=(Tc=(Sc=r.voiceRecognition)==null?void 0:Sc.autoResume)!=null?Tc:!1,tr=l=>{s.emit("voice:state",{active:ht.active,source:l,timestamp:Date.now()})},Rn=()=>{u(l=>({...l,voiceState:{active:ht.active,timestamp:Date.now(),manuallyDeactivated:ht.manuallyDeactivated}}))},aa=()=>{var y,S;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=al(d.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);ht.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<yy&&setTimeout(()=>{var H,z;ht.active||(ht.manuallyDeactivated=!1,((z=(H=r.voiceRecognition)==null?void 0:H.provider)==null?void 0:z.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("restore"),_.isVoiceActive()&&Vo()}):ca("restore"))},1e3)},ia=()=>_?qm(_.getMessages()).filter(l=>!l.__skipPersist):[];function Zr(l){if(!(i!=null&&i.save))return;let h={messages:l?qm(l):_?ia():[],metadata:d,artifacts:On.artifacts,selectedArtifactId:On.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 tt=null,w=()=>Ee.querySelector("#persona-scroll-container")||we,U=()=>{tt!==null&&(cancelAnimationFrame(tt),tt=null),dr=!1},$=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),yo=!1,U()},Q=()=>{Dr>0?(An.textContent=String(Dr),An.style.display="",ct.setAttribute("aria-label",`${Zt()||"Jump to latest"} (${Dr} new)`)):(An.textContent="",An.style.display="none",ct.setAttribute("aria-label",Zt()||"Jump to latest"))},fe=()=>{Dr!==0&&(Dr=0,Q())},Oe=()=>et()==="follow"?!qn.isFollowing():!Ro(we,Uo),Je=()=>{if(!Ht()||te){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==ce&&ce.appendChild(ct),In();let p=zr(we)>0&&Oe();p||fe(),ct.style.display=p?"":"none"},Et=()=>{qn.pause()&&($(),Je())},Nr=()=>{qn.resume(),fe(),Je()},Hn=(l=!1)=>{et()==="follow"&&qn.isFollowing()&&(!l&&!Ar||(cr!==null&&(cancelAnimationFrame(cr),cr=null),yo=!0,cr=requestAnimationFrame(()=>{cr=null,yo=!1,qn.isFollowing()&&un(w(),l?220:140)})))},jn=(l,p,h,y=()=>!0)=>{let S=l.scrollTop,H=p(),z=H-S;U();let O=performance.now();dr=!0;let B=ae=>1-Math.pow(1-ae,3),se=ae=>{if(!y()){U();return}let Z=p();Z!==H&&(H=Z,z=H-S);let be=ae-O,Fe=Math.min(be/h,1),Ce=B(Fe),nt=S+z*Ce;l.scrollTop=nt,zn=l.scrollTop,Fe<1?tt=requestAnimationFrame(se):(l.scrollTop=H,zn=l.scrollTop,tt=null,dr=!1)};tt=requestAnimationFrame(se)},un=(l,p=500)=>{let h=zr(l)-l.scrollTop;if(Math.abs(h)<1){zn=l.scrollTop;return}if(Math.abs(h)>=sa){U(),dr=!0,l.scrollTop=zr(l),zn=l.scrollTop,dr=!1;return}jn(l,()=>zr(l),p,()=>qn.isFollowing())},eo=()=>{let l=w();dr=!0,l.scrollTop=zr(l),zn=l.scrollTop,dr=!1,Je()},Fr=l=>{en.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},mn=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),U(),yn=null,en.style.height="0px"},Bn=l=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var se;Mr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,S=h;for(;S&&S!==we;)y+=S.offsetTop,S=S.offsetParent;let H=(se=yn==null?void 0:yn.spacerHeight)!=null?se:0,z=we.scrollHeight-H,{targetScrollTop:O,spacerHeight:B}=em({anchorOffsetTop:y,topOffset:Rt(),viewportHeight:we.clientHeight,contentHeight:z});yn={initialSpacerHeight:B,contentHeightAtAnchor:z,spacerHeight:B},Fr(B),jn(we,()=>O,220)})},Vn=()=>{if(et()==="follow"){if(!qn.isFollowing()||Ro(we,1))return;Hn(!Ar);return}if(yn&&yn.initialSpacerHeight>0){let l=we.scrollHeight-yn.spacerHeight,p=tm({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});p!==yn.spacerHeight&&Fr(p)}Je()},og=l=>{let p=et();p==="follow"?(Nr(),Hn(!0)):p==="anchor-top"&&Bn(l)},sg=l=>{let p=new Map;l.forEach(h=>{let y=qo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!bo&&et()!=="anchor-top"&&Oe()&&(Dr+=1,Q(),Je())),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}))}),qo.clear(),p.forEach((h,y)=>{qo.set(y,h)})},ag=(l,p,h)=>{var st,Be,We,ze,Ke,bt;let y=document.createElement("div"),H=(()=>{var Ne;let P=o.find(De=>De.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),z=(P,Ne)=>Ne==null?!1:typeof Ne=="string"?(P.textContent=Ne,!0):(P.appendChild(Ne),!0),O=new Set,B=new Set,se=o.some(P=>P.renderAskUserQuestion),ae=[],Z=[],be=r.enableComponentStreaming!==!1,Fe=o.some(P=>P.renderApproval)&&r.approval!==!1,Ce=[];if(p.forEach(P=>{var Qe,kt,nn,or,Gn,xo,wo,Go,Qo,jt,Co,ro,oo,_r,Ao,pr;O.add(P.id);let Ne=se&&Lo(P),De=Fe&&P.variant==="approval"&&!!P.approval,ge=!Ne&&P.role==="assistant"&&!P.variant&&be&&Om(P);if(!De&&lr.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),lr.delete(P.id)}if(!ge&&Tr.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),Tr.delete(P.id)}let Ft=Lo(P)?`:${(Qe=P.agentMetadata)!=null&&Qe.askUserQuestionAnswered?"a":"u"}:${(kt=P.agentMetadata)!=null&&kt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=Gu(P,Oo)+Ft,zt=Ne||De||ge?null:Xu(Sr,P.id,Dt);if(zt){y.appendChild(zt.cloneNode(!0)),Lo(P)&&((nn=P.toolCall)!=null&&nn.id)&&((or=P.agentMetadata)==null?void 0:or.awaitingLocalTool)===!0&&!((Gn=P.agentMetadata)!=null&&Gn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}let wt=null,Ut=o.find(Ye=>!!(P.variant==="reasoning"&&Ye.renderReasoning||P.variant==="tool"&&Ye.renderToolCall||!P.variant&&Ye.renderMessage)),Kn=(xo=r.layout)==null?void 0:xo.messages;if(Lo(P)&&((wo=P.agentMetadata)==null?void 0:wo.askUserQuestionAnswered)===!0){Br.delete(P.id);let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime");return}if(Mi(P)&&((Qo=(Go=r.features)==null?void 0:Go.suggestReplies)==null?void 0:Qo.enabled)!==!1)return;if(Lo(P)&&((Co=(jt=r.features)==null?void 0:jt.askUserQuestion)==null?void 0:Co.enabled)!==!1){let Ye=o.find(an=>typeof an.renderAskUserQuestion=="function");if(Ye&&St.current){let an=Br.get(P.id),_t=an!==Dt,Ot=null;if(_t){let{payload:At,complete:bn}=Zo(P),Mn=P.id,kr=()=>{var dn;return(dn=St.current)==null?void 0:dn.getMessages().find(En=>En.id===Mn)};Ot=Ye.renderAskUserQuestion({message:P,payload:At,complete:bn,resolve:dn=>{var kn;let En=kr();En&&((kn=St.current)==null||kn.resolveAskUserQuestion(En,dn))},dismiss:()=>{var En,kn,So;let dn=kr();(En=dn==null?void 0:dn.agentMetadata)!=null&&En.awaitingLocalTool&&((kn=St.current)==null||kn.markAskUserQuestionResolved(dn),(So=St.current)==null||So.resolveAskUserQuestion(dn,"(dismissed)"))},config:r})}let ft=an!=null;if(_t&&Ot===null&&!ft){((ro=P.agentMetadata)==null?void 0:ro.awaitingLocalTool)===!0&&!((oo=P.agentMetadata)!=null&&oo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${P.id}`,Vt.setAttribute("data-wrapper-id",P.id),Vt.setAttribute("data-ask-plugin-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),y.appendChild(Vt),ae.push({messageId:P.id,fingerprint:Dt,bubble:Ot});return}else{((_r=P.agentMetadata)==null?void 0:_r.awaitingLocalTool)===!0&&!((Ao=P.agentMetadata)!=null&&Ao.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}}else if(De){let Ye=o.find(ft=>typeof ft.renderApproval=="function"),_t=lr.get(P.id)!==Dt,Ot=null;if(_t&&(Ye!=null&&Ye.renderApproval)){let ft=P.id,Vt=(At,bn)=>{var kr,dn,En;let Mn=(kr=St.current)==null?void 0:kr.getMessages().find(kn=>kn.id===ft);Mn!=null&&Mn.approval&&(Mn.approval.toolType==="webmcp"?(dn=St.current)==null||dn.resolveWebMcpApproval(Mn.id,At):(En=St.current)==null||En.resolveApproval(Mn.approval,At,bn))};Ot=Ye.renderApproval({message:P,defaultRenderer:()=>Za(P,r),config:r,approve:At=>Vt("approved",At),deny:At=>Vt("denied",At)})}if(_t&&Ot===null){let ft=l.querySelector(`#wrapper-${P.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),lr.delete(P.id),wt=Za(P,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${P.id}`,ft.setAttribute("data-wrapper-id",P.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),Ce.push({messageId:P.id,fingerprint:Dt,bubble:Ot});return}}else if(Ut)if(P.variant==="reasoning"&&P.reasoning&&Ut.renderReasoning){if(!Ue)return;wt=Ut.renderReasoning({message:P,defaultRenderer:()=>Ki(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&Ut.renderToolCall){if(!xe)return;wt=Ut.renderToolCall({message:P,defaultRenderer:()=>Qi(P,r),config:r})}else Ut.renderMessage&&(wt=Ut.renderMessage({message:P,defaultRenderer:()=>{let Ye=Vi(P,h,Kn,r.messageActions,le,{loadingIndicatorRenderer:H,widgetConfig:r});return P.role!=="user"&&Zi(Ye,P,r,_),Ye},config:r}));if(!wt&&ge){let Ye=_m(P);if(Ye){let an=Tr.get(P.id),_t=an!==Dt,Ot=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(_t){let Vt=Nm(Ye,{config:r,message:P,transform:h});if(Vt)if(Ot){let At=document.createElement("div");if(At.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let bn=document.createElement("div");bn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",bn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(bn)}At.appendChild(Vt),ft=At}else{let At=document.createElement("div");if(At.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),At.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let bn=document.createElement("div");bn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",bn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(bn)}At.appendChild(Vt),ft=At}}if(ft||an!=null){let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${P.id}`,Vt.setAttribute("data-wrapper-id",P.id),Vt.setAttribute("data-component-directive-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),Ot||Vt.classList.add("persona-w-full"),y.appendChild(Vt),Z.push({messageId:P.id,fingerprint:Dt,bubble:ft});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ue)return;wt=Ki(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!xe)return;wt=Qi(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=Za(P,r)}else{let Ye=(pr=r.layout)==null?void 0:pr.messages;Ye!=null&&Ye.renderUserMessage&&P.role==="user"?wt=Ye.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):Ye!=null&&Ye.renderAssistantMessage&&P.role==="assistant"?wt=Ye.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=Vi(P,h,Ye,r.messageActions,le,{loadingIndicatorRenderer:H,widgetConfig:r}),P.role!=="user"&&wt&&Zi(wt,P,r,_)}let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id=`wrapper-${P.id}`,Jt.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Jt.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Jt.classList.add("persona-w-full"),Jt.appendChild(wt),Ju(Sr,P.id,Dt,Jt),y.appendChild(Jt)}),J.composerOverlay&&J.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let De=Ne.getAttribute("data-persona-ask-sheet-for");De&&!B.has(De)&&ts(J.composerOverlay,De)}),(Be=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&Be.grouped){let P=[],Ne=[];p.forEach(De=>{if(De.variant==="tool"&&De.toolCall&&xe){Ne.push(De);return}Ne.length>1&&P.push(Ne),Ne=[]}),Ne.length>1&&P.push(Ne),P.forEach((De,ge)=>{var Qe,kt;let Ft=De.map(nn=>Array.from(y.children).find(or=>or instanceof HTMLElement&&or.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Ft.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${ge}-${De[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${ge}-${De[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.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 Ut=`Called ${De.length} tools`,Kn=(kt=(Qe=r.toolCall)==null?void 0:Qe.renderGroupedSummary)==null?void 0:kt.call(Qe,{messages:De,toolCalls:De.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:Ut,config:r});z(wt,Kn)||(wt.textContent=Ut);let Jt=document.createElement("div");Jt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(wt,Jt),Dt.appendChild(zt),Ft[0].before(Dt),Ft.forEach((nn,or)=>{let Gn=document.createElement("div");Gn.className="persona-tool-group-item persona-relative",Gn.setAttribute("data-persona-tool-group-item","true"),or<Ft.length-1&&Gn.setAttribute("data-persona-tool-group-connector","true"),Gn.appendChild(nn),Jt.appendChild(Gn)})})}Yu(Sr,O);let nt=p.some(P=>P.role==="assistant"&&P.streaming),$e=p[p.length-1],gt=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ar&&p.some(P=>P.role==="user")&&!nt&&!gt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:Js},Ne=o.find(ge=>ge.renderLoadingIndicator),De=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(De=Ne.renderLoadingIndicator(P)),De===null&&((We=r.loadingIndicator)!=null&&We.render)&&(De=r.loadingIndicator.render(P)),De===null&&(De=Js()),De){let ge=document.createElement("div"),Ft=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ge.className=Ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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 Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(ge),y.appendChild(Dt)}}if(!Ar&&p.length>0){let P=p[p.length-1],Ne={config:r,lastMessage:P,messageCount:p.length},De=o.find(Ft=>Ft.renderIdleIndicator),ge=null;if(De!=null&&De.renderIdleIndicator&&(ge=De.renderIdleIndicator(Ne)),ge===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(ge=r.loadingIndicator.renderIdle(Ne)),ge){let Ft=document.createElement("div"),Dt=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Ft.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(ge);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Ft),y.appendChild(zt)}}if(Ha(l,y),ae.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of ae){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),Br.set(P,Ne))}if(Br.size>0)for(let P of Br.keys())O.has(P)||Br.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of Z){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),Tr.set(P,Ne))}if(Tr.size>0)for(let P of Tr.keys())O.has(P)||Tr.delete(P);if(Ce.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of Ce){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),lr.set(P,Ne))}if(lr.size>0)for(let P of lr.keys())O.has(P)||lr.delete(P)},ys=(l,p,h)=>{ag(l,p,h),Gr()},bs=null,ig=()=>{var h;if(bs)return;let l=y=>{let S=y.composedPath();S.includes(Ee)||Xe&&S.includes(Xe)||$t(!1,"user")};bs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},ml=()=>{var p;if(!bs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",bs,!0),bs=null};dt.push(()=>ml());let vs=null,lg=()=>{var h;if(vs)return;let l=y=>{y.key==="Escape"&&(y.isComposing||$t(!1,"user"))};vs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},gl=()=>{var p;if(!vs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",vs,!0),vs=null};dt.push(()=>gl());let xs=!1,fl=new Set,cg=()=>{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)},zo=()=>{var gt,st,Be,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=(gt=_==null?void 0:_.getMessages())!=null?gt:[],y;for(let ze=h.length-1;ze>=0;ze--){let Ke=h[ze];if(Ke.role==="assistant"&&Ke.content){y=Ke;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let S=y.content,H=!!y.streaming,z=cg(),O=Oa(z),B=O.type!=="none"?zs(O.type,z==null?void 0:z.plugins):null,se=((st=B==null?void 0:B.isAnimating)==null?void 0:st.call(B,y))===!0,ae=B!==null&&(H||se);ae&&B&&!fl.has(B.name)&&(Fi(B,n),fl.add(B.name));let Z=ae&&(B!=null&&B.containerClass)?B.containerClass:null,be=(Be=p.dataset.personaPeekStreamClass)!=null?Be:null;be&&be!==Z&&(p.classList.remove(be),delete p.dataset.personaPeekStreamClass),Z&&be!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),ae?(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 Fe=ae?_a(S,O.buffer,B,y,H):S;if(ae&&O.placeholder==="skeleton"&&H&&(!Fe||!Fe.trim())){let ze=document.createElement("div"),Ke=Vs();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),Ha(p,ze)}else{let ze=Math.max(0,Fe.length-100),Ke=Fe.length>100?Fe.slice(-100):Fe,bt=so(Ke);if(!ae||!B){let P=Fe.length>100?`\u2026${Ke}`:Ke;p.textContent!==P&&(p.textContent=P)}else{let P=bt;(B.wrap==="char"||B.wrap==="word")&&(P=js(bt,B.wrap,`peek-${y.id}`,{skipTags:B.skipTags,startIndex:ze}));let Ne=document.createElement("div");if(Ne.innerHTML=P,B.useCaret&&Ke.length>0){let De=$a(),ge=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=ge[ge.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(De,Ft.nextSibling):Ne.appendChild(De)}Ha(p,Ne),(We=B.onAfterRender)==null||We.call(B,{container:p,bubble:l,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let $e=Ar||xs;l.classList.toggle("persona-pill-peek--visible",$e)};if(N()){let l=J.peekBanner;if(l){let y=S=>{S.preventDefault(),S.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",y),dt.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{xs||(xs=!0,zo())},h=()=>{xs&&(xs=!1,zo())};pe.addEventListener("pointerenter",p),pe.addEventListener("pointerleave",h),dt.push(()=>{pe.removeEventListener("pointerenter",p),pe.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),dt.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let dg=l=>{var be,Fe,Ce,nt,$e,gt,st,Be;let p=(Fe=(be=r.launcher)==null?void 0:be.composerBar)!=null?Fe:{},h=(Ce=p.expandedSize)!=null?Ce:"anchored",y=(nt=p.bottomOffset)!=null?nt:"16px",S=p.collapsedMaxWidth,H=($e=p.expandedMaxWidth)!=null?$e:"880px",z=(gt=p.expandedTopOffset)!=null?gt:"5vh",O=(st=p.modalMaxWidth)!=null?st:"880px",B=(Be=p.modalMaxHeight)!=null?Be:"min(90vh, 800px)",se="calc(100vw - 32px)",ae="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="",Xe){let We=Xe.style;We.bottom=y,We.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=se,Z.maxHeight=B,Z.height=B;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${ae})`,Z.top=z,Z.width=H,Z.maxWidth=se}},ws=()=>{var B,se,ae,Z,be,Fe,Ce,nt;if(!D())return;if(N()){let gt=(ae=((se=(B=r.launcher)==null?void 0:B.composerBar)!=null?se:{}).expandedSize)!=null?ae:"anchored",st=k?"expanded":"collapsed";Ee.dataset.state=st,Ee.dataset.expandedSize=gt,Xe&&(Xe.dataset.state=st,Xe.dataset.expandedSize=gt),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),dg(k),ce.style.display=k?"flex":"none",ye(),k?(ig(),lg()):(ml(),gl()),zo();return}let l=gn(r),p=(Z=n.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(be=r.launcher)==null?void 0:be.mobileBreakpoint)!=null?Fe:640,y=(nt=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?nt:!0,S=p.innerWidth<=h,H=y&&S&&M,z=gr(r).reveal;k?(Ee.style.removeProperty("display"),Ee.style.display=l?"flex":"",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),Xt?Xt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(z==="overlay"||z==="push")&&!H?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.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"),pe.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"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),Xt?Xt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},$t=(l,p="user")=>{var H,z;if(!D()||k===l)return;let h=k;k=l,ws();let y=(()=>{var Ce,nt,$e,gt,st,Be,We,ze,Ke,bt;let O=(nt=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?nt:!1,B=($e=n.ownerDocument.defaultView)!=null?$e:window,se=(st=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?st:!0,ae=(We=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?We:640,Z=B.innerWidth<=ae,be=gn(r)&&se&&Z,Fe=N()&&((bt=(Ke=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return O||se&&Z&&M||be||Fe})();if(k&&y){if(!Qt){let O=n.getRootNode(),B=O instanceof ShadowRoot?O.host:n.closest(".persona-host");B&&(Qt=Oi(B,(z=(H=r.launcher)==null?void 0:H.zIndex)!=null?z:wn))}on||(on=_i(n.ownerDocument))}else k||(Qt==null||Qt(),Qt=null,on==null||on(),on=null);k&&(Cs(),et()==="follow"?Hn(!0):eo());let S={open:k,source:p,timestamp:Date.now()};k&&!h?s.emit("widget:opened",S):!k&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:k,launcherEnabled:M,voiceActive:ht.active,streaming:_.isStreaming()})},si=l=>{Wt(l?"stop":"send"),q&&(q.disabled=l),ho.buttons.forEach(p=>{p.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},ai=()=>{ht.active||Te&&Te.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ai(),200)});let hl=()=>{var h,y,S,H,z,O,B,se,ae,Z,be;hr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",hn.textContent=(H=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",Te.placeholder=(O=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?O:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Fe=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((ae=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&ae)&&!(_!=null&&_.isStreaming())&&(me.textContent=(be=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?be:"Send"),Te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{u(p=>({...p,sessionId:l}))}});let vo=null,pg=()=>{vo==null&&(vo=setInterval(()=>{let l=je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(vo),vo=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=wa(p-y))})},100))};_=new Ia(r,{onMessagesChanged(l){var y;ys(je,l,Re),pg(),Fo(l),Hn(!Ar),sg(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&mn(),!_o||bo?(_o=!0,$o=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==$o&&($o=p.id,og(p.id));let h=ht.lastUserMessageId;p&&p.id!==h&&(ht.lastUserMessageId=p.id,s.emit("user:message",p)),ht.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Zr(l),zo()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};lt(rn,(S=>{var H,z,O,B;return S==="idle"?(H=p.idleText)!=null?H:xn.idle:S==="connecting"?(z=p.connectingText)!=null?z:xn.connecting:S==="connected"?(O=p.connectedText)!=null?O:xn.connected:S==="error"?(B=p.errorText)!=null?B:xn.error:xn[S]})(l),p,l)},onStreamingChanged(l){Ar=l,si(l),_&&ys(je,_.getMessages(),Re),l||Hn(!0),zo()},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":Or(),Vo();break;case"processing":Or(),hg();break;case"speaking":Or(),yg();break;default:l==="idle"&&_.isBargeInActive()?(Or(),Vo(),q==null||q.setAttribute("aria-label","End voice session")):(ht.active=!1,Or(),tr("system"),Rn());break}},onArtifactsState(l){On=l,Un(),Zr()}}),St.current=_;let ii=null;if(_.onReadAloudChange((l,p)=>{var S;Vr=l,Kr=p,Gr();let h=l!=null?l:ii;l&&(ii=l);let y=h&&(S=_.getMessages().find(H=>H.id===h))!=null?S:null;s.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(ii=null)}),_o=!0,((Ec=(Mc=r.voiceRecognition)==null?void 0:Mc.provider)==null?void 0:Ec.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)}),(he||r.onSSEEvent)&&_.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),oe==null||oe.processEvent(l,p),he==null||he.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=al(l.metadata),I.syncFromMetadata()),(p=l.messages)!=null&&p.length){bo=!0;try{_.hydrateMessages(l.messages)}finally{bo=!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 yl=()=>{var p,h,y;!N()||k||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||$t(!0,"auto")},bl=l=>{var S;if(l.preventDefault(),_.isStreaming()){_.cancel(),oe==null||oe.reset(),K==null||K.update();return}let p=Te.value.trim(),h=(S=xt==null?void 0:xt.hasAttachments())!=null?S:!1;if(!p&&!h)return;yl();let y;h&&(y=[],y.push(...xt.getContentParts()),p&&y.push(Pi(p))),Te.value="",Te.style.height="auto",la(),_.sendMessage(p,{contentParts:y}),h&&xt.clearAttachments()},ug=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},li={...Ba},ci=!1,la=()=>{li={...Ba}},mg=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),gg=l=>{if(!Te)return;ci=!0,Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),ci=!1;let p=Te.value.length;Te.setSelectionRange(p,p)},vl=()=>{ci||la()},xl=l=>{if(Te){if(ug()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Te.selectionStart===0&&Te.selectionEnd===0,h=Ku({direction:l.key==="ArrowUp"?"up":"down",history:mg(),currentValue:Te.value,atStart:p,state:li});if(li=h.state,h.handled){l.preventDefault(),h.value!==void 0&&gg(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}la(),l.preventDefault(),me.click()}}},wl=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ce)&&(_.cancel(),oe==null||oe.reset(),K==null||K.update(),la(),l.preventDefault(),l.stopImmediatePropagation())},Cl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!xt)return;let p=vy(l.clipboardData);p.length!==0&&(l.preventDefault(),await xt.handleFiles(p))},nr=null,Er=!1,jo=null,mt=null,Al=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ca=(l="user")=>{var H,z,O,B,se,ae,Z;if(Er||_.isStreaming())return;let p=Al();if(!p)return;nr=new p;let y=(z=((H=r.voiceRecognition)!=null?H:{}).pauseDuration)!=null?z:2e3;nr.continuous=!0,nr.interimResults=!0,nr.lang="en-US";let S=Te.value;nr.onresult=be=>{let Fe="",Ce="";for(let $e=0;$e<be.results.length;$e++){let gt=be.results[$e],st=gt[0].transcript;gt.isFinal?Fe+=st+" ":Ce=st}let nt=S+Fe+Ce;Te.value=nt,jo&&clearTimeout(jo),(Fe||Ce)&&(jo=window.setTimeout(()=>{let $e=Te.value.trim();$e&&nr&&Er&&(to(),Te.value="",Te.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},y))},nr.onerror=be=>{be.error!=="no-speech"&&to()},nr.onend=()=>{if(Er){let be=Te.value.trim();be&&be!==S.trim()&&(Te.value="",Te.style.height="auto",_.sendMessage(be,{viaVoice:!0})),to()}};try{if(nr.start(),Er=!0,ht.active=!0,l!=="system"&&(ht.manuallyDeactivated=!1),tr(l),Rn(),q){let be=(O=r.voiceRecognition)!=null?O:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(B=be.iconName)!=null?B:"mic",iconSize:parseFloat((Z=(ae=be.iconSize)!=null?ae:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Fe=be.recordingBackgroundColor,Ce=be.recordingIconColor,nt=be.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let $e=q.querySelector("svg");$e&&$e.setAttribute("stroke",Ce)}nt&&(q.style.borderColor=nt),q.setAttribute("aria-label","Stop voice recognition")}}catch{to("system")}},to=(l="user")=>{if(Er){if(Er=!1,jo&&(clearTimeout(jo),jo=null),nr){try{nr.stop()}catch{}nr=null}if(ht.active=!1,tr(l),Rn(),q){if(q.classList.remove("persona-voice-recording"),mt){q.style.backgroundColor=mt.backgroundColor,q.style.color=mt.color,q.style.borderColor=mt.borderColor;let p=q.querySelector("svg");p&&p.setAttribute("stroke",mt.color||"currentColor"),mt=null}q.setAttribute("aria-label","Start voice recognition")}}},fg=(l,p)=>{var st,Be,We,ze,Ke,bt,P,Ne,De;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",S=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||y||S))return null;let z=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 B=(We=l==null?void 0:l.iconName)!=null?We:"mic",se=(ze=p==null?void 0:p.size)!=null?ze:"40px",ae=(Ke=l==null?void 0:l.iconSize)!=null?Ke:se,Z=parseFloat(ae)||24,be=(bt=l==null?void 0:l.backgroundColor)!=null?bt:p==null?void 0:p.backgroundColor,Fe=(P=l==null?void 0:l.iconColor)!=null?P:p==null?void 0:p.textColor;O.style.width=ae,O.style.height=ae,O.style.minWidth=ae,O.style.minHeight=ae,O.style.fontSize="18px",O.style.lineHeight="1",Fe?O.style.color=Fe:O.style.color="var(--persona-text, #111827)";let nt=Ae(B,Z,Fe||"currentColor",1.5);nt?O.appendChild(nt):O.textContent="\u{1F3A4}",be?O.style.backgroundColor=be:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),z.appendChild(O);let $e=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((De=l==null?void 0:l.showTooltip)!=null?De:!1)&&$e){let ge=b("div","persona-send-button-tooltip");ge.textContent=$e,z.appendChild(ge)}return{micButton:O,micButtonWrapper:z}},di=()=>{var p,h,y,S,H;if(!q||mt)return;let l=(p=r.voiceRecognition)!=null?p:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((H=(S=l.iconSize)!=null?S:(y=r.sendButton)==null?void 0:y.size)!=null?H:"40")||24}},pi=(l,p)=>{var H,z,O,B,se;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(se=mt==null?void 0:mt.iconSize)!=null?se:parseFloat((B=(O=(H=r.voiceRecognition)==null?void 0:H.iconSize)!=null?O:(z=r.sendButton)==null?void 0:z.size)!=null?B:"40")||24,S=Ae(l,y,p,1.5);S&&q.appendChild(S)},da=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Vo=()=>{var S;if(!q)return;di();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(da(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let H=q.querySelector("svg");H&&H.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},hg=()=>{var O,B,se,ae,Z,be,Fe,Ce;if(!q)return;di();let l=(O=r.voiceRecognition)!=null?O:{},p=_.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",y=(ae=(se=l.processingIconColor)!=null?se:mt==null?void 0:mt.color)!=null?ae:"",S=(be=(Z=l.processingBackgroundColor)!=null?Z:mt==null?void 0:mt.backgroundColor)!=null?be:"",H=(Ce=(Fe=l.processingBorderColor)!=null?Fe:mt==null?void 0:mt.borderColor)!=null?Ce:"";da(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=S,q.style.borderColor=H;let z=y||"currentColor";q.style.color=z,pi(h,z),q.setAttribute("aria-label","Processing voice input"),p==="none"&&(q.style.cursor="default")},yg=()=>{var se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We;if(!q)return;di();let l=(se=r.voiceRecognition)!=null?se:{},p=_.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ae=l.speakingIconName)!=null?ae:h,S=(Ce=l.speakingIconColor)!=null?Ce:p==="barge-in"?(be=(Z=l.recordingIconColor)!=null?Z:mt==null?void 0:mt.color)!=null?be:"":(Fe=mt==null?void 0:mt.color)!=null?Fe:"",H=(gt=l.speakingBackgroundColor)!=null?gt:p==="barge-in"?(nt=l.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":($e=mt==null?void 0:mt.backgroundColor)!=null?$e:"",z=(We=l.speakingBorderColor)!=null?We:p==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Be=mt==null?void 0:mt.borderColor)!=null?Be:"";da(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=H,q.style.borderColor=z;let O=S||"currentColor";q.style.color=O,pi(y,O);let B=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",B),p==="none"&&(q.style.cursor="default"),p==="barge-in"&&q.classList.add("persona-voice-recording")},Or=()=>{var l,p,h;q&&(da(),mt&&(q.style.backgroundColor=(l=mt.backgroundColor)!=null?l:"",q.style.color=(p=mt.color)!=null?p:"",q.style.borderColor=(h=mt.borderColor)!=null?h:"",pi(mt.iconName,mt.color||"currentColor"),mt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},pa=()=>{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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Rn(),tr("user"),Or()});return}_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),ht.manuallyDeactivated=!_.isVoiceActive(),Rn(),tr("user"),_.isVoiceActive()?Vo():Or()});return}if(Er){let h=Te.value.trim();ht.manuallyDeactivated=!0,Rn(),to("user"),h&&(Te.value="",Te.style.height="auto",_.sendMessage(h))}else ht.manuallyDeactivated=!1,Rn(),ca("user")};Nn=pa,q&&(q.addEventListener("click",pa),dt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Or()):to("system"),q&&q.removeEventListener("click",pa)}));let bg=s.on("assistant:complete",()=>{hs&&(ht.active||ht.manuallyDeactivated||hs==="assistant"&&!ht.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!ht.active&&!ht.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("auto"),_.isVoiceActive()&&Vo()}):ca("auto"))},600))});dt.push(bg);let vg=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(vg);let Sl=()=>{$t(!k,"user")},Xt=null,sn=null;if(M&&!N()){let{instance:l,element:p}=qi({config:r,plugins:o,onToggle:Sl});Xt=l,l||(sn=p)}Xt?n.appendChild(Xt.element):sn&&n.appendChild(sn),ws(),Fo(),hl(),si(_.isStreaming()),et()==="follow"?Hn(!0):eo(),aa(),F&&(!M||N()?setTimeout(()=>ai(),0):k&&setTimeout(()=>ai(),200));let Cs=()=>{var B,se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We,ze,Ke,bt,P,Ne,De,ge,Ft,Dt;if(N()){In(),ws();return}let l=gn(r),p=(se=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?se:!1,h=l||p||((Z=(ae=r.launcher)==null?void 0:ae.fullHeight)!=null?Z:!1),y=(be=n.ownerDocument.defaultView)!=null?be:window,S=(Ce=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ce:!0,H=($e=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?$e:640,z=y.innerWidth<=H,O=S&&z&&M;try{if(O){ye(),ls(n,r);return}if(W&&(W=!1,ye(),ls(n,r)),!M&&!l){pe.style.height="",pe.style.width="";return}if(!p&&!l){let zt=(st=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?st:r==null?void 0:r.launcherWidth,wt=zt!=null?zt:qr;pe.style.width=wt,pe.style.maxWidth=wt}if(xr(),!h){let zt=y.innerHeight,wt=64,Ut=(We=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?We:0,Kn=Math.max(200,zt-wt),Jt=Math.min(640,Kn),Qe=Math.max(200,Jt-Ut);pe.style.height=`${Qe}px`}}finally{if(In(),ws(),k&&M){let wt=((ze=n.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?bt:640),Ut=(Ne=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Ne:!1,Kn=(ge=(De=r.launcher)==null?void 0:De.mobileFullscreen)!=null?ge:!0,Jt=gn(r)&&Kn&&wt,Qe=Ut||Kn&&wt&&M||Jt;if(Qe&&!on){let kt=n.getRootNode(),nn=kt instanceof ShadowRoot?kt.host:n.closest(".persona-host");nn&&!Qt&&(Qt=Oi(nn,(Dt=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Dt:wn)),on=_i(n.ownerDocument)}else Qe||(Qt==null||Qt(),Qt=null,on==null||on(),on=null)}}};Cs();let Tl=(kc=n.ownerDocument.defaultView)!=null?kc:window;if(Tl.addEventListener("resize",Cs),dt.push(()=>Tl.removeEventListener("resize",Cs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{In()});l.observe(He),dt.push(()=>l.disconnect())}zn=we.scrollTop;let Ml=zr(we),xg=()=>{let l=we.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:we.ownerDocument.getSelection()},ui=()=>Zu(xg(),we),El=()=>{let l=we.scrollTop,p=zr(we),h=p<Ml;if(Ml=p,et()!=="follow"){zn=l,Je();return}let{action:y,nextLastScrollTop:S}=Na({following:qn.isFollowing(),currentScrollTop:l,lastScrollTop:zn,nearBottom:Ro(we,Uo),userScrollThreshold:oa,isAutoScrolling:dr||yo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(zn=S,y==="resume"){ui()||Nr();return}y==="pause"&&Et()};if(we.addEventListener("scroll",El,{passive:!0}),dt.push(()=>we.removeEventListener("scroll",El)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Vn()});l.observe(je),l.observe(we),dt.push(()=>l.disconnect())}let kl=()=>{et()==="follow"&&qn.isFollowing()&&ui()&&Et()},Ll=we.ownerDocument;Ll.addEventListener("selectionchange",kl),dt.push(()=>{Ll.removeEventListener("selectionchange",kl)});let Pl=l=>{if(et()!=="follow")return;let p=Fa({following:qn.isFollowing(),deltaY:l.deltaY,nearBottom:Ro(we,Uo),resumeWhenNearBottom:!0});p==="pause"?Et():p==="resume"&&!ui()&&Nr()};we.addEventListener("wheel",Pl,{passive:!0}),dt.push(()=>we.removeEventListener("wheel",Pl)),ct.addEventListener("click",()=>{mn(),we.scrollTop=we.scrollHeight,zn=we.scrollTop,Nr(),Hn(!0),Je()}),dt.push(()=>ct.remove()),dt.push(()=>{$(),mn()});let Il=()=>{Ve&&(Cr&&(Ve.removeEventListener("click",Cr),Cr=null),D()?(Ve.style.display="",Cr=()=>{$t(!1,"user")},Ve.addEventListener("click",Cr)):Ve.style.display="none")};Il(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{_.clearMessages(),Sr.clear(),Nr(),ts(J.composerOverlay);try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let 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={},I.syncFromMetadata(),he==null||he.clear(),oe==null||oe.reset(),K==null||K.update()})})(),It&&It.addEventListener("submit",bl),Te==null||Te.addEventListener("keydown",xl),Te==null||Te.addEventListener("input",vl),Te==null||Te.addEventListener("paste",Cl);let Wl=(Lc=n.ownerDocument)!=null?Lc:document;Wl.addEventListener("keydown",wl,!0);let Rl="persona-attachment-drop-active",As=0,mi=()=>{As=0,ce.classList.remove(Rl)},Ko=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&xt!==null},Hl=l=>{!ri(l.dataTransfer)||!Ko()||(As++,As===1&&ce.classList.add(Rl))},Bl=l=>{!ri(l.dataTransfer)||!Ko()||(As--,As<=0&&mi())},Dl=l=>{!ri(l.dataTransfer)||!Ko()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Nl=l=>{var h;if(!ri(l.dataTransfer)||!Ko())return;l.preventDefault(),l.stopPropagation(),mi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&xt.handleFiles(p)},no=!0;ce.addEventListener("dragenter",Hl,no),ce.addEventListener("dragleave",Bl,no),n.addEventListener("dragover",Dl,no),n.addEventListener("drop",Nl,no);let ua=n.ownerDocument,Fl=l=>{Ko()&&l.preventDefault()},Ol=l=>{Ko()&&l.preventDefault()};ua.addEventListener("dragover",Fl),ua.addEventListener("drop",Ol),dt.push(()=>{It&&It.removeEventListener("submit",bl),Te==null||Te.removeEventListener("keydown",xl),Te==null||Te.removeEventListener("input",vl),Te==null||Te.removeEventListener("paste",Cl),Wl.removeEventListener("keydown",wl,!0)}),dt.push(()=>{ce.removeEventListener("dragenter",Hl,no),ce.removeEventListener("dragleave",Bl,no),n.removeEventListener("dragover",Dl,no),n.removeEventListener("drop",Nl,no),ua.removeEventListener("dragover",Fl),ua.removeEventListener("drop",Ol),mi()}),dt.push(()=>{_.cancel()}),Xt?dt.push(()=>{Xt==null||Xt.destroy()}):sn&&dt.push(()=>{sn==null||sn.remove()});let tn={update(l){var bn,Mn,kr,dn,En,kn,So,Ss,Dc,Nc,Fc,Oc,_c,$c,Uc,qc,zc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,qd,zd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Mp,Ep,kp,Lp,Pp,Ip,Wp,Rp,Hp;let p=r.toolCall,h=r.messageActions,y=(bn=r.layout)==null?void 0:bn.messages,S=r.colorScheme,H=r.loadingIndicator,z=r.iterationDisplay,O=(Mn=r.features)==null?void 0:Mn.showReasoning,B=(kr=r.features)==null?void 0:kr.showToolCalls,se=(dn=r.features)==null?void 0:dn.toolCallDisplay,ae=(En=r.features)==null?void 0:En.reasoningDisplay;r={...r,...l},ye(),ls(n,r),ti(n,r),ni(n,r),Un(),r.colorScheme!==S&&fs();let Z=tl.getForInstance(r.plugins);o.length=0,o.push(...Z),M=(So=(kn=r.launcher)==null?void 0:kn.enabled)!=null?So:!0,E=(Dc=(Ss=r.launcher)==null?void 0:Ss.autoExpand)!=null?Dc:!1,Ue=(Fc=(Nc=r.features)==null?void 0:Nc.showReasoning)!=null?Fc:!0,xe=(_c=(Oc=r.features)==null?void 0:Oc.showToolCalls)!=null?_c:!0,_e=(Uc=($c=r.features)==null?void 0:$c.scrollToBottom)!=null?Uc:{};let be=et();Se=(zc=(qc=r.features)==null?void 0:qc.scrollBehavior)!=null?zc:{},be!==et()&&(mn(),Nr()),yr(),Je();let Fe=Ie;if(Ie=(Vc=(jc=r.features)==null?void 0:jc.showEventStreamToggle)!=null?Vc:!1,Ie&&!Fe){if(he||(X=new Zs(re),he=new Ys(ie,X),oe=oe!=null?oe:new ea,X.open().then(()=>he==null?void 0:he.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Tt)=>{var qt;(qt=r.onSSEEvent)==null||qt.call(r,ee,Tt),oe==null||oe.processEvent(ee,Tt),he.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&Me){let ee=(Gc=(Kc=r.features)==null?void 0:Kc.eventStream)==null?void 0:Gc.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");yt=b("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let qt=Ae("activity","18px","currentColor",1.5);qt&&yt.appendChild(qt);let at=J.clearChatButtonWrapper,Lt=J.closeButtonWrapper,ln=at||Lt;ln&&ln.parentNode===Me?Me.insertBefore(yt,ln):Me.appendChild(yt),yt.addEventListener("click",()=>{te?ir():Pr()})}}else!Ie&&Fe&&(ir(),yt&&(yt.remove(),yt=null),he==null||he.clear(),X==null||X.destroy(),he=null,X=null,oe==null||oe.reset(),oe=null);if(((Qc=r.launcher)==null?void 0:Qc.enabled)===!1&&Xt&&(Xt.destroy(),Xt=null),((Xc=r.launcher)==null?void 0:Xc.enabled)===!1&&sn&&(sn.remove(),sn=null),((Jc=r.launcher)==null?void 0:Jc.enabled)!==!1&&!Xt&&!sn){let{instance:ee,element:Tt}=qi({config:r,plugins:o,onToggle:Sl});Xt=ee,ee||(sn=Tt),n.appendChild(Tt)}Xt&&Xt.update(r),ue&&((Yc=r.launcher)==null?void 0:Yc.title)!==void 0&&(ue.textContent=r.launcher.title),Le&&((Zc=r.launcher)==null?void 0:Zc.subtitle)!==void 0&&(Le.textContent=r.launcher.subtitle);let Ce=(ed=r.layout)==null?void 0:ed.header;if((Ce==null?void 0:Ce.layout)!==A&&Me){let ee=Ce?za(r,Ce,{showClose:D(),onClose:()=>$t(!1,"user")}):Ho({config:r,showClose:D(),onClose:()=>$t(!1,"user")});rt.replaceHeader(ee),Me=rt.header.element,T=rt.header.iconHolder,ue=rt.header.headerTitle,Le=rt.header.headerSubtitle,Ve=rt.header.closeButton,A=Ce==null?void 0:Ce.layout}else if(Ce&&(T&&(T.style.display=Ce.showIcon===!1?"none":""),ue&&(ue.style.display=Ce.showTitle===!1?"none":""),Le&&(Le.style.display=Ce.showSubtitle===!1?"none":""),Ve&&(Ve.style.display=Ce.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let ee=Ce.showClearChat;if(ee!==void 0){J.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Tt}=J;Tt&&!Tt.classList.contains("persona-absolute")&&(ee?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let $e=((td=r.layout)==null?void 0:td.showHeader)!==!1;Me&&(Me.style.display=$e?"":"none");let gt=((nd=r.layout)==null?void 0:nd.showFooter)!==!1;He&&(He.style.display=gt?"":"none"),In(),Je(),M!==R?M?$t(E,"auto"):(k=!0,ws()):E!==L&&$t(E,"auto"),L=E,R=M,Cs(),Il();let We=JSON.stringify(l.toolCall)!==JSON.stringify(p),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((rd=r.layout)==null?void 0:rd.messages)!==JSON.stringify(y),bt=((od=r.loadingIndicator)==null?void 0:od.render)!==(H==null?void 0:H.render)||((sd=r.loadingIndicator)==null?void 0:sd.renderIdle)!==(H==null?void 0:H.renderIdle)||((ad=r.loadingIndicator)==null?void 0:ad.showBubble)!==(H==null?void 0:H.showBubble),P=r.iterationDisplay!==z,Ne=((ld=(id=r.features)==null?void 0:id.showReasoning)!=null?ld:!0)!==(O!=null?O:!0)||((dd=(cd=r.features)==null?void 0:cd.showToolCalls)!=null?dd:!0)!==(B!=null?B:!0)||JSON.stringify((pd=r.features)==null?void 0:pd.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((ud=r.features)==null?void 0:ud.reasoningDisplay)!==JSON.stringify(ae);(We||ze||Ke||bt||P||Ne)&&_&&(Oo++,ys(je,_.getMessages(),Re));let ge=(md=r.launcher)!=null?md:{},Ft=(gd=ge.headerIconHidden)!=null?gd:!1,Dt=(hd=(fd=r.layout)==null?void 0:fd.header)==null?void 0:hd.showIcon,zt=Ft||Dt===!1,wt=ge.headerIconName,Ut=(yd=ge.headerIconSize)!=null?yd:"48px";if(T){let ee=ce.querySelector(".persona-border-b-persona-divider"),Tt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(zt)T.style.display="none",ee&&Tt&&!ee.contains(Tt)&&ee.insertBefore(Tt,ee.firstChild);else{if(T.style.display="",T.style.height=Ut,T.style.width=Ut,ee&&Tt&&(ee.contains(T)?T.nextSibling!==Tt&&(T.remove(),ee.insertBefore(T,Tt)):ee.insertBefore(T,Tt)),wt){let at=parseFloat(Ut)||24,Lt=Ae(wt,at*.6,"currentColor",1);Lt?T.replaceChildren(Lt):T.textContent=(bd=ge.agentIconText)!=null?bd:"\u{1F4AC}"}else if(ge.iconUrl){let at=T.querySelector("img");if(at)at.src=ge.iconUrl,at.style.height=Ut,at.style.width=Ut;else{let Lt=document.createElement("img");Lt.src=ge.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Ut,Lt.style.width=Ut,T.replaceChildren(Lt)}}else{let at=T.querySelector("svg"),Lt=T.querySelector("img");(at||Lt)&&T.replaceChildren(),T.textContent=(vd=ge.agentIconText)!=null?vd:"\u{1F4AC}"}let qt=T.querySelector("img");qt&&(qt.style.height=Ut,qt.style.width=Ut)}}let Kn=(wd=(xd=r.layout)==null?void 0:xd.header)==null?void 0:wd.showTitle,Jt=(Ad=(Cd=r.layout)==null?void 0:Cd.header)==null?void 0:Ad.showSubtitle;if(ue&&(ue.style.display=Kn===!1?"none":""),Le&&(Le.style.display=Jt===!1?"none":""),Ve){((Td=(Sd=r.layout)==null?void 0:Sd.header)==null?void 0:Td.showCloseButton)===!1?Ve.style.display="none":Ve.style.display="";let Tt=(Md=ge.closeButtonSize)!=null?Md:"32px",qt=(Ed=ge.closeButtonPlacement)!=null?Ed:"inline";Ve.style.height=Tt,Ve.style.width=Tt;let{closeButtonWrapper:at}=J,Lt=qt==="top-right",ln=at==null?void 0:at.classList.contains("persona-absolute");if(at&&Lt!==ln)if(at.remove(),Lt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(at);else{let pt=(Ld=(kd=ge.clearChat)==null?void 0:kd.placement)!=null?Ld:"inline",cn=(Id=(Pd=ge.clearChat)==null?void 0:Pd.enabled)!=null?Id:!0;at.className=cn&&pt==="inline"?"":"persona-ml-auto";let Dn=ce.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(at)}if(Ve.style.color=ge.closeButtonColor||Pn.actionIconColor,ge.closeButtonBackgroundColor?(Ve.style.backgroundColor=ge.closeButtonBackgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let pt=ge.closeButtonBorderWidth||"0px",cn=ge.closeButtonBorderColor||"transparent";Ve.style.border=`${pt} solid ${cn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");ge.closeButtonBorderRadius?(Ve.style.borderRadius=ge.closeButtonBorderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(Ve.style.paddingLeft=ge.closeButtonPaddingX,Ve.style.paddingRight=ge.closeButtonPaddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),ge.closeButtonPaddingY?(Ve.style.paddingTop=ge.closeButtonPaddingY,Ve.style.paddingBottom=ge.closeButtonPaddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let vn=(Wd=ge.closeButtonIconName)!=null?Wd:"x",ur=(Rd=ge.closeButtonIconText)!=null?Rd:"\xD7";Ve.innerHTML="";let Ln=Ae(vn,"28px","currentColor",1);Ln?Ve.appendChild(Ln):Ve.textContent=ur;let Gt=(Hd=ge.closeButtonTooltipText)!=null?Hd:"Close chat",Qn=(Bd=ge.closeButtonShowTooltip)!=null?Bd:!0;if(Ve.setAttribute("aria-label",Gt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Qn&&Gt)){let pt=null,cn=()=>{if(pt||!Ve)return;let To=Ve.ownerDocument,Ts=To.body;if(!Ts)return;pt=Lr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Gt;let Ms=Lr(To,"div");Ms.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ms);let Mo=Ve.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(co),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ts.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};at.addEventListener("mouseenter",cn),at.addEventListener("mouseleave",Dn),Ve.addEventListener("focus",cn),Ve.addEventListener("blur",Dn),at._cleanupTooltip=()=>{Dn(),at&&(at.removeEventListener("mouseenter",cn),at.removeEventListener("mouseleave",Dn)),Ve&&(Ve.removeEventListener("focus",cn),Ve.removeEventListener("blur",Dn))}}}let{clearChatButton:Qe,clearChatButtonWrapper:kt}=J;if(Qe){let ee=(Dd=ge.clearChat)!=null?Dd:{},Tt=(Nd=ee.enabled)!=null?Nd:!0,qt=(Od=(Fd=r.layout)==null?void 0:Fd.header)==null?void 0:Od.showClearChat,at=qt!==void 0?qt:Tt,Lt=(_d=ee.placement)!=null?_d:"inline";if(kt){kt.style.display=at?"":"none";let{closeButtonWrapper:ln}=J;!N()&&ln&&!ln.classList.contains("persona-absolute")&&(at?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let vn=Lt==="top-right",ur=kt.classList.contains("persona-absolute");if(!N()&&vn!==ur&&at){if(kt.remove(),vn)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",ce.style.position="relative",ce.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let Gt=ce.querySelector(".persona-border-b-persona-divider"),Qn=J.closeButtonWrapper;Gt&&Qn&&Qn.parentElement===Gt?Gt.insertBefore(kt,Qn):Gt&&Gt.appendChild(kt)}let Ln=J.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(vn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(at){if(!N()){let pt=($d=ee.size)!=null?$d:"32px";Qe.style.height=pt,Qe.style.width=pt}let ln=(Ud=ee.iconName)!=null?Ud:"refresh-cw",vn=(qd=ee.iconColor)!=null?qd:"";Qe.style.color=vn||Pn.actionIconColor,Qe.innerHTML="";let ur=N()?"14px":"20px",Ln=Ae(ln,ur,"currentColor",2);if(Ln&&Qe.appendChild(Ln),ee.backgroundColor?(Qe.style.backgroundColor=ee.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let pt=ee.borderWidth||"0px",cn=ee.borderColor||"transparent";Qe.style.border=`${pt} solid ${cn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");ee.borderRadius?(Qe.style.borderRadius=ee.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),ee.paddingX?(Qe.style.paddingLeft=ee.paddingX,Qe.style.paddingRight=ee.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),ee.paddingY?(Qe.style.paddingTop=ee.paddingY,Qe.style.paddingBottom=ee.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Gt=(zd=ee.tooltipText)!=null?zd:"Clear chat",Qn=(jd=ee.showTooltip)!=null?jd:!0;if(Qe.setAttribute("aria-label",Gt),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),Qn&&Gt)){let pt=null,cn=()=>{if(pt||!Qe)return;let To=Qe.ownerDocument,Ts=To.body;if(!Ts)return;pt=Lr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Gt;let Ms=Lr(To,"div");Ms.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ms);let Mo=Qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(co),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ts.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};kt.addEventListener("mouseenter",cn),kt.addEventListener("mouseleave",Dn),Qe.addEventListener("focus",cn),Qe.addEventListener("blur",Dn),kt._cleanupTooltip=()=>{Dn(),kt&&(kt.removeEventListener("mouseenter",cn),kt.removeEventListener("mouseleave",Dn)),Qe&&(Qe.removeEventListener("focus",cn),Qe.removeEventListener("blur",Dn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rl],or=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ta.message,ta.messageAndClick];I=ol({parsers:nn,handlers:or,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Re=zm(r,I,ne),_.updateConfig(r),ys(je,_.getMessages(),Re),Fo(),hl(),si(_.isStreaming());let Gn=((Vd=r.voiceRecognition)==null?void 0:Vd.enabled)===!0,xo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),wo=((Gd=(Kd=r.voiceRecognition)==null?void 0:Kd.provider)==null?void 0:Gd.type)==="runtype";if(Gn&&(xo||wo))if(!q||!ot){let ee=fg(r.voiceRecognition,r.sendButton);ee&&(q=ee.micButton,ot=ee.micButtonWrapper,ut.insertBefore(ot,fn),q.addEventListener("click",pa),q.disabled=_.isStreaming())}else{let ee=(Qd=r.voiceRecognition)!=null?Qd:{},Tt=(Xd=r.sendButton)!=null?Xd:{},qt=(Jd=ee.iconName)!=null?Jd:"mic",at=(Yd=Tt.size)!=null?Yd:"40px",Lt=(Zd=ee.iconSize)!=null?Zd:at,ln=parseFloat(Lt)||24;q.style.width=Lt,q.style.height=Lt,q.style.minWidth=Lt,q.style.minHeight=Lt;let vn=(tp=(ep=ee.iconColor)!=null?ep:Tt.textColor)!=null?tp:"currentColor";q.innerHTML="";let ur=Ae(qt,ln,vn,2);ur?q.appendChild(ur):q.textContent="\u{1F3A4}";let Ln=(np=ee.backgroundColor)!=null?np:Tt.backgroundColor;Ln?q.style.backgroundColor=Ln:q.style.backgroundColor="",vn?q.style.color=vn:q.style.color="var(--persona-text, #111827)",ee.borderWidth?(q.style.borderWidth=ee.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),ee.borderColor?q.style.borderColor=ee.borderColor:q.style.borderColor="",ee.paddingX?(q.style.paddingLeft=ee.paddingX,q.style.paddingRight=ee.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),ee.paddingY?(q.style.paddingTop=ee.paddingY,q.style.paddingBottom=ee.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Gt=ot==null?void 0:ot.querySelector(".persona-send-button-tooltip"),Qn=(rp=ee.tooltipText)!=null?rp:"Start voice recognition";if(((op=ee.showTooltip)!=null?op:!1)&&Qn)if(Gt)Gt.textContent=Qn,Gt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Qn,ot==null||ot.insertBefore(cn,q)}else Gt&&(Gt.style.display="none");ot.style.display="",q.disabled=_.isStreaming()}else q&&ot&&(ot.style.display="none",((ap=(sp=r.voiceRecognition)==null?void 0:sp.provider)==null?void 0:ap.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Er&&to());if(((ip=r.attachments)==null?void 0:ip.enabled)===!0)if(!de||!G){let ee=(lp=r.attachments)!=null?lp:{},qt=(dp=((cp=r.sendButton)!=null?cp:{}).size)!=null?dp:"40px";vt||(vt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),vt.style.display="none",It.insertBefore(vt,Te)),ke||(ke=document.createElement("input"),ke.type="file",ke.accept=((pp=ee.allowedTypes)!=null?pp:Ur).join(","),ke.multiple=((up=ee.maxFiles)!=null?up:4)>1,ke.style.display="none",ke.setAttribute("aria-label","Attach files"),It.insertBefore(ke,Te)),de=b("div","persona-send-button-wrapper"),G=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),G.type="button",G.setAttribute("aria-label",(mp=ee.buttonTooltipText)!=null?mp:"Attach file");let at=(gp=ee.buttonIconName)!=null?gp:"paperclip",Lt=qt,ln=parseFloat(Lt)||40,vn=Math.round(ln*.6);G.style.width=Lt,G.style.height=Lt,G.style.minWidth=Lt,G.style.minHeight=Lt,G.style.fontSize="18px",G.style.lineHeight="1",G.style.backgroundColor="transparent",G.style.color="var(--persona-primary, #111827)",G.style.border="none",G.style.borderRadius="6px",G.style.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 ur=Ae(at,vn,"currentColor",1.5);ur?G.appendChild(ur):G.textContent="\u{1F4CE}",G.addEventListener("click",Qn=>{Qn.preventDefault(),ke==null||ke.click()}),de.appendChild(G);let Ln=(fp=ee.buttonTooltipText)!=null?fp:"Attach file",Gt=b("div","persona-send-button-tooltip");Gt.textContent=Ln,de.appendChild(Gt),Ge.append(de),!xt&&ke&&vt&&(xt=$s.fromConfig(ee),xt.setPreviewsContainer(vt),ke.addEventListener("change",async()=>{xt&&(ke!=null&&ke.files)&&(await xt.handleFileSelect(ke.files),ke.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild(jm(ee.dropOverlay))}else{de.style.display="";let ee=(hp=r.attachments)!=null?hp:{};ke&&(ke.accept=((yp=ee.allowedTypes)!=null?yp:Ur).join(","),ke.multiple=((bp=ee.maxFiles)!=null?bp:4)>1),xt&&xt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else de&&(de.style.display="none"),xt&&xt.clearAttachments(),(vp=ce.querySelector(".persona-attachment-drop-overlay"))==null||vp.remove();let jt=(xp=r.sendButton)!=null?xp:{},Co=(wp=jt.useIcon)!=null?wp:!1,ro=(Cp=jt.iconText)!=null?Cp:"\u2191",oo=jt.iconName,_r=(Ap=jt.tooltipText)!=null?Ap:"Send message",Ao=(Sp=jt.showTooltip)!=null?Sp:!1,pr=(Tp=jt.size)!=null?Tp:"40px",Ye=jt.backgroundColor,an=jt.textColor;if(Co){if(me.style.width=pr,me.style.height=pr,me.style.minWidth=pr,me.style.minHeight=pr,me.style.fontSize="18px",me.style.lineHeight="1",me.innerHTML="",an?me.style.color=an:me.style.color="var(--persona-button-primary-fg, #ffffff)",oo){let ee=parseFloat(pr)||24,Tt=(an==null?void 0:an.trim())||"currentColor",qt=Ae(oo,ee,Tt,2);qt?me.appendChild(qt):me.textContent=ro}else me.textContent=ro;me.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ye?(me.style.backgroundColor=Ye,me.classList.remove("persona-bg-persona-primary")):(me.style.backgroundColor="",me.classList.add("persona-bg-persona-primary"))}else me.textContent=(Ep=(Mp=r.copy)==null?void 0:Mp.sendButtonLabel)!=null?Ep:"Send",me.style.width="",me.style.height="",me.style.minWidth="",me.style.minHeight="",me.style.fontSize="",me.style.lineHeight="",me.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Ye?(me.style.backgroundColor=Ye,me.classList.remove("persona-bg-persona-accent")):me.classList.add("persona-bg-persona-accent"),an?me.style.color=an:me.classList.add("persona-text-white");jt.borderWidth?(me.style.borderWidth=jt.borderWidth,me.style.borderStyle="solid"):(me.style.borderWidth="",me.style.borderStyle=""),jt.borderColor?me.style.borderColor=jt.borderColor:me.style.borderColor="",jt.paddingX?(me.style.paddingLeft=jt.paddingX,me.style.paddingRight=jt.paddingX):(me.style.paddingLeft="",me.style.paddingRight=""),jt.paddingY?(me.style.paddingTop=jt.paddingY,me.style.paddingBottom=jt.paddingY):(me.style.paddingTop="",me.style.paddingBottom="");let _t=fn==null?void 0:fn.querySelector(".persona-send-button-tooltip");if(Ao&&_r)if(_t)_t.textContent=_r,_t.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=_r,fn==null||fn.insertBefore(ee,me)}else _t&&(_t.style.display="none");let Ot=(Wp=(kp=r.layout)==null?void 0:kp.contentMaxWidth)!=null?Wp:N()?(Ip=(Pp=(Lp=r.launcher)==null?void 0:Lp.composerBar)==null?void 0:Pp.contentMaxWidth)!=null?Ip:"720px":void 0;Ot?(je.style.maxWidth=Ot,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%",It&&(It.style.maxWidth=Ot,It.style.marginLeft="auto",It.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Ot,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(je.style.maxWidth="",je.style.marginLeft="",je.style.marginRight="",je.style.width="",It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let ft=(Rp=r.statusIndicator)!=null?Rp:{},Vt=(Hp=ft.visible)!=null?Hp:!0;if(rn.style.display=Vt?"":"none",_){let ee=_.getStatus();lt(rn,(qt=>{var at,Lt,ln,vn;return qt==="idle"?(at=ft.idleText)!=null?at:xn.idle:qt==="connecting"?(Lt=ft.connectingText)!=null?Lt:xn.connecting:qt==="connected"?(ln=ft.connectedText)!=null?ln:xn.connected:qt==="error"?(vn=ft.errorText)!=null?vn:xn.error:xn[qt]})(ee),ft,ee)}rn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let At=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";rn.classList.add(At)},open(){D()&&$t(!0,"api")},close(){D()&&$t(!1,"api")},toggle(){D()&&$t(!k,"api")},clearChat(){Sn=!1,_.clearMessages(),Sr.clear(),Nr();try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)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={},I.syncFromMetadata(),he==null||he.clear(),oe==null||oe.reset(),K==null||K.update()},setMessage(l){return!Te||_.isStreaming()?!1:(!k&&D()&&$t(!0,"system"),Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Te.value.trim();return p?(!k&&D()&&$t(!0,"system"),Te.value="",Te.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()||(!k&&D()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Rn(),_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("user"),_.isVoiceActive()&&Vo()})),!0):Er?!0:Al()?(!k&&D()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Rn(),ca("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(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Rn(),tr("user"),Or()}),!0):!1:Er?(ht.manuallyDeactivated=!0,Rn(),to("user"),!0):!1},injectMessage(l){return!k&&D()&&$t(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&D()&&$t(!0,"system");let p=_.injectAssistantMessage(l);return j&&(j=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(l){return!k&&D()&&$t(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&D()&&$t(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&D()&&$t(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&D()&&$t(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&D()&&$t(!0,"system"),_.injectTestEvent(l)},async connectStream(l,p){return _.connectStream(l,p)},__pushEventStreamEvent(l){he&&(oe==null||oe.processEvent(l.type,l.payload),he.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ie||!he||Pr()},hideEventStream(){te&&ir()},isEventStreamVisible(){return te},showArtifacts(){ar(r)&&(Sn=!1,Un(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){ar(r)&&(Sn=!0,Un())},upsertArtifact(l){return ar(r)?(Sn=!1,_.upsertArtifact(l)):null},selectArtifact(l){ar(r)&&_.selectArtifact(l)},clearArtifacts(){ar(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 M&&!k&&!N()||!Te?!1:(Te.focus(),!0)},async resolveApproval(l,p,h){let S=_.getMessages().find(H=>{var z;return H.variant==="approval"&&((z=H.approval)==null?void 0:z.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){u(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return D()&&k},isVoiceActive(){return ht.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:D()&&k,launcherEnabled:M,voiceActive:ht.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&D()&&$t(!0,"system");let p=je.querySelector(".persona-feedback-container");p&&p.remove();let h=$m({onSubmit:async(y,S)=>{var H;_.isClientTokenMode()&&await _.submitCSATFeedback(y,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&D()&&$t(!0,"system");let p=je.querySelector(".persona-feedback-container");p&&p.remove();let h=Um({onSubmit:async(y,S)=>{var H;_.isClientTokenMode()&&await _.submitNPSFeedback(y,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});je.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(){vo!=null&&(clearInterval(vo),vo=null),dt.forEach(l=>l()),Ee.remove(),Xe==null||Xe.remove(),Xt==null||Xt.destroy(),sn==null||sn.remove(),Cr&&Ve.removeEventListener("click",Cr)}};if((((Pc=t==null?void 0:t.debugTools)!=null?Pc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,dt.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 B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",p),dt.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ie){let O=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&tn.showEventStream()},B=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",B),dt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",B)})}let h=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.showArtifacts()},y=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.hideArtifacts()},S=O=>{let B=O.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&tn.upsertArtifact(B.artifact)},H=O=>{let B=O.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&tn.selectArtifact(B.id)},z=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",z),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",z)})}let rr=xy(r.persistState);if(rr&&D()){let l=wy(rr.storage),p=`${rr.keyPrefix}widget-open`,h=`${rr.keyPrefix}widget-voice`,y=`${rr.keyPrefix}widget-voice-mode`;if(l){let S=((Ic=rr.persist)==null?void 0:Ic.openState)&&l.getItem(p)==="true",H=((Wc=rr.persist)==null?void 0:Wc.voiceState)&&l.getItem(h)==="true",z=((Rc=rr.persist)==null?void 0:Rc.voiceState)&&l.getItem(y)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var O;if(H||z)tn.startVoiceRecognition();else if((O=rr.persist)!=null&&O.focusInput){let B=n.querySelector("textarea");B&&B.focus()}},100)},0),(Hc=rr.persist)!=null&&Hc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Bc=rr.persist)!=null&&Bc.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")})),rr.clearOnChatClear){let O=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},B=()=>O();window.addEventListener("persona:clear-chat",B),dt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return m&&D()&&setTimeout(()=>{tn.open()},0),zo(),ra||Up().then(()=>{_&&(Oo++,Sr.clear(),ys(je,_.getMessages(),Re))}).catch(()=>{}),tn};var Cy=(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},Ay=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},Sy=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},Ty=(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.")},Km=(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"},dl=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=""},Gm=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",dl(n)},il=n=>{n.style.transition=""},ll=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},cl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},oi=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},My=(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))},Ey=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Qm=(n,e,t,r,o,s,a)=>{var v,x,I,M,E,F;let i=gr(s),d=i.reveal==="push";My(n,e,t,r,d),Ey(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,m=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(M=(I=s==null?void 0:s.launcher)==null?void 0:I.mobileBreakpoint)!=null?M:640,g=c!=null?c.innerWidth<=f:!1;if(m&&g&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),ll(e),il(r),Gm(r),cl(t),oi(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=(E=s==null?void 0:s.launcher)==null?void 0:E.zIndex)!=null?F:wn),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"),Gm(r),Ay(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",ll(e),il(r),cl(t),oi(o,r);let L=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=L,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",il(r),dl(r),oi(o,r);let L=Cy(i.width,n.clientWidth),R=Math.max(0,n.clientWidth),A=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-L:0:a?0:-L;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+L}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="",ll(e),dl(r),cl(t),oi(o,r);let L=i.reveal==="emerge";L?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",Sy(r,i.maxHeight),r.style.overflow=L||W?"hidden":"visible",r.style.transition=A,L&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},ky=(n,e)=>{let t=n.ownerDocument.createElement("div");return Km(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Km(t,r)},destroy(){t.remove()}}},Ly=(n,e)=>{var F,L,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"),m=t.createElement("div"),f=(L=(F=e==null?void 0:e.launcher)==null?void 0:F.enabled)==null||L?(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",m.dataset.personaDockRole="host",c.appendChild(m),r.insertBefore(a,n),d.appendChild(n);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),gr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Qm(a,i,d,c,m,e,f)}),g.observe(a))},x=!1,I=()=>{Qm(a,i,d,c,m,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,Ty(a,gr(e)))},M=a.ownerDocument.defaultView,E=()=>{I()};return M==null||M.addEventListener("resize",E),gr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),I(),{mode:"docked",host:m,shell:a,syncWidgetState(W){let N=W.launcherEnabled?W.open:!0;f!==N&&(f=N,I())},updateConfig(W){var N,D;e=W,((D=(N=e==null?void 0:e.launcher)==null?void 0:N.enabled)!=null?D:!0)===!1&&(f=!0),I()},destroy(){M==null||M.removeEventListener("resize",E),u(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},Xm=(n,e)=>gn(e)?Ly(n,e):ky(n,e);var na={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Jm=.15,Ym=1.5,pl="persona-preview-shell-theme",Py={load:()=>null,save:()=>{},clear:()=>{}},Iy=["How do I get started?","Pricing & plans","Talk to support"];function ul(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Wy(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 Zm(n){let e=Wy(n);return`* { box-sizing: border-box; }
110
112
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
111
113
  html { color-scheme: ${n}; }
112
114
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -130,7 +132,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
130
132
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
131
133
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
132
134
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
133
- .preview-workspace-card.short { height: 96px; }`}function Xm(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(pl);r||(r=t.createElement("style"),r.id=pl,t.head.appendChild(r)),r.textContent=Qm(e)}var My=`
135
+ .preview-workspace-card.short { height: 96px; }`}function eg(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(pl);r||(r=t.createElement("style"),r.id=pl,t.head.appendChild(r)),r.textContent=Zm(e)}var Ry=`
134
136
  <div class="preview-iframe-mock" aria-hidden="true">
135
137
  <div class="preview-iframe-chrome">
136
138
  <span class="preview-iframe-dot"></span>
@@ -149,7 +151,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
149
151
  <div class="preview-iframe-line body"></div>
150
152
  <div class="preview-iframe-line body"></div>
151
153
  </div>
152
- </div>`,Ey=`
154
+ </div>`,Hy=`
153
155
  <div class="preview-workspace-content-shell" aria-hidden="true">
154
156
  <div class="preview-iframe-line hero"></div>
155
157
  <div class="preview-iframe-line body"></div>
@@ -162,8 +164,8 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
162
164
  <div class="preview-workspace-card short"></div>
163
165
  <div class="preview-workspace-card short"></div>
164
166
  </div>
165
- </div>`;function Jm(n,e,t,r){let o=`
166
- ${My}
167
+ </div>`;function tg(n,e,t,r){let o=`
168
+ ${Ry}
167
169
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
168
170
  <div class="preview-workspace-shell">
169
171
  <div class="preview-workspace-topbar">
@@ -175,7 +177,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
175
177
  </div>
176
178
  <div class="preview-workspace-body">
177
179
  <div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
178
- ${Ey}
180
+ ${Hy}
179
181
  </div>
180
182
  </div>
181
183
  </div>`;return`<!DOCTYPE html>
@@ -184,15 +186,15 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
184
186
  <meta charset="UTF-8">
185
187
  <meta name="viewport" content="width=device-width, initial-scale=1">
186
188
  <link rel="stylesheet" href="${ul(r)}">
187
- <style id="${pl}">${Qm(e)}</style>
189
+ <style id="${pl}">${Zm(e)}</style>
188
190
  </head>
189
191
  <body>
190
192
  ${t?s:o}
191
193
  </body>
192
- </html>`}var ky=()=>[{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()}],Ly=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 Py(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"&&Ly(e)?[...ky(),...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 Iy(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:Sy:n.suggestionChips,initialMessages:Py(e,n,t),storageAdapter:Ay};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Wy(n,e){var r,o;let t=n.theme?Wo(n.theme,{validate:!1}):Wo();return{...Nt,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function gs(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Iy(Wy(n,e),t,(o=n.appendedMessages)!=null?o:[])}function Ym(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:gs(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:gs(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:gs(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:gs(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:gs(n,t),shellMode:t}]}function Zm(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function m(){var E;return(E=t.device)!=null?E:"desktop"}function f(){var E;return(E=t.zoom)!=null?E:i}function g(){var k,j;let E=getComputedStyle(n),F=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),L=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),R=40,A=((k=t.compareMode)!=null?k:"off")!=="off",W=(n.clientWidth-F-R)/(A?2:1),N=n.clientHeight-L-R;if(W<=0||N<=0)return 1;let D=(j=na[m()])!=null?j:na.desktop;return Math.min(W/D.w,N/D.h,1)}function u(){var L,R,A;i=g();let E=Math.max(Km,Math.min(Gm,f()));d=E;let F=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let W of F){let N=(L=W.dataset.device)!=null?L:"desktop",D=(R=na[N])!=null?R:na.desktop;W.style.width=`${D.w*E}px`,W.style.height=`${D.h*E}px`,N==="mobile"&&(W.style.borderRadius=`${32*E}px`);let k=W.querySelector("iframe");k&&(k.style.width=`${D.w}px`,k.style.height=`${D.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${E})`)}(A=t.onScaleChange)==null||A.call(t,E)}function v(){var E;(E=t.onBeforeDestroy)==null||E.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 I(){var xe,Ie,_e,Se;if(a)return;v();let E=++c,F=Ym(t),L=m(),R=((xe=t.compareMode)!=null?xe:"off")!=="off",A=((Ie=t.scene)!=null?Ie:"conversation")==="minimized",W=(_e=t.widgetCssPath)!=null?_e:"/widget-dist/widget.css",N=(Se=t.buildSrcdoc)!=null?Se:Jm,D=L==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=ve=>`<div class="${D}" data-mount-id="${ve.mountId}" data-device="${L}" data-shell-mode="${ve.shellMode}">
194
+ </html>`}var By=()=>[{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()}],Dy=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 Ny(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"&&Dy(e)?[...By(),...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 Fy(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:Iy:n.suggestionChips,initialMessages:Ny(e,n,t),storageAdapter:Py};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Oy(n,e){var r,o;let t=n.theme?Wo(n.theme,{validate:!1}):Wo();return{...Nt,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function gs(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Fy(Oy(n,e),t,(o=n.appendedMessages)!=null?o:[])}function ng(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:gs(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:gs(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:gs(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:gs(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:gs(n,t),shellMode:t}]}function rg(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function m(){var E;return(E=t.device)!=null?E:"desktop"}function f(){var E;return(E=t.zoom)!=null?E:i}function g(){var k,j;let E=getComputedStyle(n),F=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),L=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),R=40,A=((k=t.compareMode)!=null?k:"off")!=="off",W=(n.clientWidth-F-R)/(A?2:1),N=n.clientHeight-L-R;if(W<=0||N<=0)return 1;let D=(j=na[m()])!=null?j:na.desktop;return Math.min(W/D.w,N/D.h,1)}function u(){var L,R,A;i=g();let E=Math.max(Jm,Math.min(Ym,f()));d=E;let F=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let W of F){let N=(L=W.dataset.device)!=null?L:"desktop",D=(R=na[N])!=null?R:na.desktop;W.style.width=`${D.w*E}px`,W.style.height=`${D.h*E}px`,N==="mobile"&&(W.style.borderRadius=`${32*E}px`);let k=W.querySelector("iframe");k&&(k.style.width=`${D.w}px`,k.style.height=`${D.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${E})`)}(A=t.onScaleChange)==null||A.call(t,E)}function v(){var E;(E=t.onBeforeDestroy)==null||E.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 I(){var xe,Ie,_e,Se;if(a)return;v();let E=++c,F=ng(t),L=m(),R=((xe=t.compareMode)!=null?xe:"off")!=="off",A=((Ie=t.scene)!=null?Ie:"conversation")==="minimized",W=(_e=t.widgetCssPath)!=null?_e:"/widget-dist/widget.css",N=(Se=t.buildSrcdoc)!=null?Se:tg,D=L==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=ve=>`<div class="${D}" data-mount-id="${ve.mountId}" data-device="${L}" data-shell-mode="${ve.shellMode}">
193
195
  ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${ul(ve.label)}</span></div>`:""}
194
196
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ve.mountId}"></iframe>
195
- </div>`,j=R?`<div class="preview-compare-grid">${F.map(ve=>`<div class="preview-compare-cell">${k(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${k(F[0])}</div>`;t.morphContainer?t.morphContainer(n,j):n.innerHTML=j,u();let V=x(),ne=0,Re=V.length,Ue=()=>{var re,X,ie,he,oe;if(a||E!==c)return;for(let K of V){let te=K.dataset.mountId;if(!te||!K.contentDocument)continue;let qe=F.find(lt=>lt.mountId===te);if(!qe)continue;let Y=()=>{},le=gn(qe.config),Pe=le?(()=>{var J;let lt=(J=K.contentDocument)==null?void 0:J.getElementById(`preview-content-${te}`);if(!lt)return null;let rt=Vm(lt,qe.config),Ee=K.contentDocument.createElement("div");Ee.id=te,Ee.style.height="100%",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1",Ee.style.minHeight="0",rt.host.appendChild(Ee);let pe=()=>rt.syncWidgetState(it.getState()),Xe=Y;return Y=()=>{rt.destroy(),Xe()},Ee.__syncDock=pe,Ee.__hostLayout=rt,Ee})():K.contentDocument.getElementById(te);if(!Pe)continue;let it=Um(Pe,qe.config);if(r.push(it),le&&Pe.__syncDock){let lt=Pe.__syncDock,rt=it.on("widget:opened",lt),Ee=it.on("widget:closed",lt),pe=Y;Y=()=>{rt(),Ee(),pe()},lt()}o.push(Y),A&&it.close()}if(((re=t.scene)!=null?re:"conversation")==="artifact"||(he=(ie=(X=t.config)==null?void 0:X.features)==null?void 0:ie.artifacts)!=null&&he.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
197
+ </div>`,j=R?`<div class="preview-compare-grid">${F.map(ve=>`<div class="preview-compare-cell">${k(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${k(F[0])}</div>`;t.morphContainer?t.morphContainer(n,j):n.innerHTML=j,u();let V=x(),ne=0,Re=V.length,Ue=()=>{var re,X,ie,he,oe;if(a||E!==c)return;for(let K of V){let te=K.dataset.mountId;if(!te||!K.contentDocument)continue;let qe=F.find(lt=>lt.mountId===te);if(!qe)continue;let Y=()=>{},le=gn(qe.config),Pe=le?(()=>{var J;let lt=(J=K.contentDocument)==null?void 0:J.getElementById(`preview-content-${te}`);if(!lt)return null;let rt=Xm(lt,qe.config),Ee=K.contentDocument.createElement("div");Ee.id=te,Ee.style.height="100%",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1",Ee.style.minHeight="0",rt.host.appendChild(Ee);let pe=()=>rt.syncWidgetState(it.getState()),Xe=Y;return Y=()=>{rt.destroy(),Xe()},Ee.__syncDock=pe,Ee.__hostLayout=rt,Ee})():K.contentDocument.getElementById(te);if(!Pe)continue;let it=Vm(Pe,qe.config);if(r.push(it),le&&Pe.__syncDock){let lt=Pe.__syncDock,rt=it.on("widget:opened",lt),Ee=it.on("widget:closed",lt),pe=Y;Y=()=>{rt(),Ee(),pe()},lt()}o.push(Y),A&&it.close()}if(((re=t.scene)!=null?re:"conversation")==="artifact"||(he=(ie=(X=t.config)==null?void 0:X.features)==null?void 0:ie.artifacts)!=null&&he.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
196
198
 
197
199
  This is a preview of the artifact sidebar.
198
200
 
@@ -200,4 +202,4 @@ This is a preview of the artifact sidebar.
200
202
 
201
203
  - Markdown rendering
202
204
  - Document toolbar
203
- - Resizable panes`});(oe=t.onAfterMount)==null||oe.call(t,{iframes:V,controllers:[...r]})};for(let ve of V){let re=ve.dataset.mountId;if(!re)continue;let X=F.find(ie=>ie.mountId===re);X&&(ve.addEventListener("load",()=>{ne++,ne>=Re&&Ue()},{once:!0}),ve.srcdoc=N(re,X.shellMode,gn(X.config),W))}Re===0&&Ue()}function M(){var L;if(a)return;let E=Ym(t);if(r.length!==E.length){I();return}if(E.some(R=>{let A=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!A||A.dataset.shellMode!==R.shellMode})){I();return}r.forEach((R,A)=>{var W;R.update(E[A].config),((W=t.scene)!=null?W:"conversation")==="minimized"&&R.close()});for(let R of E){let A=n.querySelector(`iframe[data-mount-id="${R.mountId}"]`);A&&Xm(A,R.shellMode)}(L=t.onAfterUpdate)==null||L.call(t,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(n)),I(),{update(E){if(a)return;let F=E.device!==void 0&&E.device!==t.device||E.scene!==void 0&&E.scene!==t.scene||E.compareMode!==void 0&&E.compareMode!==t.compareMode||E.widgetCssPath!==void 0&&E.widgetCssPath!==t.widgetCssPath;t={...t,...E},F?I():M()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},u())},getIframes(){return x()},getScale(){return d},setZoom(E){a||(t={...t,zoom:E},u())}}}0&&(module.exports={createThemePreview});
205
+ - Resizable panes`});(oe=t.onAfterMount)==null||oe.call(t,{iframes:V,controllers:[...r]})};for(let ve of V){let re=ve.dataset.mountId;if(!re)continue;let X=F.find(ie=>ie.mountId===re);X&&(ve.addEventListener("load",()=>{ne++,ne>=Re&&Ue()},{once:!0}),ve.srcdoc=N(re,X.shellMode,gn(X.config),W))}Re===0&&Ue()}function M(){var L;if(a)return;let E=ng(t);if(r.length!==E.length){I();return}if(E.some(R=>{let A=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!A||A.dataset.shellMode!==R.shellMode})){I();return}r.forEach((R,A)=>{var W;R.update(E[A].config),((W=t.scene)!=null?W:"conversation")==="minimized"&&R.close()});for(let R of E){let A=n.querySelector(`iframe[data-mount-id="${R.mountId}"]`);A&&eg(A,R.shellMode)}(L=t.onAfterUpdate)==null||L.call(t,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(n)),I(),{update(E){if(a)return;let F=E.device!==void 0&&E.device!==t.device||E.scene!==void 0&&E.scene!==t.scene||E.compareMode!==void 0&&E.compareMode!==t.compareMode||E.widgetCssPath!==void 0&&E.widgetCssPath!==t.widgetCssPath;t={...t,...E},F?I():M()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},u())},getIframes(){return x()},getScale(){return d},setZoom(E){a||(t={...t,zoom:E},u())}}}0&&(module.exports={createThemePreview});