@runtypelabs/persona 3.22.0 → 3.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,18 +1,18 @@
1
- import{Marked as ym}from"marked";var bm=e=>{if(e)return e},fa=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new ym({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=bm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Oo=e=>e?fa({markedOptions:e.options,renderer:e.renderer}):fa(),xm=fa(),gp=e=>xm(e),Fo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),fp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),mp=e=>`%%FORM_PLACEHOLDER_${e}%%`,hp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=mp(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=mp(n.length);return n.push({token:o,type:s}),o}),t},vm=e=>{let n=Oo(e);return t=>{let r=[],s=hp(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${fp(i)}"></div>`;o=o.replace(d,u)}),o}},wm=e=>{let n=[],t=hp(e,n),r=gp(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${fp(o)}"></div>`;r=r.replace(a,d)}),r};import Cm from"dompurify";var Am={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"]},Sm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,yp=()=>{let e=Cm(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!Sm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,Am)},Cs=e=>e===!1?null:typeof e=="function"?e:yp();var ya="webmcp:",ha={warn(e,...n){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...n)}},As=class{constructor(n){this.config=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=n.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(n){this.confirmHandler=n}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let n=this.getModelContext();if(!n)return[];let t;try{t=await n.getTools()}catch(s){return ha.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return t.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Tm(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(n,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return ir("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let m=typeof document!="undefined"&&!!document.modelContext;return ir(m?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=bp(n),a;try{a=await s.getTools()}catch(m){let v=m instanceof Error?m.message:String(m);return ir(`Failed to read WebMCP registry: ${v}`)}let i=a.find(m=>m.name===o);if(!i)return ir(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return ir(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return ir("Aborted by cancel()");let d={toolName:o,args:t,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return ir("User declined the tool call.");if(r!=null&&r.aborted)return ir("Aborted by cancel()");let l=new AbortController,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),f=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",f,{once:!0}));try{let m=await s.executeTool(i,Pm(t),{signal:l.signal});return Mm(m)}catch(m){if(u)return ir(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return ir("Aborted by cancel()");let v=m instanceof Error?m.message:String(m);return ir(v)}finally{clearTimeout(p),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(n){ha.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",n),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let n=document.modelContext;if(!n||typeof n!="object")return null;let t=n;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() \u2014 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):n}async requestConfirm(n){var r;let t=(r=this.confirmHandler)!=null?r:km;try{return await t(n)}catch(s){return ha.warn(`Confirm handler threw for WebMCP tool '${n.toolName}'; declining.`,s),!1}}passesClientAllowlist(n){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Em(n,r))}},bp=e=>e.startsWith(ya)?e.slice(ya.length):e,ba=e=>e.startsWith(ya),Em=(e,n)=>{if(n==="*")return!0;let t=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)},Tm=e=>{if(!(e===void 0||e===""))try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:void 0}catch{return}},Mm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let n;try{n=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return n!==null&&typeof n=="object"&&Array.isArray(n.content)?n:{content:[{type:"text",text:typeof n=="string"?n:Im(n)}]}},ir=e=>({isError:!0,content:[{type:"text",text:e}]}),km=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let n=Lm(e.args),t=`Allow the AI to call ${e.toolName}`+(n?`
1
+ import{Marked as Tm}from"marked";var Mm=e=>{if(e)return e},ba=e=>{var s,o;let t=e==null?void 0:e.markedOptions,n=new Tm({gfm:(s=t==null?void 0:t.gfm)!=null?s:!0,breaks:(o=t==null?void 0:t.breaks)!=null?o:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),r=Mm(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},$o=e=>e?ba({markedOptions:e.options,renderer:e.renderer}):ba(),km=ba(),vp=e=>km(e),jo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),wp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),xp=e=>`%%FORM_PLACEHOLDER_${e}%%`,Cp=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=xp(t.length);return t.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=xp(t.length);return t.push({token:o,type:s}),o}),n},Lm=e=>{let t=$o(e);return n=>{let r=[],s=Cp(n,r),o=t(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${wp(i)}"></div>`;o=o.replace(d,u)}),o}},Pm=e=>{let t=[],n=Cp(e,t),r=vp(n);return t.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${wp(o)}"></div>`;r=r.replace(a,d)}),r};import Im from"dompurify";var Wm={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"]},Rm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ap=()=>{let e=Im(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(t,n)=>{if(n.attrName==="src"||n.attrName==="href"){let r=n.attrValue;r.toLowerCase().startsWith("data:")&&!Rm.test(r)&&(n.attrValue="",n.keepAttr=!1)}}),t=>e.sanitize(t,Wm)},Es=e=>e===!1?null:typeof e=="function"?e:Ap();var va="webmcp:",xa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Ts=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return xa.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Bm(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let m=typeof document!="undefined"&&!!document.modelContext;return hr(m?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=Sp(t),a;try{a=await s.getTools()}catch(m){let v=m instanceof Error?m.message:String(m);return hr(`Failed to read WebMCP registry: ${v}`)}let i=a.find(m=>m.name===o);if(!i)return hr(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return hr(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d={toolName:o,args:n,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let l=new AbortController,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),f=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",f,{once:!0}));try{let m=await s.executeTool(i,Fm(n),{signal:l.signal});return Dm(m)}catch(m){if(u)return hr(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let v=m instanceof Error?m.message:String(m);return hr(v)}finally{clearTimeout(p),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){xa.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,xa.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Nm;try{return await n(t)}catch(s){return xa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,s),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Hm(t,r))}},Sp=e=>e.startsWith(va)?e.slice(va.length):e,wa=e=>e.startsWith(va),Hm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Bm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Dm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:_m(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),Nm=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Om(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
2
2
 
3
3
  Arguments:
4
- ${n}`:"")+(e.description?`
4
+ ${t}`:"")+(e.description?`
5
5
 
6
- ${e.description}`:"");return window.confirm(t)},Lm=e=>{if(e==null)return"";try{let n=JSON.stringify(e,null,2);return n.length>500?n.slice(0,500)+"\u2026":n}catch{return String(e)}},Pm=e=>{if(e===void 0)return"{}";try{let n=JSON.stringify(e);return n===void 0?"{}":n}catch{return"{}"}},Im=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as xp,STR as vp,OBJ as wp}from"partial-json";var xa=e=>e.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),$o=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Wm=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Cp=e=>e.status==="complete"?Wm(e):e.status==="pending"?"Waiting":"",Rm=e=>{var s,o,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Ap=e=>e.status==="complete"?Rm(e):"Using tool...",va=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},Es=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return va(n)},wa=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return va(n)},yi=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Es(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ca=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Ss(r,t.slice(o,a.index),[]),a[1]!==void 0?Ss(r,a[1],["bold"]):a[2]!==void 0?Ss(r,a[2],["italic"]):a[3]!==void 0&&Ss(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Ss(r,t.slice(o),[]),r},Ss=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},Hm=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
6
+ ${e.description}`:"");return window.confirm(n)},Om=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Fm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},_m=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Ep,STR as Tp,OBJ as Mp}from"partial-json";var Ca=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Uo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},$m=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},kp=e=>e.status==="complete"?$m(e):e.status==="pending"?"Waiting":"",jm=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Lp=e=>e.status==="complete"?jm(e):"Using tool...",Aa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ks=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Aa(t)},Sa=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Aa(t)},wi=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=ks(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ea=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Ms(r,n.slice(o,a.index),[]),a[1]!==void 0?Ms(r,a[1],["bold"]):a[2]!==void 0?Ms(r,a[2],["italic"]):a[3]!==void 0&&Ms(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Ms(r,n.slice(o),[]),r},Ms=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Um=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Co=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},bi=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},xi=()=>{var n;let e=Hm();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},vi=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=xp(t,vp|wp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?xa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=xa(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Bm=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?xa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xa(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=xp(o,vp|wp),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},wi=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Aa=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Dm="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function Nm(e){var o,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let s=n.indexOf("/");if(s>0){let i=(a=(o=n.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ci=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Om(e){switch(e){case"json":return vi;case"regex-json":return xi;case"xml":return wi;default:return bi}}var Sp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Fm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=Sp(t);if(!Sp(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Co(e);return Co(n)!==null&&a===null?n:e}var _o=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s,o;this.apiUrl=(t=n.apiUrl)!=null?t:Dm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Om(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders,this.webMcpBridge=((o=n.webmcp)==null?void 0:o.enabled)===!0?new As(n.webmcp):null}setSSEEventCallback(n){this.onSSEEvent=n}setWebMcpConfirmHandler(n){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(n)}isWebMcpOperational(){var n;return((n=this.webMcpBridge)==null?void 0:n.isOperational())===!0}executeWebMcpToolCall(n,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(n,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/${n}`}getClientSession(){return this.clientSession}async initSession(){var n,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,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/feedback`}async sendFeedback(n){var o,a;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(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,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:n,comment:t})}async submitNPSFeedback(n,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:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.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.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(Ci).map(m=>{var v,x,S;return{id:m.id,role:m.role,content:(S=(x=(v=m.contentParts)!=null?v:m.llmContent)!=null?x:m.rawContent)!=null?S:m.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}if(f.status===429){let x=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:x}),x}let v=new Error(m.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw 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(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var l,u;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Sa}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:n,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(n){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Ci).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(n){var o;let r={messages:n.slice().filter(Ci).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(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(n,t,r){var zt,vr,dr,Ue;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=U=>{let Ae=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,Be=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,De=U.tools?U.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...U,reasoning:Ae,toolCall:Be,tools:De}},p=U=>{t({type:"message",message:u(U)})},f=null,m=null,v={current:null},x={current:null},S=!1,A=new Map,k=new Map,R=new Map,H=new Map,L={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},B=(U,Ae,Be="")=>`${U}::${Ae}::${Be}`,F=(U,Ae)=>`${U}::${Ae}::`,$=(U,Ae,Be,De)=>{let _e=B(U,Ae,Be),ct=R.get(_e);if(ct)return ct;let nt=Be?`-${Be}`:"",Ct={id:`nested-${U}-${Ae}${nt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:De,parentToolId:U,parentStepId:Ae}};return R.set(_e,Ct),p(Ct),Ct},W=U=>{if(U==null)return null;try{return String(U)}catch{return null}},O=U=>{var Ae,Be,De,_e,ct;return W((ct=(_e=(De=(Be=(Ae=U.stepId)!=null?Ae:U.step_id)!=null?Be:U.step)!=null?De:U.parentId)!=null?_e:U.flowStepId)!=null?ct:U.flow_step_id)},V=U=>{var Ae,Be,De,_e,ct,nt,Ct;return W((Ct=(nt=(ct=(_e=(De=(Be=(Ae=U.callId)!=null?Ae:U.call_id)!=null?Be:U.requestId)!=null?De:U.request_id)!=null?_e:U.toolCallId)!=null?ct:U.tool_call_id)!=null?nt:U.stepId)!=null?Ct:U.step_id)},oe=r,Ie=!1,Pe=()=>{if(f)return f;let U;return!Ie&&oe?(U=oe,Ie=!0):oe&&x.current?U=`${oe}_${x.current}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:U,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},ze=(U,Ae)=>{L.lastId=Ae,U&&L.byStep.set(U,Ae)},pe=(U,Ae)=>{var ct;let Be=(ct=U.reasoningId)!=null?ct:U.id,De=O(U);if(Be){let nt=String(Be);return ze(De,nt),nt}if(De){let nt=L.byStep.get(De);if(nt)return L.lastId=nt,nt}if(L.lastId&&!Ae)return L.lastId;if(!Ae)return null;let _e=`reason-${l()}`;return ze(De,_e),_e},ce=U=>{let Ae=A.get(U);if(Ae)return Ae;let Be={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"streaming",chunks:[]}};return A.set(U,Be),p(Be),Be},Ee=(U,Ae)=>{w.lastId=Ae,U&&w.byCall.set(U,Ae)},je=new Set,te=new Map,xe=new Set,G=new Map,ae=U=>{if(!U)return!1;let Ae=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ae==="emit_artifact_markdown"||Ae==="emit_artifact_component"},He=(U,Ae)=>{var ct;let Be=(ct=U.toolId)!=null?ct:U.id,De=V(U);if(Be){let nt=String(Be);return Ee(De,nt),nt}if(De){let nt=w.byCall.get(De);if(nt)return w.lastId=nt,nt}if(w.lastId&&!Ae)return w.lastId;if(!Ae)return null;let _e=`tool-${l()}`;return Ee(De,_e),_e},ue=U=>{let Ae=k.get(U);if(Ae)return Ae;let Be={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:U,status:"pending"}};return k.set(U,Be),p(Be),Be},Re=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let Ae=Number(U);if(!Number.isNaN(Ae)&&Number.isFinite(Ae))return Ae;let Be=Date.parse(U);if(!Number.isNaN(Be))return Be}return Date.now()},tt=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},K=new Map,se=new Map,Oe=new Map,J=new Map,z=null,we=(U,Ae,Be)=>{var Ct;let De=Oe.get(U);De||(De=[],Oe.set(U,De));let _e=0,ct=De.length;for(;_e<ct;){let jt=_e+ct>>>1;De[jt].seq<Ae?_e=jt+1:ct=jt}((Ct=De[_e])==null?void 0:Ct.seq)===Ae?De[_e]={seq:Ae,text:Be}:De.splice(_e,0,{seq:Ae,text:Be});let nt="";for(let jt=0;jt<De.length;jt++)nt+=De[jt].text;return nt},$e=(U,Ae)=>{let Be=tt(Ae),De=se.get(U.id),_e=Fm(De,Be);U.rawContent=_e;let ct=K.get(U.id),nt=ge=>{var Ke;let dt=(Ke=U.content)!=null?Ke:"";ge.trim()!==""&&(dt.trim().length===0||ge.startsWith(dt)||ge.trimStart().startsWith(dt.trim()))&&(U.content=ge)},Ct=()=>{var ge;if(ct){let dt=(ge=ct.close)==null?void 0:ge.call(ct);dt instanceof Promise&&dt.catch(()=>{})}K.delete(U.id),se.delete(U.id),U.streaming=!1,p(U)};if(!ct){nt(Be),Ct();return}let jt=Co(_e);if(jt!==null&&jt.trim()!==""){nt(jt),Ct();return}let P=ge=>{var It;let dt=typeof ge=="string"?ge:(It=ge==null?void 0:ge.text)!=null?It:null;if(dt!==null&&dt.trim()!=="")return dt;let Ke=ct.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Be},he;try{he=ct.processChunk(_e)}catch{nt(Be),Ct();return}if(he instanceof Promise){he.then(ge=>{nt(P(ge)),Ct()}).catch(()=>{nt(Be),Ct()});return}nt(P(he)),Ct()},ne=[],Te=!1,ve,Ht=()=>{Te||(Te=!0,queueMicrotask(()=>{Te=!1,ve()}))},ie=new Aa((U,Ae)=>{ne.push({payloadType:U,payload:Ae}),Ht()}),re=null,sn=new Map,Nt=(zt=this.config.iterationDisplay)!=null?zt:"separate";for(ve=()=>{var U,Ae,Be,De,_e,ct,nt,Ct,jt,P,he,ge,dt,Ke,It,an,At,bt,Mt,ut,Vt,wr,_n,Br,vt,pr,ur,Cr,Qn,gt,io,mr,lo,Sn,ko,Dr,Ar,yt,Pn,In,fn,kt,jn,Un,Wn,Nr,Sr,Or,Rn,Wt,hn,qn,Fr,Er,$r,gr,Hn,Zn,ft,Kt,Jt,Bn,_r,zn,er,Dn,_,de,Nn,tr,fr,ns,nr,rr,or,Tr,co,Js,rs,Gs,Lo,mt,os,Vn,En,Xs,Ys,Po,Mr,Qs,po,ss,kr,as,jr,Ur,Zs,ea,fi,uo,qr,ta,is,zr,na,ls,Vr,cs,ra,Lr,oa,Kr,Rt,Io,Wo,ds,hr,sa,ps,us,aa,Ro,Ho,mo,ia,la,ms,gs,fs,hs,yn,On,Pr,rt,ys,go,sr,ca;for(let Jr=0;Jr<ne.length;Jr++){let Ve=ne[Jr].payloadType,C=ne[Jr].payload;if(Ve==="reason_start"){let j=(U=pe(C,!0))!=null?U:`reason-${l()}`,M=ce(j);M.reasoning=(Ae=M.reasoning)!=null?Ae:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(De=M.reasoning.startedAt)!=null?De:Re((Be=C.startedAt)!=null?Be:C.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",p(M)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let j=(ct=(_e=pe(C,!1))!=null?_e:pe(C,!0))!=null?ct:`reason-${l()}`,M=ce(j);M.reasoning=(nt=M.reasoning)!=null?nt:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(jt=M.reasoning.startedAt)!=null?jt:Re((Ct=C.startedAt)!=null?Ct:C.timestamp);let Z=(ge=(he=(P=C.reasoningText)!=null?P:C.text)!=null?he:C.delta)!=null?ge:"";if(Z&&C.hidden!==!0){let X=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(X!==void 0){let Y=we(j,X,String(Z));M.reasoning.chunks=[Y]}else M.reasoning.chunks.push(String(Z))}if(M.reasoning.status=C.done?"complete":"streaming",C.done){M.reasoning.completedAt=Re((dt=C.completedAt)!=null?dt:C.timestamp);let X=(Ke=M.reasoning.startedAt)!=null?Ke:Date.now();M.reasoning.durationMs=Math.max(0,((It=M.reasoning.completedAt)!=null?It:Date.now())-X)}M.streaming=M.reasoning.status!=="complete",p(M)}else if(Ve==="reason_complete"){let j=(At=(an=pe(C,!1))!=null?an:pe(C,!0))!=null?At:`reason-${l()}`,M=A.get(j);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=Re((bt=C.completedAt)!=null?bt:C.timestamp);let X=(Mt=M.reasoning.startedAt)!=null?Mt:Date.now();M.reasoning.durationMs=Math.max(0,((ut=M.reasoning.completedAt)!=null?ut:Date.now())-X),M.streaming=!1,p(M)}let Z=O(C);Z&&L.byStep.delete(Z)}else if(Ve==="tool_start"){let j=(Vt=He(C,!0))!=null?Vt:`tool-${l()}`,M=(wr=C.toolName)!=null?wr:C.name;if(ae(M)){je.add(j);continue}let Z=ue(j),X=(_n=Z.toolCall)!=null?_n:{id:j,status:"pending"};X.name=M!=null?M:X.name,X.status="running",C.args!==void 0?X.args=C.args:C.parameters!==void 0&&(X.args=C.parameters),X.startedAt=(vt=X.startedAt)!=null?vt:Re((Br=C.startedAt)!=null?Br:C.timestamp),X.completedAt=void 0,X.durationMs=void 0,Z.toolCall=X,Z.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(Z.agentMetadata={executionId:(pr=Y==null?void 0:Y.executionId)!=null?pr:C.executionId,iteration:(ur=Y==null?void 0:Y.iteration)!=null?ur:C.iteration}),p(Z)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let j=(Qn=(Cr=He(C,!1))!=null?Cr:He(C,!0))!=null?Qn:`tool-${l()}`;if(je.has(j))continue;let M=ue(j),Z=(gt=M.toolCall)!=null?gt:{id:j,status:"running"};Z.startedAt=(mr=Z.startedAt)!=null?mr:Re((io=C.startedAt)!=null?io:C.timestamp);let X=(ko=(Sn=(lo=C.text)!=null?lo:C.delta)!=null?Sn:C.message)!=null?ko:"";X&&(Z.chunks=(Dr=Z.chunks)!=null?Dr:[],Z.chunks.push(String(X))),Z.status="running",M.toolCall=Z,M.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(M.agentMetadata=(Pn=M.agentMetadata)!=null?Pn:{executionId:(Ar=Y==null?void 0:Y.executionId)!=null?Ar:C.executionId,iteration:(yt=Y==null?void 0:Y.iteration)!=null?yt:C.iteration}),p(M)}else if(Ve==="tool_complete"){let j=(fn=(In=He(C,!1))!=null?In:He(C,!0))!=null?fn:`tool-${l()}`;if(je.has(j)){je.delete(j);continue}let M=ue(j),Z=(kt=M.toolCall)!=null?kt:{id:j,status:"running"};Z.status="complete",C.result!==void 0&&(Z.result=C.result),typeof C.duration=="number"&&(Z.duration=C.duration),Z.completedAt=Re((jn=C.completedAt)!=null?jn:C.timestamp);let X=(Un=C.duration)!=null?Un:C.executionTime;if(typeof X=="number")Z.durationMs=X;else{let Fe=(Wn=Z.startedAt)!=null?Wn:Date.now();Z.durationMs=Math.max(0,((Nr=Z.completedAt)!=null?Nr:Date.now())-Fe)}M.toolCall=Z,M.streaming=!1;let Y=C.agentContext;(Y||C.executionId)&&(M.agentMetadata=(Rn=M.agentMetadata)!=null?Rn:{executionId:(Sr=Y==null?void 0:Y.executionId)!=null?Sr:C.executionId,iteration:(Or=Y==null?void 0:Y.iteration)!=null?Or:C.iteration}),p(M);let Ye=V(C);Ye&&w.byCall.delete(Ye)}else if(Ve==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let j=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,M=(Wt=j!=null?j:C.toolId)!=null?Wt:`local-${l()}`,Z=ue(M),X=(hn=Z.toolCall)!=null?hn:{id:M,status:"pending"};X.name=C.toolName,X.args=C.parameters,X.status="complete",X.chunks=(qn=X.chunks)!=null?qn:[],X.startedAt=(Er=X.startedAt)!=null?Er:Re((Fr=C.startedAt)!=null?Fr:C.timestamp),X.completedAt=($r=X.completedAt)!=null?$r:X.startedAt,Z.toolCall=X,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(Hn=C.executionId)!=null?Hn:(gr=Z.agentMetadata)==null?void 0:gr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},p(Z)}else if(Ve==="text_start"){if((Zn=C.toolContext)!=null&&Zn.toolId)continue;let j=C.partId;if(j!==void 0&&x.current!==null&&j!==x.current){let M=f;M&&(M.streaming=!1,p(M),z=M,f=null,S=!0)}j!==void 0&&(x.current=j)}else if(Ve==="text_end"){if((ft=C.toolContext)!=null&&ft.toolId)continue;let j=f;j&&(j.streaming=!1,p(j),z=j,f=null,S=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let j=C.stepType,M=C.executionType;if(j==="tool"||M==="context")continue;let Z=C.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Jt=(Kt=C.id)!=null?Kt:Z.stepId)!=null?Jt:`step-${l()}`),Ze=C.partId!==void 0&&C.partId!==null?String(C.partId):"",Me=`${Z.toolId}::${Fe}`,Ge=H.get(Me);if(Ze!==""&&Ge!==void 0&&Ge!==""&&Ge!==Ze){let wt=R.get(B(Z.toolId,Fe,Ge));wt&&wt.streaming!==!1&&(wt.streaming=!1,p(wt))}Ze!==""&&H.set(Me,Ze);let Lt=$(Z.toolId,Fe,Ze,Z.executionId),en=(er=(zn=(_r=(Bn=C.text)!=null?Bn:C.delta)!=null?_r:C.content)!=null?zn:C.chunk)!=null?er:"";en&&(Lt.content+=String(en),Lt.streaming=!0,p(Lt)),C.isComplete&&(Lt.streaming=!1,p(Lt));continue}let X=C.partId;if(X!==void 0&&x.current!==null&&X!==x.current){let Fe=f;Fe&&(Fe.streaming=!1,p(Fe),z=Fe,f=null,S=!0)}X!==void 0&&(x.current=X);let Y=X!==void 0&&(Dn=J.get(X))!=null?Dn:Pe();X!==void 0&&(Y.partId||(Y.partId=X),J.set(X,Y));let Ye=(tr=(Nn=(de=(_=C.text)!=null?_:C.delta)!=null?de:C.content)!=null?Nn:C.chunk)!=null?tr:"";if(Ye){let Fe=typeof C.seq=="number"?C.seq:void 0,Ze=X!=null?X:Y.id,Me=Fe!==void 0?we(Ze,Fe,String(Ye)):((fr=se.get(Y.id))!=null?fr:"")+Ye;Y.rawContent=Me,K.has(Y.id)||K.set(Y.id,this.createStreamParser());let Ge=K.get(Y.id),Lt=Me.trim().startsWith("{")||Me.trim().startsWith("[");if(Lt&&se.set(Y.id,Me),Ge.__isPlainTextParser===!0){Y.content=Fe!==void 0?Me:Y.content+Ye,se.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y);continue}let wt=Ge.processChunk(Me);if(wt instanceof Promise)wt.then(Et=>{var dn;let tn=typeof Et=="string"?Et:(dn=Et==null?void 0:Et.text)!=null?dn:null;if(tn!==null&&tn.trim()!=="")Y.content=tn,p(Y);else if(!Lt&&!Me.trim().startsWith("<")){let bn=f,Gt=bn&&bn.id===Y.id?bn:Y;Gt.id===Y.id&&(Gt.content=Fe!==void 0?Me:Gt.content+Ye,se.delete(Gt.id),K.delete(Gt.id),Gt.rawContent=void 0,p(Gt))}}).catch(()=>{Y.content=Fe!==void 0?Me:Y.content+Ye,se.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y)});else{let Et=typeof wt=="string"?wt:(ns=wt==null?void 0:wt.text)!=null?ns:null;Et!==null&&Et.trim()!==""?(Y.content=Et,p(Y)):!Lt&&!Me.trim().startsWith("<")&&(Y.content=Fe!==void 0?Me:Y.content+Ye,se.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y))}}if(C.isComplete){let Fe=(rr=(nr=C.result)==null?void 0:nr.response)!=null?rr:Y.content;if(Fe){let Ze=se.get(Y.id),Me=Ze!=null?Ze:tt(Fe);Y.rawContent=Me;let Ge=K.get(Y.id),Lt=null,en=!1;if(Ge&&(Lt=Ge.getExtractedText(),Lt===null&&(Lt=Co(Me)),Lt===null)){let wt=Ge.processChunk(Me);wt instanceof Promise?(en=!0,wt.then(Et=>{var dn;let tn=typeof Et=="string"?Et:(dn=Et==null?void 0:Et.text)!=null?dn:null;if(tn!==null){let bn=f;bn&&bn.id===Y.id&&(bn.content=tn,bn.streaming=!1,K.delete(bn.id),se.delete(bn.id),p(bn))}})):Lt=typeof wt=="string"?wt:(or=wt==null?void 0:wt.text)!=null?or:null}if(!en){Lt!==null&&Lt.trim()!==""?Y.content=Lt:se.has(Y.id)||(Y.content=tt(Fe));let wt=K.get(Y.id);if(wt){let Et=(Tr=wt.close)==null?void 0:Tr.call(wt);Et instanceof Promise&&Et.catch(()=>{}),K.delete(Y.id)}se.delete(Y.id),Y.streaming=!1,p(Y)}}}}else if(Ve==="step_complete"){let j=C.stepType,M=C.executionType;if(j==="tool"||M==="context")continue;let Z=C.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Js=(co=C.id)!=null?co:Z.stepId)!=null?Js:"");if(Fe){let Ze=F(Z.toolId,Fe);for(let[Me,Ge]of R)Me.startsWith(Ze)&&Ge.streaming!==!1&&(Ge.streaming=!1,p(Ge));H.delete(`${Z.toolId}::${Fe}`)}continue}let X=C.stopReason;if(S){if(f!==null){let Me=f;X&&(Me.stopReason=X),K.delete(Me.id),se.delete(Me.id),Me.streaming!==!1&&(Me.streaming=!1,p(Me))}let Fe=(rs=C.result)==null?void 0:rs.response,Ze=z;Ze&&(X&&(Ze.stopReason=X),Fe!=null?$e(Ze,Fe):(K.delete(Ze.id),se.delete(Ze.id))),z=null;continue}let Y=(Gs=C.result)==null?void 0:Gs.response,Ye=Pe();if(X&&(Ye.stopReason=X),Y!=null){let Fe=K.get(Ye.id),Ze=!1,Me=!1;if(Fe){let Ge=Fe.getExtractedText(),Lt=se.get(Ye.id),en=Lt!=null?Lt:tt(Y);if(Ye.rawContent=en,Ge!==null&&Ge.trim()!=="")Ye.content=Ge,Ze=!0;else{let wt=Co(en);if(wt!==null)Ye.content=wt,Ze=!0;else{let Et=Fe.processChunk(en);if(Et instanceof Promise)Me=!0,Et.then(tn=>{var bn;let dn=typeof tn=="string"?tn:(bn=tn==null?void 0:tn.text)!=null?bn:null;if(dn!==null&&dn.trim()!==""){let Gt=f;Gt&&Gt.id===Ye.id&&(Gt.content=dn,Gt.streaming=!1,K.delete(Gt.id),se.delete(Gt.id),p(Gt))}else{let Gt=Fe.getExtractedText(),Kn=f;Kn&&Kn.id===Ye.id&&(Gt!==null&&Gt.trim()!==""?Kn.content=Gt:se.has(Kn.id)||(Kn.content=tt(Y)),Kn.streaming=!1,K.delete(Kn.id),se.delete(Kn.id),p(Kn))}});else{let tn=typeof Et=="string"?Et:(Lo=Et==null?void 0:Et.text)!=null?Lo:null;if(tn!==null&&tn.trim()!=="")Ye.content=tn,Ze=!0;else{let dn=Fe.getExtractedText();dn!==null&&dn.trim()!==""&&(Ye.content=dn,Ze=!0)}}}}}if(!Me){if(!Ye.rawContent){let Ge=se.get(Ye.id);Ye.rawContent=Ge!=null?Ge:tt(Y)}if(!Ze&&!se.has(Ye.id)&&(Ye.content=tt(Y)),Fe){let Ge=(mt=Fe.close)==null?void 0:mt.call(Fe);Ge instanceof Promise&&Ge.catch(()=>{})}K.delete(Ye.id),se.delete(Ye.id),Ye.streaming=!1,p(Ye)}}else K.delete(Ye.id),se.delete(Ye.id),Ye.streaming=!1,p(Ye)}else if(Ve==="flow_complete"){let j=(os=C.result)==null?void 0:os.response;if(S){if(f!==null){let M=f;K.delete(M.id),se.delete(M.id),M.streaming!==!1&&(M.streaming=!1,p(M))}}else if(j!=null){let M=Pe(),Z=se.get(M.id),X=Z!=null?Z:tt(j);M.rawContent=X;let Y=tt(j),Ye=K.get(M.id);if(Ye){let Me=Co(X);if(Me!==null)Y=Me;else{let Ge=Ye.processChunk(X);Ge instanceof Promise&&Ge.then(en=>{var Et;let wt=typeof en=="string"?en:(Et=en==null?void 0:en.text)!=null?Et:null;wt!==null&&(M.content=wt,M.streaming=!1,p(M))});let Lt=Ye.getExtractedText();Lt!==null&&(Y=Lt)}}K.delete(M.id),se.delete(M.id);let Fe=Y!==M.content,Ze=M.streaming!==!1;Fe&&(M.content=Y),M.streaming=!1,(Fe||Ze)&&p(M)}else if(f!==null){let M=f;K.delete(M.id),se.delete(M.id),M.streaming!==!1&&(M.streaming=!1,p(M))}t({type:"status",status:"idle"})}else if(Ve==="agent_start")re={executionId:C.executionId,agentId:(Vn=C.agentId)!=null?Vn:"virtual",agentName:(En=C.agentName)!=null?En:"",status:"running",currentIteration:0,maxTurns:(Xs=C.maxTurns)!=null?Xs:1,startedAt:Re(C.startedAt)};else if(Ve==="agent_iteration_start"){if(re&&(re.currentIteration=C.iteration),Nt==="separate"&&C.iteration>1){let j=f;j&&(j.streaming=!1,p(j),sn.set(C.iteration-1,j),f=null)}}else if(Ve==="agent_turn_start")m=null;else if(Ve==="agent_turn_delta"){if(C.contentType==="text"){let j=Pe();j.content+=(Ys=C.delta)!=null?Ys:"",j.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:re==null?void 0:re.agentName},m=j,p(j)}else if(C.contentType==="thinking"){let j=(Po=C.turnId)!=null?Po:`agent-think-${C.iteration}`,M=ce(j);M.reasoning=(Mr=M.reasoning)!=null?Mr:{id:j,status:"streaming",chunks:[]},M.reasoning.chunks.push((Qs=C.delta)!=null?Qs:""),M.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(M)}else if(C.contentType==="tool_input"){let j=(po=C.toolCallId)!=null?po:w.lastId;if(j){let M=k.get(j);M!=null&&M.toolCall&&(M.toolCall.chunks=(ss=M.toolCall.chunks)!=null?ss:[],M.toolCall.chunks.push((kr=C.delta)!=null?kr:""),p(M))}}}else if(Ve==="agent_turn_complete"){let j=C.turnId;if(j){let X=A.get(j);if(X!=null&&X.reasoning){X.reasoning.status="complete",X.reasoning.completedAt=Re(C.completedAt);let Y=(as=X.reasoning.startedAt)!=null?as:Date.now();X.reasoning.durationMs=Math.max(0,((jr=X.reasoning.completedAt)!=null?jr:Date.now())-Y),X.streaming=!1,p(X)}}let M=C.stopReason,Z=f!=null?f:m;if(M&&Z!==null){let X=C.turnId;(!X||((Ur=Z.agentMetadata)==null?void 0:Ur.turnId)===X)&&(Z.stopReason=M,p(Z))}}else if(Ve==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let j=(Zs=C.toolCallId)!=null?Zs:`agent-tool-${l()}`;Ee(V(C),j);let M=ue(j),Z=(ea=M.toolCall)!=null?ea:{id:j,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(uo=(fi=C.toolName)!=null?fi:C.name)!=null?uo:Z.name,Z.status="running",C.parameters!==void 0&&(Z.args=C.parameters),Z.startedAt=Re((qr=C.startedAt)!=null?qr:C.timestamp),M.toolCall=Z,M.streaming=!0,M.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(M)}else if(Ve==="agent_tool_delta"){let j=(ta=C.toolCallId)!=null?ta:w.lastId;if(j){let M=(is=k.get(j))!=null?is:ue(j);M.toolCall&&(M.toolCall.chunks=(zr=M.toolCall.chunks)!=null?zr:[],M.toolCall.chunks.push((na=C.delta)!=null?na:""),M.toolCall.status="running",M.streaming=!0,p(M))}}else if(Ve==="agent_tool_complete"){let j=(ls=C.toolCallId)!=null?ls:w.lastId;if(j){let M=(Vr=k.get(j))!=null?Vr:ue(j);if(M.toolCall){M.toolCall.status="complete",C.result!==void 0&&(M.toolCall.result=C.result),typeof C.executionTime=="number"&&(M.toolCall.durationMs=C.executionTime),M.toolCall.completedAt=Re((cs=C.completedAt)!=null?cs:C.timestamp),M.streaming=!1,p(M);let Z=V(C);Z&&w.byCall.delete(Z)}}}else if(Ve==="agent_media"){let j=Array.isArray(C.media)?C.media:[],M=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let X=Z,Y=typeof X.type=="string"?X.type:void 0,Ye=typeof X.mediaType=="string"?X.mediaType.toLowerCase():"",Fe=null,Ze="";if(Y==="media"){let Me=typeof X.data=="string"?X.data:void 0;if(!Me)continue;Ze=Ye.length>0?Ye:"application/octet-stream",Fe=`data:${Ze};base64,${Me}`}else if(Y==="image-url"){let Me=typeof X.url=="string"?X.url:void 0;if(!Me)continue;Ze=Ye,Fe=Me}else if(Y==="file-url"){let Me=typeof X.url=="string"?X.url:void 0;if(!Me)continue;Ze=Ye,Fe=Me}else continue;if(Fe)if(Y==="image-url"||Ze.startsWith("image/"))M.push({type:"image",image:Fe,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))M.push({type:"audio",audio:Fe,mimeType:Ze});else if(Ze.startsWith("video/"))M.push({type:"video",video:Fe,mimeType:Ze});else{let Me=Ze||"application/octet-stream";M.push({type:"file",data:Fe,mimeType:Me,filename:Nm(Me)})}}if(M.length>0){let Z=l(),X=C.toolCallId,Ye={id:`agent-media-${typeof X=="string"&&X.length>0?`${X}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:M,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(Ye);let Fe=f;Fe&&(Fe.streaming=!1,p(Fe)),f=null,v.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let j=`agent-reflection-${C.executionId}-${C.iteration}`,M={id:j,role:"assistant",content:(ra=C.reflection)!=null?ra:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Lr=C.reflection)!=null?Lr:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(M)}else if(Ve==="agent_complete"){re&&(re.status=C.success?"complete":"error",re.completedAt=Re(C.completedAt),re.stopReason=C.stopReason);let j=f;j&&(j.streaming=!1,p(j)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let j=typeof C.error=="string"?C.error:(Kr=(oa=C.error)==null?void 0:oa.message)!=null?Kr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):t({type:"error",error:new Error(j)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let j=(Rt=C.approvalId)!=null?Rt:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Io=re==null?void 0:re.agentId)!=null?Io:"virtual",executionId:(ds=(Wo=C.executionId)!=null?Wo:re==null?void 0:re.executionId)!=null?ds:"",toolName:(hr=C.toolName)!=null?hr:"",toolType:C.toolType,description:(ps=C.description)!=null?ps:`Execute ${(sa=C.toolName)!=null?sa:"tool"}`,parameters:C.parameters}};p(M)}else if(Ve==="step_await"&&C.awaitReason==="approval_required"){let j=(us=C.approvalId)!=null?us:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(aa=re==null?void 0:re.agentId)!=null?aa:"virtual",executionId:(Ho=(Ro=C.executionId)!=null?Ro:re==null?void 0:re.executionId)!=null?Ho:"",toolName:(mo=C.toolName)!=null?mo:"",toolType:C.toolType,description:(la=C.description)!=null?la:`Execute ${(ia=C.toolName)!=null?ia:"tool"}`,parameters:C.parameters}};p(M)}else if(Ve==="agent_approval_complete"){let j=C.approvalId;if(j){let Z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(ms=C.decision)!=null?ms:"approved",agentId:(gs=re==null?void 0:re.agentId)!=null?gs:"virtual",executionId:(hs=(fs=C.executionId)!=null?fs:re==null?void 0:re.executionId)!=null?hs:"",toolName:(yn=C.toolName)!=null?yn:"",description:(On=C.description)!=null?On:"",resolvedAt:Date.now()}};p(Z)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let j=C.artifactType,M=String(C.id),Z=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:M,artifactType:j,title:Z,component:typeof C.component=="string"?C.component:void 0}),G.set(M,{markdown:"",title:Z}),!xe.has(M)){xe.add(M);let X={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:M,title:Z,artifactType:j,status:"streaming"}})};te.set(M,X),p(X)}}else if(Ve==="artifact_delta"){let j=String(C.id),M=typeof C.delta=="string"?C.delta:String((Pr=C.delta)!=null?Pr:"");t({type:"artifact_delta",id:j,artDelta:M});let Z=G.get(j);Z&&(Z.markdown+=M)}else if(Ve==="artifact_update"){let j=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:j,component:typeof C.component=="string"?C.component:void 0})}else if(Ve==="artifact_complete"){let j=String(C.id);t({type:"artifact_complete",id:j});let M=te.get(j);if(M){M.streaming=!1;try{let Z=JSON.parse((rt=M.rawContent)!=null?rt:"{}");if(Z.props){Z.props.status="complete";let X=G.get(j);X!=null&&X.markdown&&(Z.props.markdown=X.markdown)}M.rawContent=JSON.stringify(Z)}catch{}G.delete(j),p(M),te.delete(j)}}}else if(Ve==="transcript_insert"){let j=C.message;if(!j||typeof j!="object")continue;let M=String((ys=j.id)!=null?ys:`msg-${l()}`),Z=j.role,Y={id:M,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(p(Y),Y.rawContent)try{let Ye=JSON.parse(Y.rawContent),Fe=(go=Ye==null?void 0:Ye.props)==null?void 0:go.artifactId;typeof Fe=="string"&&xe.add(Fe)}catch{}f=null,v.current=null,K.delete(M),se.delete(M)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let j=null;if(C.error instanceof Error)j=C.error;else if(Ve==="dispatch_error"){let M=(sr=C.message)!=null?sr:C.error;M!=null&&M!==""&&(j=new Error(String(M)))}else if(Ve==="step_error"||Ve==="flow_error"){let M=C.error;typeof M=="string"&&M!==""?j=new Error(M):M!=null&&typeof M=="object"&&"message"in M&&(j=new Error(String((ca=M.message)!=null?ca:M)))}else Ve==="error"&&C.error!=null&&C.error!==""&&(j=new Error(String(C.error)));if(j){t({type:"error",error:j});let M=f;M&&M.streaming&&(M.streaming=!1,p(M)),t({type:"status",status:"idle"})}}}}}ne.length=0};;){let{done:U,value:Ae}=await s.read();if(U)break;a+=o.decode(Ae,{stream:!0});let Be=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Ao=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ci=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ai=()=>{var t;let e=Um();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Si=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=Ep(n,Tp|Mp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ca(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ca(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},qm=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ca(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ca(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=Ep(o,Tp|Mp),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},Ei=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ta=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var zm="https://api.runtype.com/v1/dispatch",Ma="https://api.runtype.com";function Vm(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ti=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Km(e){switch(e){case"json":return Si;case"regex-json":return Ai;case"xml":return Ei;default:return Ci}}var Pp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Jm(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Pp(n);if(!Pp(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Ao(e);return Ao(t)!==null&&a===null?t:e}var qo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:zm,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Km(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new Ts(t.webmcp):null}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ma}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ma}/v1/client/feedback`}async sendFeedback(t){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:m}),m}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Ti).map(m=>{var v,x,E;return{id:m.id,role:m.role,content:(E=(x=(v=m.contentParts)!=null?v:m.llmContent)!=null?x:m.rawContent)!=null?E:m.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:x}),x}if(f.status===429){let x=new Error(m.hint||"Message limit reached for this session.");throw n({type:"error",error:x}),x}let v=new Error(m.error||"Failed to send message");throw n({type:"error",error:v}),v}if(!f.body){let m=new Error("No response body received");throw n({type:"error",error:m}),m}n({type:"status",status:"connected"});try{await this.streamResponse(f.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ma}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,u;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ma}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Ti).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(t){var o;let r={messages:t.slice().filter(Ti).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:t,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Dt,ln,Hn,Xn;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=H=>{let oe=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,Be=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Xe=H.tools?H.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...H,reasoning:oe,toolCall:Be,tools:Xe}},p=H=>{n({type:"message",message:u(H)})},f=null,m=null,v={current:null},x={current:null},E=!1,A=new Map,I=new Map,P=new Map,N=new Map,L={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},W=(H,oe,Be="")=>`${H}::${oe}::${Be}`,F=(H,oe)=>`${H}::${oe}::`,_=(H,oe,Be,Xe)=>{let Fe=W(H,oe,Be),_e=P.get(Fe);if(_e)return _e;let rt=Be?`-${Be}`:"",At={id:`nested-${H}-${oe}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:Xe,parentToolId:H,parentStepId:oe}};return P.set(Fe,At),p(At),At},B=H=>{if(H==null)return null;try{return String(H)}catch{return null}},j=H=>{var oe,Be,Xe,Fe,_e;return B((_e=(Fe=(Xe=(Be=(oe=H.stepId)!=null?oe:H.step_id)!=null?Be:H.step)!=null?Xe:H.parentId)!=null?Fe:H.flowStepId)!=null?_e:H.flow_step_id)},q=H=>{var oe,Be,Xe,Fe,_e,rt,At;return B((At=(rt=(_e=(Fe=(Xe=(Be=(oe=H.callId)!=null?oe:H.call_id)!=null?Be:H.requestId)!=null?Xe:H.request_id)!=null?Fe:H.toolCallId)!=null?_e:H.tool_call_id)!=null?rt:H.stepId)!=null?At:H.step_id)},re=r,Ie=!1,Re=()=>{if(f)return f;let H;return!Ie&&re?(H=re,Ie=!0):re&&x.current?H=`${re}_${x.current}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:H,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Ne=(H,oe)=>{L.lastId=oe,H&&L.byStep.set(H,oe)},ce=(H,oe)=>{var _e;let Be=(_e=H.reasoningId)!=null?_e:H.id,Xe=j(H);if(Be){let rt=String(Be);return Ne(Xe,rt),rt}if(Xe){let rt=L.byStep.get(Xe);if(rt)return L.lastId=rt,rt}if(L.lastId&&!oe)return L.lastId;if(!oe)return null;let Fe=`reason-${l()}`;return Ne(Xe,Fe),Fe},ve=H=>{let oe=A.get(H);if(oe)return oe;let Be={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:H,status:"streaming",chunks:[]}};return A.set(H,Be),p(Be),Be},Me=(H,oe)=>{w.lastId=oe,H&&w.byCall.set(H,oe)},Le=new Set,ne=new Map,ke=new Set,V=new Map,pe=H=>{if(!H)return!1;let oe=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return oe==="emit_artifact_markdown"||oe==="emit_artifact_component"},fe=(H,oe)=>{var _e;let Be=(_e=H.toolId)!=null?_e:H.id,Xe=q(H);if(Be){let rt=String(Be);return Me(Xe,rt),rt}if(Xe){let rt=w.byCall.get(Xe);if(rt)return w.lastId=rt,rt}if(w.lastId&&!oe)return w.lastId;if(!oe)return null;let Fe=`tool-${l()}`;return Me(Xe,Fe),Fe},me=H=>{let oe=I.get(H);if(oe)return oe;let Be={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:H,status:"pending"}};return I.set(H,Be),p(Be),Be},ue=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let oe=Number(H);if(!Number.isNaN(oe)&&Number.isFinite(oe))return oe;let Be=Date.parse(H);if(!Number.isNaN(Be))return Be}return Date.now()},Ge=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},z=new Map,te=new Map,We=new Map,ge=new Map,ie=null,ae=(H,oe,Be)=>{var At;let Xe=We.get(H);Xe||(Xe=[],We.set(H,Xe));let Fe=0,_e=Xe.length;for(;Fe<_e;){let Ft=Fe+_e>>>1;Xe[Ft].seq<oe?Fe=Ft+1:_e=Ft}((At=Xe[Fe])==null?void 0:At.seq)===oe?Xe[Fe]={seq:oe,text:Be}:Xe.splice(Fe,0,{seq:oe,text:Be});let rt="";for(let Ft=0;Ft<Xe.length;Ft++)rt+=Xe[Ft].text;return rt},Qe=(H,oe)=>{let Be=Ge(oe),Xe=te.get(H.id),Fe=Jm(Xe,Be);H.rawContent=Fe;let _e=z.get(H.id),rt=gt=>{var Ut;let nt=(Ut=H.content)!=null?Ut:"";gt.trim()!==""&&(nt.trim().length===0||gt.startsWith(nt)||gt.trimStart().startsWith(nt.trim()))&&(H.content=gt)},At=()=>{var gt;if(_e){let nt=(gt=_e.close)==null?void 0:gt.call(_e);nt instanceof Promise&&nt.catch(()=>{})}z.delete(H.id),te.delete(H.id),H.streaming=!1,p(H)};if(!_e){rt(Be),At();return}let Ft=Ao(Fe);if(Ft!==null&&Ft.trim()!==""){rt(Ft),At();return}let Kt=gt=>{var se;let nt=typeof gt=="string"?gt:(se=gt==null?void 0:gt.text)!=null?se:null;if(nt!==null&&nt.trim()!=="")return nt;let Ut=_e.getExtractedText();return Ut!==null&&Ut.trim()!==""?Ut:Be},K;try{K=_e.processChunk(Fe)}catch{rt(Be),At();return}if(K instanceof Promise){K.then(gt=>{rt(Kt(gt)),At()}).catch(()=>{rt(Be),At()});return}rt(Kt(K)),At()},Ce=[],de=!1,X,$e=()=>{de||(de=!0,queueMicrotask(()=>{de=!1,X()}))},Ct=new Ta((H,oe)=>{Ce.push({payloadType:H,payload:oe}),$e()}),G=null,Oe=new Map,Mn=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(X=()=>{var H,oe,Be,Xe,Fe,_e,rt,At,Ft,Kt,K,gt,nt,Ut,se,ye,wt,_t,Zt,yn,Tt,St,ht,bt,qt,et,Bn,Qn,bn,Dn,ut,xr,Nn,co,kn,Po,Fr,Tr,xt,On,Fn,xn,Pt,Yn,Zn,_n,_r,Mr,$r,$n,Wt,vn,er,jr,kr,Ur,vr,jn,lr,ft,Jt,Gt,Un,qr,tr,cr,qn,S,zn,dr,Lr,wr,ss,pr,ur,mr,Pr,po,Ys,as,Zs,Io,mt,is,nr,Ln,ea,ta,Wo,Ir,na,uo,ls,Wr,cs,zr,Vr,ra,oa,xi,mo,Kr,sa,ds,Jr,aa,ps,Gr,us,ia,Rr,la,Xr,Rt,Ro,Ho,ms,Cr,ca,gs,fs,da,Bo,Do,go,pa,ua,hs,ys,bs,xs,wn,Vn,Hr,ot,vs,fo,gr;for(let No=0;No<Ce.length;No++){let Ue=Ce[No].payloadType,C=Ce[No].payload;if(Ue==="reason_start"){let $=(H=ce(C,!0))!=null?H:`reason-${l()}`,M=ve($);M.reasoning=(oe=M.reasoning)!=null?oe:{id:$,status:"streaming",chunks:[]},M.reasoning.startedAt=(Xe=M.reasoning.startedAt)!=null?Xe:ue((Be=C.startedAt)!=null?Be:C.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",p(M)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let $=(_e=(Fe=ce(C,!1))!=null?Fe:ce(C,!0))!=null?_e:`reason-${l()}`,M=ve($);M.reasoning=(rt=M.reasoning)!=null?rt:{id:$,status:"streaming",chunks:[]},M.reasoning.startedAt=(Ft=M.reasoning.startedAt)!=null?Ft:ue((At=C.startedAt)!=null?At:C.timestamp);let Y=(gt=(K=(Kt=C.reasoningText)!=null?Kt:C.text)!=null?K:C.delta)!=null?gt:"";if(Y&&C.hidden!==!0){let Z=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(Z!==void 0){let J=ae($,Z,String(Y));M.reasoning.chunks=[J]}else M.reasoning.chunks.push(String(Y))}if(M.reasoning.status=C.done?"complete":"streaming",C.done){M.reasoning.completedAt=ue((nt=C.completedAt)!=null?nt:C.timestamp);let Z=(Ut=M.reasoning.startedAt)!=null?Ut:Date.now();M.reasoning.durationMs=Math.max(0,((se=M.reasoning.completedAt)!=null?se:Date.now())-Z)}M.streaming=M.reasoning.status!=="complete",p(M)}else if(Ue==="reason_complete"){let $=(wt=(ye=ce(C,!1))!=null?ye:ce(C,!0))!=null?wt:`reason-${l()}`,M=A.get($);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=ue((_t=C.completedAt)!=null?_t:C.timestamp);let Z=(Zt=M.reasoning.startedAt)!=null?Zt:Date.now();M.reasoning.durationMs=Math.max(0,((yn=M.reasoning.completedAt)!=null?yn:Date.now())-Z),M.streaming=!1,p(M)}let Y=j(C);Y&&L.byStep.delete(Y)}else if(Ue==="tool_start"){let $=(Tt=fe(C,!0))!=null?Tt:`tool-${l()}`,M=(St=C.toolName)!=null?St:C.name;if(pe(M)){Le.add($);continue}let Y=me($),Z=(ht=Y.toolCall)!=null?ht:{id:$,status:"pending"};Z.name=M!=null?M:Z.name,Z.status="running",C.args!==void 0?Z.args=C.args:C.parameters!==void 0&&(Z.args=C.parameters),Z.startedAt=(qt=Z.startedAt)!=null?qt:ue((bt=C.startedAt)!=null?bt:C.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,Y.toolCall=Z,Y.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(Y.agentMetadata={executionId:(et=J==null?void 0:J.executionId)!=null?et:C.executionId,iteration:(Bn=J==null?void 0:J.iteration)!=null?Bn:C.iteration}),p(Y)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let $=(bn=(Qn=fe(C,!1))!=null?Qn:fe(C,!0))!=null?bn:`tool-${l()}`;if(Le.has($))continue;let M=me($),Y=(Dn=M.toolCall)!=null?Dn:{id:$,status:"running"};Y.startedAt=(xr=Y.startedAt)!=null?xr:ue((ut=C.startedAt)!=null?ut:C.timestamp);let Z=(kn=(co=(Nn=C.text)!=null?Nn:C.delta)!=null?co:C.message)!=null?kn:"";Z&&(Y.chunks=(Po=Y.chunks)!=null?Po:[],Y.chunks.push(String(Z))),Y.status="running",M.toolCall=Y,M.streaming=!0;let J=C.agentContext;(J||C.executionId)&&(M.agentMetadata=(xt=M.agentMetadata)!=null?xt:{executionId:(Fr=J==null?void 0:J.executionId)!=null?Fr:C.executionId,iteration:(Tr=J==null?void 0:J.iteration)!=null?Tr:C.iteration}),p(M)}else if(Ue==="tool_complete"){let $=(Fn=(On=fe(C,!1))!=null?On:fe(C,!0))!=null?Fn:`tool-${l()}`;if(Le.has($)){Le.delete($);continue}let M=me($),Y=(xn=M.toolCall)!=null?xn:{id:$,status:"running"};Y.status="complete",C.result!==void 0&&(Y.result=C.result),typeof C.duration=="number"&&(Y.duration=C.duration),Y.completedAt=ue((Pt=C.completedAt)!=null?Pt:C.timestamp);let Z=(Yn=C.duration)!=null?Yn:C.executionTime;if(typeof Z=="number")Y.durationMs=Z;else{let De=(Zn=Y.startedAt)!=null?Zn:Date.now();Y.durationMs=Math.max(0,((_n=Y.completedAt)!=null?_n:Date.now())-De)}M.toolCall=Y,M.streaming=!1;let J=C.agentContext;(J||C.executionId)&&(M.agentMetadata=($r=M.agentMetadata)!=null?$r:{executionId:(_r=J==null?void 0:J.executionId)!=null?_r:C.executionId,iteration:(Mr=J==null?void 0:J.iteration)!=null?Mr:C.iteration}),p(M);let qe=q(C);qe&&w.byCall.delete(qe)}else if(Ue==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,M=($n=$!=null?$:C.toolId)!=null?$n:`local-${l()}`,Y=me(M),Z=(Wt=Y.toolCall)!=null?Wt:{id:M,status:"pending"};Z.name=C.toolName,Z.args=C.parameters,Z.status="complete",Z.chunks=(vn=Z.chunks)!=null?vn:[],Z.startedAt=(jr=Z.startedAt)!=null?jr:ue((er=C.startedAt)!=null?er:C.timestamp),Z.completedAt=(kr=Z.completedAt)!=null?kr:Z.startedAt,Y.toolCall=Z,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(vr=C.executionId)!=null?vr:(Ur=Y.agentMetadata)==null?void 0:Ur.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},p(Y)}else if(Ue==="text_start"){if((jn=C.toolContext)!=null&&jn.toolId)continue;let $=C.partId;if($!==void 0&&x.current!==null&&$!==x.current){let M=f;M&&(M.streaming=!1,p(M),ie=M,f=null,E=!0)}$!==void 0&&(x.current=$)}else if(Ue==="text_end"){if((lr=C.toolContext)!=null&&lr.toolId)continue;let $=f;$&&($.streaming=!1,p($),ie=$,f=null,E=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let $=C.stepType,M=C.executionType;if($==="tool"||M==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let De=String((Jt=(ft=C.id)!=null?ft:Y.stepId)!=null?Jt:`step-${l()}`),at=C.partId!==void 0&&C.partId!==null?String(C.partId):"",Ve=`${Y.toolId}::${De}`,Ke=N.get(Ve);if(at!==""&&Ke!==void 0&&Ke!==""&&Ke!==at){let Et=P.get(W(Y.toolId,De,Ke));Et&&Et.streaming!==!1&&(Et.streaming=!1,p(Et))}at!==""&&N.set(Ve,at);let Ye=_(Y.toolId,De,at,Y.executionId),Xt=(tr=(qr=(Un=(Gt=C.text)!=null?Gt:C.delta)!=null?Un:C.content)!=null?qr:C.chunk)!=null?tr:"";Xt&&(Ye.content+=String(Xt),Ye.streaming=!0,p(Ye)),C.isComplete&&(Ye.streaming=!1,p(Ye));continue}let Z=C.partId;if(Z!==void 0&&x.current!==null&&Z!==x.current){let De=f;De&&(De.streaming=!1,p(De),ie=De,f=null,E=!0)}Z!==void 0&&(x.current=Z);let J=Z!==void 0&&(cr=ge.get(Z))!=null?cr:Re();Z!==void 0&&(J.partId||(J.partId=Z),ge.set(Z,J));let qe=(dr=(zn=(S=(qn=C.text)!=null?qn:C.delta)!=null?S:C.content)!=null?zn:C.chunk)!=null?dr:"";if(qe){let De=typeof C.seq=="number"?C.seq:void 0,at=Z!=null?Z:J.id,Ve=De!==void 0?ae(at,De,String(qe)):((Lr=te.get(J.id))!=null?Lr:"")+qe;J.rawContent=Ve,z.has(J.id)||z.set(J.id,this.createStreamParser());let Ke=z.get(J.id),Ye=Ve.trim().startsWith("{")||Ve.trim().startsWith("[");if(Ye&&te.set(J.id,Ve),Ke.__isPlainTextParser===!0){J.content=De!==void 0?Ve:J.content+qe,te.delete(J.id),z.delete(J.id),J.rawContent=void 0,p(J);continue}let Et=Ke.processChunk(Ve);if(Et instanceof Promise)Et.then(kt=>{var un;let rn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(rn!==null&&rn.trim()!=="")J.content=rn,p(J);else if(!Ye&&!Ve.trim().startsWith("<")){let cn=f,en=cn&&cn.id===J.id?cn:J;en.id===J.id&&(en.content=De!==void 0?Ve:en.content+qe,te.delete(en.id),z.delete(en.id),en.rawContent=void 0,p(en))}}).catch(()=>{J.content=De!==void 0?Ve:J.content+qe,te.delete(J.id),z.delete(J.id),J.rawContent=void 0,p(J)});else{let kt=typeof Et=="string"?Et:(wr=Et==null?void 0:Et.text)!=null?wr:null;kt!==null&&kt.trim()!==""?(J.content=kt,p(J)):!Ye&&!Ve.trim().startsWith("<")&&(J.content=De!==void 0?Ve:J.content+qe,te.delete(J.id),z.delete(J.id),J.rawContent=void 0,p(J))}}if(C.isComplete){let De=(pr=(ss=C.result)==null?void 0:ss.response)!=null?pr:J.content;if(De){let at=te.get(J.id),Ve=at!=null?at:Ge(De);J.rawContent=Ve;let Ke=z.get(J.id),Ye=null,Xt=!1;if(Ke&&(Ye=Ke.getExtractedText(),Ye===null&&(Ye=Ao(Ve)),Ye===null)){let Et=Ke.processChunk(Ve);Et instanceof Promise?(Xt=!0,Et.then(kt=>{var un;let rn=typeof kt=="string"?kt:(un=kt==null?void 0:kt.text)!=null?un:null;if(rn!==null){let cn=f;cn&&cn.id===J.id&&(cn.content=rn,cn.streaming=!1,z.delete(cn.id),te.delete(cn.id),p(cn))}})):Ye=typeof Et=="string"?Et:(ur=Et==null?void 0:Et.text)!=null?ur:null}if(!Xt){Ye!==null&&Ye.trim()!==""?J.content=Ye:te.has(J.id)||(J.content=Ge(De));let Et=z.get(J.id);if(Et){let kt=(mr=Et.close)==null?void 0:mr.call(Et);kt instanceof Promise&&kt.catch(()=>{}),z.delete(J.id)}te.delete(J.id),J.streaming=!1,p(J)}}}}else if(Ue==="step_complete"){let $=C.stepType,M=C.executionType;if($==="tool"||M==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let De=String((po=(Pr=C.id)!=null?Pr:Y.stepId)!=null?po:"");if(De){let at=F(Y.toolId,De);for(let[Ve,Ke]of P)Ve.startsWith(at)&&Ke.streaming!==!1&&(Ke.streaming=!1,p(Ke));N.delete(`${Y.toolId}::${De}`)}continue}let Z=C.stopReason;if(E){if(f!==null){let Ve=f;Z&&(Ve.stopReason=Z),z.delete(Ve.id),te.delete(Ve.id),Ve.streaming!==!1&&(Ve.streaming=!1,p(Ve))}let De=(Ys=C.result)==null?void 0:Ys.response,at=ie;at&&(Z&&(at.stopReason=Z),De!=null?Qe(at,De):(z.delete(at.id),te.delete(at.id))),ie=null;continue}let J=(as=C.result)==null?void 0:as.response,qe=Re();if(Z&&(qe.stopReason=Z),J!=null){let De=z.get(qe.id),at=!1,Ve=!1;if(De){let Ke=De.getExtractedText(),Ye=te.get(qe.id),Xt=Ye!=null?Ye:Ge(J);if(qe.rawContent=Xt,Ke!==null&&Ke.trim()!=="")qe.content=Ke,at=!0;else{let Et=Ao(Xt);if(Et!==null)qe.content=Et,at=!0;else{let kt=De.processChunk(Xt);if(kt instanceof Promise)Ve=!0,kt.then(rn=>{var cn;let un=typeof rn=="string"?rn:(cn=rn==null?void 0:rn.text)!=null?cn:null;if(un!==null&&un.trim()!==""){let en=f;en&&en.id===qe.id&&(en.content=un,en.streaming=!1,z.delete(en.id),te.delete(en.id),p(en))}else{let en=De.getExtractedText(),rr=f;rr&&rr.id===qe.id&&(en!==null&&en.trim()!==""?rr.content=en:te.has(rr.id)||(rr.content=Ge(J)),rr.streaming=!1,z.delete(rr.id),te.delete(rr.id),p(rr))}});else{let rn=typeof kt=="string"?kt:(Zs=kt==null?void 0:kt.text)!=null?Zs:null;if(rn!==null&&rn.trim()!=="")qe.content=rn,at=!0;else{let un=De.getExtractedText();un!==null&&un.trim()!==""&&(qe.content=un,at=!0)}}}}}if(!Ve){if(!qe.rawContent){let Ke=te.get(qe.id);qe.rawContent=Ke!=null?Ke:Ge(J)}if(!at&&!te.has(qe.id)&&(qe.content=Ge(J)),De){let Ke=(Io=De.close)==null?void 0:Io.call(De);Ke instanceof Promise&&Ke.catch(()=>{})}z.delete(qe.id),te.delete(qe.id),qe.streaming=!1,p(qe)}}else z.delete(qe.id),te.delete(qe.id),qe.streaming=!1,p(qe)}else if(Ue==="flow_complete"){let $=(mt=C.result)==null?void 0:mt.response;if(E){if(f!==null){let M=f;z.delete(M.id),te.delete(M.id),M.streaming!==!1&&(M.streaming=!1,p(M))}}else if($!=null){let M=Re(),Y=te.get(M.id),Z=Y!=null?Y:Ge($);M.rawContent=Z;let J=Ge($),qe=z.get(M.id);if(qe){let Ve=Ao(Z);if(Ve!==null)J=Ve;else{let Ke=qe.processChunk(Z);Ke instanceof Promise&&Ke.then(Xt=>{var kt;let Et=typeof Xt=="string"?Xt:(kt=Xt==null?void 0:Xt.text)!=null?kt:null;Et!==null&&(M.content=Et,M.streaming=!1,p(M))});let Ye=qe.getExtractedText();Ye!==null&&(J=Ye)}}z.delete(M.id),te.delete(M.id);let De=J!==M.content,at=M.streaming!==!1;De&&(M.content=J),M.streaming=!1,(De||at)&&p(M)}else if(f!==null){let M=f;z.delete(M.id),te.delete(M.id),M.streaming!==!1&&(M.streaming=!1,p(M))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")G={executionId:C.executionId,agentId:(is=C.agentId)!=null?is:"virtual",agentName:(nr=C.agentName)!=null?nr:"",status:"running",currentIteration:0,maxTurns:(Ln=C.maxTurns)!=null?Ln:1,startedAt:ue(C.startedAt)};else if(Ue==="agent_iteration_start"){if(G&&(G.currentIteration=C.iteration),Mn==="separate"&&C.iteration>1){let $=f;$&&($.streaming=!1,p($),Oe.set(C.iteration-1,$),f=null)}}else if(Ue==="agent_turn_start")m=null;else if(Ue==="agent_turn_delta"){if(C.contentType==="text"){let $=Re();$.content+=(ea=C.delta)!=null?ea:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:G==null?void 0:G.agentName},m=$,p($)}else if(C.contentType==="thinking"){let $=(ta=C.turnId)!=null?ta:`agent-think-${C.iteration}`,M=ve($);M.reasoning=(Wo=M.reasoning)!=null?Wo:{id:$,status:"streaming",chunks:[]},M.reasoning.chunks.push((Ir=C.delta)!=null?Ir:""),M.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(M)}else if(C.contentType==="tool_input"){let $=(na=C.toolCallId)!=null?na:w.lastId;if($){let M=I.get($);M!=null&&M.toolCall&&(M.toolCall.chunks=(uo=M.toolCall.chunks)!=null?uo:[],M.toolCall.chunks.push((ls=C.delta)!=null?ls:""),p(M))}}}else if(Ue==="agent_turn_complete"){let $=C.turnId;if($){let Z=A.get($);if(Z!=null&&Z.reasoning){Z.reasoning.status="complete",Z.reasoning.completedAt=ue(C.completedAt);let J=(Wr=Z.reasoning.startedAt)!=null?Wr:Date.now();Z.reasoning.durationMs=Math.max(0,((cs=Z.reasoning.completedAt)!=null?cs:Date.now())-J),Z.streaming=!1,p(Z)}}let M=C.stopReason,Y=f!=null?f:m;if(M&&Y!==null){let Z=C.turnId;(!Z||((zr=Y.agentMetadata)==null?void 0:zr.turnId)===Z)&&(Y.stopReason=M,p(Y))}}else if(Ue==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let $=(Vr=C.toolCallId)!=null?Vr:`agent-tool-${l()}`;Me(q(C),$);let M=me($),Y=(ra=M.toolCall)!=null?ra:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(xi=(oa=C.toolName)!=null?oa:C.name)!=null?xi:Y.name,Y.status="running",C.parameters!==void 0&&(Y.args=C.parameters),Y.startedAt=ue((mo=C.startedAt)!=null?mo:C.timestamp),M.toolCall=Y,M.streaming=!0,M.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(M)}else if(Ue==="agent_tool_delta"){let $=(Kr=C.toolCallId)!=null?Kr:w.lastId;if($){let M=(sa=I.get($))!=null?sa:me($);M.toolCall&&(M.toolCall.chunks=(ds=M.toolCall.chunks)!=null?ds:[],M.toolCall.chunks.push((Jr=C.delta)!=null?Jr:""),M.toolCall.status="running",M.streaming=!0,p(M))}}else if(Ue==="agent_tool_complete"){let $=(aa=C.toolCallId)!=null?aa:w.lastId;if($){let M=(ps=I.get($))!=null?ps:me($);if(M.toolCall){M.toolCall.status="complete",C.result!==void 0&&(M.toolCall.result=C.result),typeof C.executionTime=="number"&&(M.toolCall.durationMs=C.executionTime),M.toolCall.completedAt=ue((Gr=C.completedAt)!=null?Gr:C.timestamp),M.streaming=!1,p(M);let Y=q(C);Y&&w.byCall.delete(Y)}}}else if(Ue==="agent_media"){let $=Array.isArray(C.media)?C.media:[],M=[];for(let Y of $){if(!Y||typeof Y!="object")continue;let Z=Y,J=typeof Z.type=="string"?Z.type:void 0,qe=typeof Z.mediaType=="string"?Z.mediaType.toLowerCase():"",De=null,at="";if(J==="media"){let Ve=typeof Z.data=="string"?Z.data:void 0;if(!Ve)continue;at=qe.length>0?qe:"application/octet-stream",De=`data:${at};base64,${Ve}`}else if(J==="image-url"){let Ve=typeof Z.url=="string"?Z.url:void 0;if(!Ve)continue;at=qe,De=Ve}else if(J==="file-url"){let Ve=typeof Z.url=="string"?Z.url:void 0;if(!Ve)continue;at=qe,De=Ve}else continue;if(De)if(J==="image-url"||at.startsWith("image/"))M.push({type:"image",image:De,...at?{mimeType:at}:{}});else if(at.startsWith("audio/"))M.push({type:"audio",audio:De,mimeType:at});else if(at.startsWith("video/"))M.push({type:"video",video:De,mimeType:at});else{let Ve=at||"application/octet-stream";M.push({type:"file",data:De,mimeType:Ve,filename:Vm(Ve)})}}if(M.length>0){let Y=l(),Z=C.toolCallId,qe={id:`agent-media-${typeof Z=="string"&&Z.length>0?`${Z}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:M,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(qe);let De=f;De&&(De.streaming=!1,p(De)),f=null,v.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,M={id:$,role:"assistant",content:(us=C.reflection)!=null?us:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(ia=C.reflection)!=null?ia:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(M)}else if(Ue==="agent_complete"){G&&(G.status=C.success?"complete":"error",G.completedAt=ue(C.completedAt),G.stopReason=C.stopReason);let $=f;$&&($.streaming=!1,p($)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let $=typeof C.error=="string"?C.error:(la=(Rr=C.error)==null?void 0:Rr.message)!=null?la:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let $=(Xr=C.approvalId)!=null?Xr:`approval-${l()}`,M={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Rt=G==null?void 0:G.agentId)!=null?Rt:"virtual",executionId:(Ho=(Ro=C.executionId)!=null?Ro:G==null?void 0:G.executionId)!=null?Ho:"",toolName:(ms=C.toolName)!=null?ms:"",toolType:C.toolType,description:(ca=C.description)!=null?ca:`Execute ${(Cr=C.toolName)!=null?Cr:"tool"}`,parameters:C.parameters}};p(M)}else if(Ue==="step_await"&&C.awaitReason==="approval_required"){let $=(gs=C.approvalId)!=null?gs:`approval-${l()}`,M={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(fs=G==null?void 0:G.agentId)!=null?fs:"virtual",executionId:(Bo=(da=C.executionId)!=null?da:G==null?void 0:G.executionId)!=null?Bo:"",toolName:(Do=C.toolName)!=null?Do:"",toolType:C.toolType,description:(pa=C.description)!=null?pa:`Execute ${(go=C.toolName)!=null?go:"tool"}`,parameters:C.parameters}};p(M)}else if(Ue==="agent_approval_complete"){let $=C.approvalId;if($){let Y={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(ua=C.decision)!=null?ua:"approved",agentId:(hs=G==null?void 0:G.agentId)!=null?hs:"virtual",executionId:(bs=(ys=C.executionId)!=null?ys:G==null?void 0:G.executionId)!=null?bs:"",toolName:(xs=C.toolName)!=null?xs:"",description:(wn=C.description)!=null?wn:"",resolvedAt:Date.now()}};p(Y)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let $=C.artifactType,M=String(C.id),Y=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:M,artifactType:$,title:Y,component:typeof C.component=="string"?C.component:void 0}),V.set(M,{markdown:"",title:Y}),!ke.has(M)){ke.add(M);let Z={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:M,title:Y,artifactType:$,status:"streaming"}})};ne.set(M,Z),p(Z)}}else if(Ue==="artifact_delta"){let $=String(C.id),M=typeof C.delta=="string"?C.delta:String((Vn=C.delta)!=null?Vn:"");n({type:"artifact_delta",id:$,artDelta:M});let Y=V.get($);Y&&(Y.markdown+=M)}else if(Ue==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ue==="artifact_complete"){let $=String(C.id);n({type:"artifact_complete",id:$});let M=ne.get($);if(M){M.streaming=!1;try{let Y=JSON.parse((Hr=M.rawContent)!=null?Hr:"{}");if(Y.props){Y.props.status="complete";let Z=V.get($);Z!=null&&Z.markdown&&(Y.props.markdown=Z.markdown)}M.rawContent=JSON.stringify(Y)}catch{}V.delete($),p(M),ne.delete($)}}}else if(Ue==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let M=String((ot=$.id)!=null?ot:`msg-${l()}`),Y=$.role,J={id:M,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(p(J),J.rawContent)try{let qe=JSON.parse(J.rawContent),De=(vs=qe==null?void 0:qe.props)==null?void 0:vs.artifactId;typeof De=="string"&&ke.add(De)}catch{}f=null,v.current=null,z.delete(M),te.delete(M)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(Ue==="dispatch_error"){let M=(fo=C.message)!=null?fo:C.error;M!=null&&M!==""&&($=new Error(String(M)))}else if(Ue==="step_error"||Ue==="flow_error"){let M=C.error;typeof M=="string"&&M!==""?$=new Error(M):M!=null&&typeof M=="object"&&"message"in M&&($=new Error(String((gr=M.message)!=null?gr:M)))}else Ue==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){n({type:"error",error:$});let M=f;M&&M.streaming&&(M.streaming=!1,p(M)),n({type:"status",status:"idle"})}}}}}Ce.length=0};;){let{done:H,value:oe}=await s.read();if(H)break;a+=o.decode(oe,{stream:!0});let Be=a.split(`
10
10
 
11
- `);a=(vr=Be.pop())!=null?vr:"";for(let De of Be){let _e=De.split(`
12
- `),ct="message",nt="";for(let P of _e)P.startsWith("event:")?ct=P.replace("event:","").trim():P.startsWith("data:")&&(nt+=P.replace("data:","").trim());if(!nt)continue;let Ct;try{Ct=JSON.parse(nt)}catch(P){t({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let jt=ct!=="message"?ct:(dr=Ct.type)!=null?dr:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,jt,Ct),this.parseSSEEvent){v.current=f;let P=await this.handleCustomSSEEvent(Ct,t,v,p,l,x);if(v.current&&v.current!==f&&(f=v.current),P)continue}ie.push(jt,Ct),ve()}}ie.flushPending(),ve(),ie.destroy()}};function $m(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ts(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function jo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Ea="[Image]";function _m(e){return typeof e=="string"?[{type:"text",text:e}]:e}function jm(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Um(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function qm(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Ta(e){return{type:"text",text:e}}function zm(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Vm(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Km(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Ep=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Jm=["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"],Rr=[...Ep,...Jm];function Gm(e){return Ep.includes(e)||e.startsWith("image/")}function Ma(e){return Gm(e.type)}async function Tp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ma(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Mp(e,n=Rr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Xm(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function kp(e,n){let t=Xm(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var ka=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}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 n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,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.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var La=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ms=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new La;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,x=A=>{v||(v=!0,clearTimeout(S),m(new Error(A)))},S=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(S),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!v){let k=A.code!==1006?` (code ${A.code})`:"";x("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ka(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ao=class{constructor(n={}){this.config=n;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(n=>n("connected"))}async startListening(){var n,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=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Uo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ms(e.runtype);case"browser":if(!Ao.isSupported())throw new Error("Browser speech recognition not supported");return new Ao(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ai(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Uo({type:"runtype",runtype:e.runtype});if(Ao.isSupported())return Uo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Pa(e){try{return Ai(e),!0}catch{return!1}}function Lp(e,n){let t=e instanceof Error?e:new Error(String(e));if(typeof n=="string")return n;if(typeof n=="function")return n(t);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${r}
11
+ `);a=(ln=Be.pop())!=null?ln:"";for(let Xe of Be){let Fe=Xe.split(`
12
+ `),_e="message",rt="";for(let Kt of Fe)Kt.startsWith("event:")?_e=Kt.replace("event:","").trim():Kt.startsWith("data:")&&(rt+=Kt.replace("data:","").trim());if(!rt)continue;let At;try{At=JSON.parse(rt)}catch(Kt){n({type:"error",error:Kt instanceof Error?Kt:new Error("Failed to parse chat stream payload")});continue}let Ft=_e!=="message"?_e:(Hn=At.type)!=null?Hn:"message";if((Xn=this.onSSEEvent)==null||Xn.call(this,Ft,At),this.parseSSEEvent){v.current=f;let Kt=await this.handleCustomSSEEvent(At,n,v,p,l,x);if(v.current&&v.current!==f&&(f=v.current),Kt)continue}Ct.push(Ft,At),X()}}Ct.flushPending(),X(),Ct.destroy()}};function Gm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ls(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function zo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ka="[Image]";function Xm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Qm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ym(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Zm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function La(e){return{type:"text",text:e}}function eg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function tg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function ng(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Ip=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],rg=["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"],Nr=[...Ip,...rg];function og(e){return Ip.includes(e)||e.startsWith("image/")}function Pa(e){return og(e.type)}async function Wp(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Pa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Rp(e,t=Nr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function sg(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Hp(e,t){let n=sg(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Ia=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Wa=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Wa;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,x=A=>{v||(v=!0,clearTimeout(E),m(new Error(A)))},E=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!v){let I=A.code!==1006?` (code ${A.code})`:"";x("WebSocket connection failed"+I+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ia(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var So=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!So.isSupported())throw new Error("Browser speech recognition not supported");return new So(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Mi(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Vo({type:"runtype",runtype:e.runtype});if(So.isSupported())return Vo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ra(e){try{return Mi(e),!0}catch{return!1}}function Bp(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
13
13
 
14
- _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;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.handleEvent=n=>{var t,r,s,o,a,i,d,l;if(n.type==="message"){this.upsertMessage(n.message);let u=n.message.toolCall;((t=n.message.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&(u!=null&&u.name)&&ba(u.name)&&this.enqueueWebMcpAwait(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(s=n.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(n.type==="status"){if(this.setStatus(n.status),n.status==="connecting")this.setStreaming(!0);else if(n.status==="idle"||n.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(n.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else n.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new _o(n),this.wireDefaultWebMcpConfirm();for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Pa((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Uo(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,m,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let S=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:v.id;S&&this.ttsSpokenMessageIds.add(S)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new _o(this.config),this.wireDefaultWebMcpConfirm(),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=n,m={id:a!=null?a:t==="user"?Ts():t==="assistant"?jo():`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:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:s==="user"?Ts():s==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=n,l={text:s,component:t,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(n,t){var l,u,p,f,m;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=Ts(),o=jo(),a={id:s,role:"user",content:r||Ea,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:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let S=Lp(v,this.config.errorMessage);if(S){let A={id:o,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(A)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=jo();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:n},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=Lp(l,this.config.errorMessage);if(p){let f={id:n,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(n,t){var s,o,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let n=this.config.webmcp;(n==null?void 0:n.enabled)===!0&&!n.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(n){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,n))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:n.toolName,toolType:"webmcp",description:(a=n.description)!=null?a:`Allow the assistant to run ${n.toolName}?`,parameters:n.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(n,t){let r=this.webMcpApprovalResolvers.get(n);if(!r)return;this.webMcpApprovalResolvers.delete(n);let s=this.messages.find(o=>o.id===n);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(n,t){var d,l,u,p;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):f=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),f){let m=null;if(f instanceof Response){if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${f.status}`)}m=f.body}else f instanceof ReadableStream&&(m=f);m?await this.connectStream(m,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${n.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(f){let m=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,p,f,m,v,x,S,A,k,R,H,L;let r=this.messages.find(w=>w.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=n.agentMetadata)==null?void 0:p.executionId,o=(f=n.toolCall)==null?void 0:f.name;if(!s||!o){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let w=(x=n.toolCall)==null?void 0:x.args,B=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(B.length===1){let F=typeof((S=B[0])==null?void 0:S.question)=="string"?B[0].question:"";F&&(a={[F]:t})}}this.markAskUserQuestionResolved(n,a),(A=this.abortController)==null||A.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(k=n.toolCall)==null?void 0:k.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof t=="string"?t:Object.entries(t).map(([B,F])=>`${B}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((B,F)=>{let $=typeof(B==null?void 0:B.question)=="string"?B.question:"";if(!$)return;let W=w[$],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:t});if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((R=B==null?void 0:B.error)!=null?R:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let B=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,B||(L=(H=this.callbacks).onError)==null||L.call(H,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(n){var o,a;let t=(o=n.agentMetadata)==null?void 0:o.executionId,r=(a=n.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(n)});return}let s=this.webMcpAwaitBatches.get(t);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(n))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let n=this.webMcpEpoch;queueMicrotask(()=>{if(n===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(n){let t=this.webMcpAwaitBatches.get(n);if(!t)return;this.webMcpAwaitBatches.delete(n);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(n,r)}async resolveWebMcpToolCallBatch(n,t){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(t.map(async u=>{var k,R,H,L,w,B,F;let p=(k=u.toolCall)==null?void 0:k.name,f=(R=u.toolCall)==null?void 0:R.id;if(!p||!f)return null;let m=`${n}:${f}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),r.push(m),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(L=(H=u.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?L:p,S=this.client.executeWebMcpToolCall(p,(w=u.toolCall)==null?void 0:w.args,v.signal),A;if(!S)A={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{A=await S}catch($){return $ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"))||(F=(B=this.callbacks).onError)==null||F.call(B,$ instanceof Error?$:new Error(String($))),this.webMcpInflightKeys.delete(m),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:x,output:A}}));try{let u=a.filter(m=>m!==null);if(u.length===0)return;let p={};for(let m of u)p[m.resumeKey]=m.output;let f=await this.client.resumeFlow(n,p,{signal:o.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${f.status}`)}for(let m of u)this.webMcpResolvedKeys.add(m.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of s)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(n){var u,p,f,m,v,x,S,A,k,R,H,L;let t=(u=n.agentMetadata)==null?void 0:u.executionId,r=(p=n.toolCall)==null?void 0:p.name,s=(f=n.toolCall)==null?void 0:f.id;if(!t){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(B){(S=(x=this.callbacks).onError)==null||S.call(x,B instanceof Error?B:new Error(String(B)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${t}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(A=n.toolCall)==null?void 0:A.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let B=(R=(k=n.agentMetadata)==null?void 0:k.webMcpToolCallId)!=null?R:r;await this.resumeWithToolOutput(t,B,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(L=(H=this.callbacks).onError)==null||L.call(H,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(n,t,r,s){var a,i;let o=await this.client.resumeFlow(n,{[t]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let n of this.webMcpResolveControllers)n.abort();this.webMcpResolveControllers.clear();for(let n of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(n,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};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 n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var u,p,f,m,v,x;if(o!==r)return s;let a={...s,...t};((u=s.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=t.toolCall)==null?void 0:p.name,d=(f=t.agentMetadata)==null?void 0:f.executionId,l=(m=t.toolCall)==null?void 0:m.id;if(i&&ba(i)&&d&&l&&((v=t.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let S=`${d}:${l}`;(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},br=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as Ym,ArrowDown as Qm,ArrowUp as Zm,ArrowUpRight as eg,Bot as tg,ChevronDown as ng,ChevronUp as rg,ChevronRight as og,ChevronLeft as sg,Check as ag,Clipboard as ig,ClipboardCopy as lg,Copy as cg,File as dg,FileCode as pg,FileSpreadsheet as ug,FileText as mg,ImagePlus as gg,Loader as fg,LoaderCircle as hg,Mic as yg,Paperclip as bg,RefreshCw as xg,Search as vg,Send as wg,ShieldAlert as Cg,ShieldCheck as Ag,ShieldX as Sg,Square as Eg,ThumbsDown as Tg,ThumbsUp as Mg,Upload as kg,Volume2 as Lg,X as Pg,User as Ig,Mail as Wg,Phone as Rg,Calendar as Hg,Clock as Bg,Building as Dg,MapPin as Ng,Lock as Og,Key as Fg,CreditCard as $g,AtSign as _g,Hash as jg,Globe as Ug,Link as qg,CircleCheck as zg,CircleX as Vg,TriangleAlert as Kg,Info as Jg,Ban as Gg,Shield as Xg,ArrowLeft as Yg,ArrowRight as Qg,ExternalLink as Zg,Ellipsis as ef,EllipsisVertical as tf,Menu as nf,House as rf,Plus as of,Minus as sf,Pencil as af,Trash as lf,Trash2 as cf,Save as df,Download as pf,Share as uf,Funnel as mf,Settings as gf,RotateCw as ff,Maximize as hf,Minimize as yf,ShoppingCart as bf,ShoppingBag as xf,Package as vf,Truck as wf,Tag as Cf,Gift as Af,Receipt as Sf,Wallet as Ef,Store as Tf,DollarSign as Mf,Percent as kf,Play as Lf,Pause as Pf,VolumeX as If,Camera as Wf,Image as Rf,Film as Hf,Headphones as Bf,MessageCircle as Df,MessageSquare as Nf,Bell as Of,Heart as Ff,Star as $f,Eye as _f,EyeOff as jf,Bookmark as Uf,CalendarDays as qf,History as zf,Timer as Vf,Folder as Kf,FolderOpen as Jf,Files as Gf,Sparkles as Xf,Zap as Yf,Sun as Qf,Moon as Zf,Flag as eh,Monitor as th,Smartphone as nh}from"lucide";var rh={activity:Ym,"arrow-down":Qm,"arrow-up":Zm,"arrow-up-right":eg,bot:tg,"chevron-down":ng,"chevron-up":rg,"chevron-right":og,"chevron-left":sg,check:ag,clipboard:ig,"clipboard-copy":lg,copy:cg,file:dg,"file-code":pg,"file-spreadsheet":ug,"file-text":mg,"image-plus":gg,loader:fg,"loader-circle":hg,mic:yg,paperclip:bg,"refresh-cw":xg,search:vg,send:wg,"shield-alert":Cg,"shield-check":Ag,"shield-x":Sg,square:Eg,"thumbs-down":Tg,"thumbs-up":Mg,upload:kg,"volume-2":Lg,x:Pg,user:Ig,mail:Wg,phone:Rg,calendar:Hg,clock:Bg,building:Dg,"map-pin":Ng,lock:Og,key:Fg,"credit-card":$g,"at-sign":_g,hash:jg,globe:Ug,link:qg,"circle-check":zg,"circle-x":Vg,"triangle-alert":Kg,info:Jg,ban:Gg,shield:Xg,"arrow-left":Yg,"arrow-right":Qg,"external-link":Zg,ellipsis:ef,"ellipsis-vertical":tf,menu:nf,house:rf,plus:of,minus:sf,pencil:af,trash:lf,"trash-2":cf,save:df,download:pf,share:uf,funnel:mf,settings:gf,"rotate-cw":ff,maximize:hf,minimize:yf,"shopping-cart":bf,"shopping-bag":xf,package:vf,truck:wf,tag:Cf,gift:Af,receipt:Sf,wallet:Ef,store:Tf,"dollar-sign":Mf,percent:kf,play:Lf,pause:Pf,"volume-x":If,camera:Wf,image:Rf,film:Hf,headphones:Bf,"message-circle":Df,"message-square":Nf,bell:Of,heart:Ff,star:$f,eye:_f,"eye-off":jf,bookmark:Uf,"calendar-days":qf,history:zf,timer:Vf,folder:Kf,"folder-open":Jf,files:Gf,sparkles:Xf,zap:Yf,sun:Qf,moon:Zf,flag:eh,monitor:th,smartphone:nh},fe=(e,n=24,t="currentColor",r=2)=>{let s=rh[e];return s?oh(s,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function oh(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var Ia={allowedTypes:Rr,maxFileSize:10*1024*1024,maxFiles:4};function sh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ah(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var qo=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ia.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ia.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ia.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Ia.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let u=Mp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await Tp(l),f=Ma(l)?URL.createObjectURL(l):null,m={id:sh(),file:l,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ma(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.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=h("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=ah(n.file.type),d=fe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=kp(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Pp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ls(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];Pp(o)&&Pp(s)?t[r]=Ls(o,s):t[r]=s}return t}var Gn="min(440px, calc(100vw - 24px))",Si="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{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:Gn,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)"},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:""},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 Ip(e,n){if(!(!e&&!n))return e?n?Ls(e,n):e:n}function Ei(e){var n,t,r,s,o,a,i,d,l,u,p,f,m,v,x,S,A,k,R,H,L;return e?{...Ft,...e,theme:Ip(Ft.theme,e.theme),darkTheme:Ip(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(n=Ft.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var ce,Ee,je,te,xe,G,ae,He;let w=(ce=Ft.features)==null?void 0:ce.artifacts,B=(Ee=e.features)==null?void 0:Ee.artifacts,F=(je=Ft.features)==null?void 0:je.scrollToBottom,$=(te=e.features)==null?void 0:te.scrollToBottom,W=(xe=Ft.features)==null?void 0:xe.streamAnimation,O=(G=e.features)==null?void 0:G.streamAnimation,V=(ae=Ft.features)==null?void 0:ae.askUserQuestion,oe=(He=e.features)==null?void 0:He.askUserQuestion,Ie=w===void 0&&B===void 0?void 0:{...w,...B,layout:{...w==null?void 0:w.layout,...B==null?void 0:B.layout}},Pe=F===void 0&&$===void 0?void 0:{...F,...$},ze=W===void 0&&O===void 0?void 0:{...W,...O},pe=V===void 0&&oe===void 0?void 0:{...V,...oe,styles:{...V==null?void 0:V.styles,...oe==null?void 0:oe.styles}};return{...Ft.features,...e.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{artifacts:Ie}:{},...ze!==void 0?{streamAnimation:ze}:{},...pe!==void 0?{askUserQuestion:pe}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Ft.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Ft.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(A=(S=e.layout)==null?void 0:S.messages)==null?void 0:A.timestamp}},slots:{...(k=Ft.layout)==null?void 0:k.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(H=Ft.markdown)==null?void 0:H.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var Wp={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"}},Rp={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"}},Hp={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:Gn,maxWidth:Si,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:"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"},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 zo(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?zo(e,r):r}function Ti(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=zo(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function Bp(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function Dp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=Dp(o,s):t[r]=s}return t}function ih(e,n){return n?Dp(e,n):e}function Ps(e,n={}){var s,o,a,i,d,l,u,p,f,m,v,x,S;let t={palette:Wp,semantic:Rp,components:Hp},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:ih(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let A=Bp(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(k=>k.message).join(", ")}`)}if(n.plugins)for(let A of n.plugins)r=A.transform(r);return r}function Mi(e){var x,S,A,k,R,H,L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe,ce,Ee,je,te,xe,G,ae,He,ue,Re,tt,K,se,Oe,J,z,we,$e,ne,Te,ve,Ht,ie,re,sn,Nt,zt,vr,dr,Ue,U,Ae,Be,De,_e,ct,nt,Ct,jt,P,he,ge,dt,Ke,It,an,At,bt,Mt,ut,Vt,wr,_n,Br,vt,pr,ur,Cr,Qn,gt,io,mr,lo,Sn,ko,Dr,Ar,yt,Pn,In,fn,kt,jn,Un,Wn,Nr,Sr,Or,Rn,Wt,hn,qn,Fr,Er,$r,gr,Hn,Zn,ft,Kt,Jt,Bn,_r,zn,er,Dn,_;let n=Ti(e),t={};for(let[de,Nn]of Object.entries(n)){let tr=de.replace(/\./g,"-");t[`--persona-${tr}`]=Nn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(S=t["--persona-semantic-colors-secondary"])!=null?S:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(A=t["--persona-semantic-colors-accent"])!=null?A:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(k=t["--persona-semantic-colors-surface"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(R=t["--persona-semantic-colors-background"])!=null?R:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(L=t["--persona-semantic-colors-text"])!=null?L:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(w=t["--persona-semantic-colors-text-muted"])!=null?w:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(B=t["--persona-semantic-colors-text-inverse"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(F=t["--persona-semantic-colors-border"])!=null?F:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=($=t["--persona-semantic-colors-divider"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(W=t["--persona-components-voice-recording-indicator"])!=null?W:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O: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"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ie=t["--persona-components-approval-requested-background"])!=null?Ie:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Pe=t["--persona-components-approval-requested-border"])!=null?Pe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ze=t["--persona-components-approval-requested-text"])!=null?ze:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(pe=t["--persona-components-approval-approve-background"])!=null?pe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ce=t["--persona-components-approval-deny-background"])!=null?ce:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Ee=t["--persona-components-attachment-image-background"])!=null?Ee:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(je=t["--persona-components-attachment-image-border"])!=null?je:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(te=t["--persona-semantic-typography-fontFamily"])!=null?te:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(xe=t["--persona-semantic-typography-fontSize"])!=null?xe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(G=t["--persona-semantic-typography-fontWeight"])!=null?G:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ae=t["--persona-semantic-typography-lineHeight"])!=null?ae: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"]=(He=t["--persona-palette-radius-sm"])!=null?He:"0.125rem",t["--persona-radius-md"]=(ue=t["--persona-palette-radius-md"])!=null?ue:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(tt=t["--persona-palette-radius-xl"])!=null?tt:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=(Oe=(se=t["--persona-components-launcher-borderRadius"])!=null?se:t["--persona-palette-radius-full"])!=null?Oe:"9999px",t["--persona-launcher-bg"]=(J=t["--persona-components-launcher-background"])!=null?J:t["--persona-primary"],t["--persona-launcher-fg"]=(z=t["--persona-components-launcher-foreground"])!=null?z:t["--persona-text-inverse"],t["--persona-launcher-border"]=(we=t["--persona-components-launcher-border"])!=null?we:t["--persona-border"],t["--persona-button-primary-bg"]=($e=t["--persona-components-button-primary-background"])!=null?$e:t["--persona-primary"],t["--persona-button-primary-fg"]=(ne=t["--persona-components-button-primary-foreground"])!=null?ne:t["--persona-text-inverse"],t["--persona-button-radius"]=(ve=(Te=t["--persona-components-button-primary-borderRadius"])!=null?Te:t["--persona-palette-radius-full"])!=null?ve:"9999px",t["--persona-panel-radius"]=(ie=(Ht=t["--persona-components-panel-borderRadius"])!=null?Ht:t["--persona-radius-xl"])!=null?ie:"0.75rem",t["--persona-panel-border"]=(re=t["--persona-components-panel-border"])!=null?re:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Nt=(sn=t["--persona-components-panel-shadow"])!=null?sn:t["--persona-palette-shadows-xl"])!=null?Nt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(vr=(zt=t["--persona-components-input-borderRadius"])!=null?zt:t["--persona-radius-lg"])!=null?vr:"0.5rem",t["--persona-message-user-radius"]=(Ue=(dr=t["--persona-components-message-user-borderRadius"])!=null?dr:t["--persona-radius-lg"])!=null?Ue:"0.5rem",t["--persona-message-assistant-radius"]=(Ae=(U=t["--persona-components-message-assistant-borderRadius"])!=null?U:t["--persona-radius-lg"])!=null?Ae:"0.5rem",t["--persona-header-bg"]=(Be=t["--persona-components-header-background"])!=null?Be:t["--persona-surface"],t["--persona-header-border"]=(De=t["--persona-components-header-border"])!=null?De:t["--persona-divider"],t["--persona-header-icon-bg"]=(_e=t["--persona-components-header-iconBackground"])!=null?_e:t["--persona-primary"],t["--persona-header-icon-fg"]=(ct=t["--persona-components-header-iconForeground"])!=null?ct:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(nt=t["--persona-components-header-titleForeground"])!=null?nt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ct=t["--persona-components-header-subtitleForeground"])!=null?Ct:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(jt=t["--persona-components-header-actionIconForeground"])!=null?jt:t["--persona-muted"];let r=(P=e.components)==null?void 0:P.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(he=e.components)==null?void 0:he.introCard;t["--persona-intro-card-bg"]=(ge=t["--persona-components-introCard-background"])!=null?ge:t["--persona-surface"],t["--persona-intro-card-radius"]=(dt=t["--persona-components-introCard-borderRadius"])!=null?dt:"1rem",t["--persona-intro-card-padding"]=(Ke=t["--persona-components-introCard-padding"])!=null?Ke:"1.5rem",t["--persona-intro-card-shadow"]=(an=(It=s==null?void 0:s.shadow)!=null?It:t["--persona-components-introCard-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(At=t["--persona-components-input-background"])!=null?At:t["--persona-surface"],t["--persona-input-placeholder"]=(bt=t["--persona-components-input-placeholder"])!=null?bt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Mt=t["--persona-components-message-user-background"])!=null?Mt:t["--persona-accent"],t["--persona-message-user-text"]=(ut=t["--persona-components-message-user-text"])!=null?ut:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Vt=t["--persona-components-message-user-shadow"])!=null?Vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(wr=t["--persona-components-message-assistant-background"])!=null?wr:t["--persona-surface"],t["--persona-message-assistant-text"]=(_n=t["--persona-components-message-assistant-text"])!=null?_n:t["--persona-text"],t["--persona-message-assistant-border"]=(Br=t["--persona-components-message-assistant-border"])!=null?Br:t["--persona-border"],t["--persona-message-assistant-shadow"]=(vt=t["--persona-components-message-assistant-shadow"])!=null?vt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(pr=t["--persona-components-scrollToBottom-background"])!=null?pr:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Qn=(Cr=t["--persona-components-scrollToBottom-foreground"])!=null?Cr:t["--persona-button-primary-fg"])!=null?Qn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(gt=t["--persona-components-scrollToBottom-border"])!=null?gt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(io=t["--persona-components-scrollToBottom-size"])!=null?io:"40px",t["--persona-scroll-to-bottom-radius"]=(Sn=(lo=(mr=t["--persona-components-scrollToBottom-borderRadius"])!=null?mr:t["--persona-button-radius"])!=null?lo:t["--persona-radius-full"])!=null?Sn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Dr=(ko=t["--persona-components-scrollToBottom-shadow"])!=null?ko:t["--persona-palette-shadows-sm"])!=null?Dr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Ar=t["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(yt=t["--persona-components-scrollToBottom-gap"])!=null?yt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(In=(Pn=t["--persona-components-scrollToBottom-fontSize"])!=null?Pn:t["--persona-palette-typography-fontSize-sm"])!=null?In:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(fn=t["--persona-components-scrollToBottom-iconSize"])!=null?fn:"14px",t["--persona-tool-bubble-shadow"]=(kt=t["--persona-components-toolBubble-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(jn=t["--persona-components-reasoningBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Un=t["--persona-components-composer-shadow"])!=null?Un:"none",t["--persona-md-inline-code-bg"]=(Wn=t["--persona-components-markdown-inlineCode-background"])!=null?Wn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Nr=t["--persona-components-markdown-inlineCode-foreground"])!=null?Nr:t["--persona-text"],t["--persona-md-link-color"]=(Or=(Sr=t["--persona-components-markdown-link-foreground"])!=null?Sr:t["--persona-accent"])!=null?Or:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);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 l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Rn=t["--persona-components-markdown-codeBlock-background"])!=null?Rn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Wt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Wt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(hn=t["--persona-components-markdown-codeBlock-textColor"])!=null?hn:"inherit",t["--persona-md-table-header-bg"]=(qn=t["--persona-components-markdown-table-headerBackground"])!=null?qn:t["--persona-container"],t["--persona-md-table-border-color"]=(Fr=t["--persona-components-markdown-table-borderColor"])!=null?Fr:t["--persona-border"],t["--persona-md-hr-color"]=(Er=t["--persona-components-markdown-hr-color"])!=null?Er:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=($r=t["--persona-components-markdown-blockquote-borderColor"])!=null?$r:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(gr=t["--persona-components-markdown-blockquote-background"])!=null?gr:"transparent",t["--persona-md-blockquote-text-color"]=(Hn=t["--persona-components-markdown-blockquote-textColor"])!=null?Hn:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zn=t["--persona-components-collapsibleWidget-container"])!=null?Zn:t["--persona-surface"],t["--cw-surface"]=(ft=t["--persona-components-collapsibleWidget-surface"])!=null?ft:t["--persona-surface"],t["--cw-border"]=(Kt=t["--persona-components-collapsibleWidget-border"])!=null?Kt:t["--persona-border"],t["--persona-message-border"]=(Jt=t["--persona-components-message-border"])!=null?Jt:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let de=v.toolbar;de.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=de.iconHoverColor),de.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=de.iconHoverBackground),de.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=de.iconPadding),de.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=de.iconBorderRadius),de.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=de.iconBorder),de.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=de.toggleGroupGap),de.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=de.toggleBorderRadius),de.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=de.copyBackground),de.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=de.copyBorder),de.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=de.copyColor),de.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=de.copyBorderRadius),de.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=de.copyPadding),de.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=de.copyMenuBackground,t["--persona-dropdown-bg"]=(Bn=t["--persona-dropdown-bg"])!=null?Bn:de.copyMenuBackground),de.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=de.copyMenuBorder,t["--persona-dropdown-border"]=(_r=t["--persona-dropdown-border"])!=null?_r:de.copyMenuBorder),de.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=de.copyMenuShadow,t["--persona-dropdown-shadow"]=(zn=t["--persona-dropdown-shadow"])!=null?zn:de.copyMenuShadow),de.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=de.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(er=t["--persona-dropdown-radius"])!=null?er:de.copyMenuBorderRadius),de.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=de.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Dn=t["--persona-dropdown-item-hover-bg"])!=null?Dn:de.copyMenuItemHoverBackground),de.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=de.iconBackground),de.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=de.toolbarBorder)}if(v!=null&&v.tab){let de=v.tab;de.background&&(t["--persona-artifact-tab-bg"]=de.background),de.activeBackground&&(t["--persona-artifact-tab-active-bg"]=de.activeBackground),de.activeBorder&&(t["--persona-artifact-tab-active-border"]=de.activeBorder),de.borderRadius&&(t["--persona-artifact-tab-radius"]=de.borderRadius),de.textColor&&(t["--persona-artifact-tab-color"]=de.textColor),de.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=de.hoverBackground),de.listBackground&&(t["--persona-artifact-tab-list-bg"]=de.listBackground),de.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=de.listBorderColor),de.listPadding&&(t["--persona-artifact-tab-list-padding"]=de.listPadding)}if(v!=null&&v.pane){let de=v.pane;if(de.toolbarBackground){let Nn=(_=zo(e,de.toolbarBackground))!=null?_:de.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nn}}return t}var lh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var ch={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"}}},Np=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Wa=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},dh=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Wa()},Op=e=>dh(e),ph=e=>Ps(e),uh=e=>{var t;let n=Ps(void 0,{validate:!1});return Ps({...e,palette:{...n.palette,colors:{...ch.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Is=e=>{let n=Op(e),t=Np(e==null?void 0:e.theme),r=Np(e==null?void 0:e.darkTheme);return n==="dark"?uh(Ls(t!=null?t:{},r!=null?r:{})):ph(t)},mh=e=>Mi(e),So=(e,n)=>{var o;let t=Is(n),r=mh(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ki=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Wa())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Wa());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as gh}from"idiomorph";var Ra=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;gh.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Ha={index:-1,draft:""};function Fp(e){let{direction:n,history:t,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(t.length===0)return{handled:!1,state:o};if(n==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<t.length-1){let i=o.index+1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Ha}}}function $p(e,n){var t,r,s,o,a,i,d,l,u,p,f,m,v,x,S,A,k,R,H,L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe,ce,Ee,je,te,xe,G;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(S=(x=e.toolCall)==null?void 0:x.name)!=null?S:"",(R=(k=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:k.length)!=null?R:0,(B=(w=(L=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?B:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(V=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?V:0,(ze=(Pe=(Ie=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:Pe.length)!=null?ze:0,(je=(Ee=(ce=(pe=e.reasoning)==null?void 0:pe.chunks)==null?void 0:ce[e.reasoning.chunks.length-1])==null?void 0:Ee.slice(-32))!=null?je:"",(xe=(te=e.contentParts)==null?void 0:te.length)!=null?xe:0,(G=e.stopReason)!=null?G:"",n].join("\0")}function _p(){return new Map}function jp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Up(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function qp(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Ba(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Ws(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Rs(e,n){return Ws(e)-e.scrollTop<=n}function Da(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!n&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Na(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},gn=1e5,Yr=gn+1;var Hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},fh=["pre","code","a","script","style"],Oa=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Hs.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Hs.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Hs.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Hs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Hs.buffer}},Vp=[{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"}],Bs=new Map;for(let e of Vp)Bs.set(e.name,e);var hh=e=>{Bs.set(e.name,e)},yh=e=>{Vp.some(n=>n.name===e)||Bs.delete(e)},bh=()=>Array.from(Bs.keys()),Ds=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Bs.get(e))!=null?r:null},Fa=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
15
- `);return o<0?"":e.slice(0,o)}return e},xh=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},vh=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},Li=/\s/,wh=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Ch=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(Li.test(o[i])){let l=i;for(;l<o.length&&Li.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!Li.test(o[u]);)l.appendChild(xh(r,o[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},Ah=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(vh(r,l,n,t.value)),t.value+=1));s.replaceChild(a,e)},Ns=(e,n,t,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((p=r==null?void 0:r.skipTags)!=null?p:fh).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)wh(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?Ch:Ah;for(let m of i)u(m,t,l);return s.innerHTML},$a=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},Os=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},zp=new WeakMap,Sh=(e,n)=>{var o;if(!e.styles)return;let t=zp.get(n);if(t||(t=new Set,zp.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},Pi=new WeakMap,Eh=(e,n)=>{if(!e.onAttach)return;let t=Pi.get(n);if(t||(t=new Map,Pi.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},Kp=e=>{let n=Pi.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},Ii=(e,n)=>{Sh(e,n),Eh(e,n)};function Wi(e,n=gn){let t=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var Fs=0,Qr=null;function Ri(e=document){var t;if(Fs++,Fs===1){let r=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Qr={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,Fs=Math.max(0,Fs-1),Fs===0&&Qr)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=Qr.originalOverflow,s.style.position=Qr.originalPosition,s.style.top=Qr.originalTop,s.style.width=Qr.originalWidth,o.scrollTo(0,Qr.scrollY),Qr=null}}}var _a={side:"right",width:"420px",animate:!0,reveal:"resize"},on=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Zr=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},lr=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:_a.side,width:(s=n==null?void 0:n.width)!=null?s:_a.width,animate:(o=n==null?void 0:n.animate)!=null?o:_a.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:_a.reveal}};var cr={"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 $s=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
14
+ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,r,s,o,a,i,d,l;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall;((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&(u!=null&&u.name)&&wa(u.name)&&this.enqueueWebMcpAwait(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,s;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new qo(t),this.wireDefaultWebMcpConfirm();for(let o of(s=t.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ra((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,s;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vo(o);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,m,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let E=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:v.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,s,o,a,i,d,l,u;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((s=t.runtype)==null?void 0:s.clientToken)||"",host:(o=t.runtype)==null?void 0:o.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=t.browser)==null?void 0:l.language)||"en-US",continuous:(u=t.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new qo(this.config),this.wireDefaultWebMcpConfirm(),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=t,m={id:a!=null?a:n==="user"?Ls():n==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:s==="user"?Ls():s==="assistant"?zo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=t,l={text:s,component:n,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,u,p,f,m;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=Ls(),o=zo(),a={id:s,role:"user",content:r||ka,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=Bp(v,this.config.errorMessage);if(E){let A={id:o,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(A)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let t=zo();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=Bp(l,this.config.errorMessage);if(p){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var s,o,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(o=>o.id===t);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n){var d,l,u,p;let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):f=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),f){let m=null;if(f instanceof Response){if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${f.status}`)}m=f.body}else f instanceof ReadableStream&&(m=f);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let m=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(s=>s.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var u,p,f,m,v,x,E,A,I,P,N,L;let r=this.messages.find(w=>w.id===t.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=t.agentMetadata)==null?void 0:p.executionId,o=(f=t.toolCall)==null?void 0:f.name;if(!s||!o){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let w=(x=t.toolCall)==null?void 0:x.args,W=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(W.length===1){let F=typeof((E=W[0])==null?void 0:E.question)=="string"?W[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(t,a),(A=this.abortController)==null||A.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(I=t.toolCall)==null?void 0:I.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof n=="string"?n:Object.entries(n).map(([W,F])=>`${W}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((W,F)=>{let _=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!_)return;let B=w[_],j=Array.isArray(B)?B.join(", "):typeof B=="string"?B:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:n});if(!w.ok){let W=await w.json().catch(()=>null);throw new Error((P=W==null?void 0:W.error)!=null?P:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let W=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(L=(N=this.callbacks).onError)==null||L.call(N,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(t){var o,a;let n=(o=t.agentMetadata)==null?void 0:o.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}async resolveWebMcpToolCallBatch(t,n){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{var I,P,N,L,w,W,F;let p=(I=u.toolCall)==null?void 0:I.name,f=(P=u.toolCall)==null?void 0:P.id;if(!p||!f)return null;let m=`${t}:${f}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),r.push(m),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(L=(N=u.agentMetadata)==null?void 0:N.webMcpToolCallId)!=null?L:p,E=this.client.executeWebMcpToolCall(p,(w=u.toolCall)==null?void 0:w.args,v.signal),A;if(!E)A={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{A=await E}catch(_){return _ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"))||(F=(W=this.callbacks).onError)==null||F.call(W,_ instanceof Error?_:new Error(String(_))),this.webMcpInflightKeys.delete(m),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:x,output:A}}));try{let u=a.filter(m=>m!==null);if(u.length===0)return;let p={};for(let m of u)p[m.resumeKey]=m.output;let f=await this.client.resumeFlow(t,p,{signal:o.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${f.status}`)}for(let m of u)this.webMcpResolvedKeys.add(m.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of s)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var u,p,f,m,v,x,E,A,I,P,N,L;let n=(u=t.agentMetadata)==null?void 0:u.executionId,r=(p=t.toolCall)==null?void 0:p.name,s=(f=t.toolCall)==null?void 0:f.id;if(!n){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(W){(E=(x=this.callbacks).onError)==null||E.call(x,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${n}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...t,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(A=t.toolCall)==null?void 0:A.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let W=(P=(I=t.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?P:r;await this.resumeWithToolOutput(n,W,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(L=(N=this.callbacks).onError)==null||L.call(N,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,s){var a,i;let o=await this.client.resumeFlow(t,{[n]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var s;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let o={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),o}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(s=t.props)!=null?s:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let s=this.artifacts.get(t.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...t.props},t.component&&(s.component=t.component));break}case"artifact_complete":{let s=this.artifacts.get(t.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(t),o=r.getVoices();if(n.voice){let a=o.find(i=>i.name===n.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=n.pickVoice?n.pickVoice(o):e.pickBestVoice(o));n.rate!==void 0&&(s.rate=n.rate),n.pitch!==void 0&&(s.pitch=n.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(t){var r;let n=["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 s of n){let o=t.find(a=>a.name===s);if(o)return o}return(r=t.find(s=>s.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(s=>s.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,o)=>{var u,p,f,m,v,x;if(o!==r)return s;let a={...s,...n};((u=s.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=n.toolCall)==null?void 0:p.name,d=(f=n.agentMetadata)==null?void 0:f.executionId,l=(m=n.toolCall)==null?void 0:m.id;if(i&&wa(i)&&d&&l&&((v=n.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let E=`${d}:${l}`;(this.webMcpInflightKeys.has(E)||this.webMcpResolvedKeys.has(E))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let s=new Date(n.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Sr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import{Activity as ag,ArrowDown as ig,ArrowUp as lg,ArrowUpRight as cg,Bot as dg,ChevronDown as pg,ChevronUp as ug,ChevronRight as mg,ChevronLeft as gg,Check as fg,Clipboard as hg,ClipboardCopy as yg,Copy as bg,File as xg,FileCode as vg,FileSpreadsheet as wg,FileText as Cg,ImagePlus as Ag,Loader as Sg,LoaderCircle as Eg,Mic as Tg,Paperclip as Mg,RefreshCw as kg,Search as Lg,Send as Pg,ShieldAlert as Ig,ShieldCheck as Wg,ShieldX as Rg,Square as Hg,ThumbsDown as Bg,ThumbsUp as Dg,Upload as Ng,Volume2 as Og,X as Fg,User as _g,Mail as $g,Phone as jg,Calendar as Ug,Clock as qg,Building as zg,MapPin as Vg,Lock as Kg,Key as Jg,CreditCard as Gg,AtSign as Xg,Hash as Qg,Globe as Yg,Link as Zg,CircleCheck as ef,CircleX as tf,TriangleAlert as nf,Info as rf,Ban as of,Shield as sf,ArrowLeft as af,ArrowRight as lf,ExternalLink as cf,Ellipsis as df,EllipsisVertical as pf,Menu as uf,House as mf,Plus as gf,Minus as ff,Pencil as hf,Trash as yf,Trash2 as bf,Save as xf,Download as vf,Share as wf,Funnel as Cf,Settings as Af,RotateCw as Sf,Maximize as Ef,Minimize as Tf,ShoppingCart as Mf,ShoppingBag as kf,Package as Lf,Truck as Pf,Tag as If,Gift as Wf,Receipt as Rf,Wallet as Hf,Store as Bf,DollarSign as Df,Percent as Nf,Play as Of,Pause as Ff,VolumeX as _f,Camera as $f,Image as jf,Film as Uf,Headphones as qf,MessageCircle as zf,MessageSquare as Vf,Bell as Kf,Heart as Jf,Star as Gf,Eye as Xf,EyeOff as Qf,Bookmark as Yf,CalendarDays as Zf,History as eh,Timer as th,Folder as nh,FolderOpen as rh,Files as oh,Sparkles as sh,Zap as ah,Sun as ih,Moon as lh,Flag as ch,Monitor as dh,Smartphone as ph}from"lucide";var uh={activity:ag,"arrow-down":ig,"arrow-up":lg,"arrow-up-right":cg,bot:dg,"chevron-down":pg,"chevron-up":ug,"chevron-right":mg,"chevron-left":gg,check:fg,clipboard:hg,"clipboard-copy":yg,copy:bg,file:xg,"file-code":vg,"file-spreadsheet":wg,"file-text":Cg,"image-plus":Ag,loader:Sg,"loader-circle":Eg,mic:Tg,paperclip:Mg,"refresh-cw":kg,search:Lg,send:Pg,"shield-alert":Ig,"shield-check":Wg,"shield-x":Rg,square:Hg,"thumbs-down":Bg,"thumbs-up":Dg,upload:Ng,"volume-2":Og,x:Fg,user:_g,mail:$g,phone:jg,calendar:Ug,clock:qg,building:zg,"map-pin":Vg,lock:Kg,key:Jg,"credit-card":Gg,"at-sign":Xg,hash:Qg,globe:Yg,link:Zg,"circle-check":ef,"circle-x":tf,"triangle-alert":nf,info:rf,ban:of,shield:sf,"arrow-left":af,"arrow-right":lf,"external-link":cf,ellipsis:df,"ellipsis-vertical":pf,menu:uf,house:mf,plus:gf,minus:ff,pencil:hf,trash:yf,"trash-2":bf,save:xf,download:vf,share:wf,funnel:Cf,settings:Af,"rotate-cw":Sf,maximize:Ef,minimize:Tf,"shopping-cart":Mf,"shopping-bag":kf,package:Lf,truck:Pf,tag:If,gift:Wf,receipt:Rf,wallet:Hf,store:Bf,"dollar-sign":Df,percent:Nf,play:Of,pause:Ff,"volume-x":_f,camera:$f,image:jf,film:Uf,headphones:qf,"message-circle":zf,"message-square":Vf,bell:Kf,heart:Jf,star:Gf,eye:Xf,"eye-off":Qf,bookmark:Yf,"calendar-days":Zf,history:eh,timer:th,folder:nh,"folder-open":rh,files:oh,sparkles:sh,zap:ah,sun:ih,moon:lh,flag:ch,monitor:dh,smartphone:ph},be=(e,t=24,n="currentColor",r=2)=>{let s=uh[e];return s?mh(s,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function mh(e,t,n,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var Ha={allowedTypes:Nr,maxFileSize:10*1024*1024,maxFiles:4};function gh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function fh(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ko=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,s;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ha.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ha.maxFileSize,maxFiles:(s=t.maxFiles)!=null?s:Ha.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ha.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,s,o,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let u=Rp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await Wp(l),f=Pa(l)?URL.createObjectURL(l):null,m={id:gh(),file:l,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var o,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Pa(t.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("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=fh(t.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Hp(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=be("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Dp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];Dp(o)&&Dp(s)?n[r]=Ws(o,s):n[r]=s}return n}var sr="min(440px, calc(100vw - 24px))",ki="440px",Ot={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:sr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},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:""},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 Np(e,t){if(!(!e&&!t))return e?t?Ws(e,t):e:t}function Li(e){var t,n,r,s,o,a,i,d,l,u,p,f,m,v,x,E,A,I,P,N,L;return e?{...Ot,...e,theme:Np(Ot.theme,e.theme),darkTheme:Np(Ot.darkTheme,e.darkTheme),launcher:{...Ot.launcher,...e.launcher,dock:{...(t=Ot.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ot.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ot.copy,...e.copy},sendButton:{...Ot.sendButton,...e.sendButton},statusIndicator:{...Ot.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ot.voiceRecognition,...e.voiceRecognition},features:(()=>{var ve,Me,Le,ne,ke,V,pe,fe;let w=(ve=Ot.features)==null?void 0:ve.artifacts,W=(Me=e.features)==null?void 0:Me.artifacts,F=(Le=Ot.features)==null?void 0:Le.scrollToBottom,_=(ne=e.features)==null?void 0:ne.scrollToBottom,B=(ke=Ot.features)==null?void 0:ke.streamAnimation,j=(V=e.features)==null?void 0:V.streamAnimation,q=(pe=Ot.features)==null?void 0:pe.askUserQuestion,re=(fe=e.features)==null?void 0:fe.askUserQuestion,Ie=w===void 0&&W===void 0?void 0:{...w,...W,layout:{...w==null?void 0:w.layout,...W==null?void 0:W.layout}},Re=F===void 0&&_===void 0?void 0:{...F,..._},Ne=B===void 0&&j===void 0?void 0:{...B,...j},ce=q===void 0&&re===void 0?void 0:{...q,...re,styles:{...q==null?void 0:q.styles,...re==null?void 0:re.styles}};return{...Ot.features,...e.features,...Re!==void 0?{scrollToBottom:Re}:{},...Ie!==void 0?{artifacts:Ie}:{},...Ne!==void 0?{streamAnimation:Ne}:{},...ce!==void 0?{askUserQuestion:ce}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ot.suggestionChips,suggestionChipsConfig:{...Ot.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ot.layout,...e.layout,header:{...(a=Ot.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ot.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Ot.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Ot.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(A=(E=e.layout)==null?void 0:E.messages)==null?void 0:A.timestamp}},slots:{...(I=Ot.layout)==null?void 0:I.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Ot.markdown,...e.markdown,options:{...(N=Ot.markdown)==null?void 0:N.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Ot.messageActions,...e.messageActions}}:Ot}var Op={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"}},Fp={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"}},_p={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:sr,maxWidth:ki,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:"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"},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 Jo(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let s of n){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Jo(e,r):r}function Pi(e){let t={};function n(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Jo(e,a);d!==void 0&&(t[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function $p(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function jp(e,t){let n={...e};for(let[r,s]of Object.entries(t)){let o=n[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?n[r]=jp(o,s):n[r]=s}return n}function hh(e,t){return t?jp(e,t):e}function Rs(e,t={}){var s,o,a,i,d,l,u,p,f,m,v,x,E;let n={palette:Op,semantic:Fp,components:_p},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...n.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:hh(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let A=$p(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(I=>I.message).join(", ")}`)}if(t.plugins)for(let A of t.plugins)r=A.transform(r);return r}function Ii(e){var x,E,A,I,P,N,L,w,W,F,_,B,j,q,re,Ie,Re,Ne,ce,ve,Me,Le,ne,ke,V,pe,fe,me,ue,Ge,z,te,We,ge,ie,ae,Qe,Ce,de,X,$e,Ct,G,Oe,Mn,Dt,ln,Hn,Xn,H,oe,Be,Xe,Fe,_e,rt,At,Ft,Kt,K,gt,nt,Ut,se,ye,wt,_t,Zt,yn,Tt,St,ht,bt,qt,et,Bn,Qn,bn,Dn,ut,xr,Nn,co,kn,Po,Fr,Tr,xt,On,Fn,xn,Pt,Yn,Zn,_n,_r,Mr,$r,$n,Wt,vn,er,jr,kr,Ur,vr,jn,lr,ft,Jt,Gt,Un,qr,tr,cr,qn;let t=Pi(e),n={};for(let[S,zn]of Object.entries(t)){let dr=S.replace(/\./g,"-");n[`--persona-${dr}`]=zn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(A=n["--persona-semantic-colors-accent"])!=null?A:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(I=n["--persona-semantic-colors-surface"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(N=n["--persona-semantic-colors-container"])!=null?N:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(L=n["--persona-semantic-colors-text"])!=null?L:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(w=n["--persona-semantic-colors-text-muted"])!=null?w:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(W=n["--persona-semantic-colors-text-inverse"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(_=n["--persona-semantic-colors-divider"])!=null?_:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(B=n["--persona-components-voice-recording-indicator"])!=null?B:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(j=n["--persona-components-voice-recording-background"])!=null?j:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(q=n["--persona-components-voice-processing-icon"])!=null?q:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(re=n["--persona-components-voice-speaking-icon"])!=null?re:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ie=n["--persona-components-approval-requested-background"])!=null?Ie:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Re=n["--persona-components-approval-requested-border"])!=null?Re:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(Ne=n["--persona-components-approval-requested-text"])!=null?Ne:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(ce=n["--persona-components-approval-approve-background"])!=null?ce:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(ve=n["--persona-components-approval-deny-background"])!=null?ve:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(Me=n["--persona-components-attachment-image-background"])!=null?Me:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(Le=n["--persona-components-attachment-image-border"])!=null?Le:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ne=n["--persona-semantic-typography-fontFamily"])!=null?ne:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ke=n["--persona-semantic-typography-fontSize"])!=null?ke:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(V=n["--persona-semantic-typography-fontWeight"])!=null?V:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(pe=n["--persona-semantic-typography-lineHeight"])!=null?pe:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(fe=n["--persona-palette-radius-sm"])!=null?fe:"0.125rem",n["--persona-radius-md"]=(me=n["--persona-palette-radius-md"])!=null?me:"0.375rem",n["--persona-radius-lg"]=(ue=n["--persona-palette-radius-lg"])!=null?ue:"0.5rem",n["--persona-radius-xl"]=(Ge=n["--persona-palette-radius-xl"])!=null?Ge:"0.75rem",n["--persona-radius-full"]=(z=n["--persona-palette-radius-full"])!=null?z:"9999px",n["--persona-launcher-radius"]=(We=(te=n["--persona-components-launcher-borderRadius"])!=null?te:n["--persona-palette-radius-full"])!=null?We:"9999px",n["--persona-launcher-bg"]=(ge=n["--persona-components-launcher-background"])!=null?ge:n["--persona-primary"],n["--persona-launcher-fg"]=(ie=n["--persona-components-launcher-foreground"])!=null?ie:n["--persona-text-inverse"],n["--persona-launcher-border"]=(ae=n["--persona-components-launcher-border"])!=null?ae:n["--persona-border"],n["--persona-button-primary-bg"]=(Qe=n["--persona-components-button-primary-background"])!=null?Qe:n["--persona-primary"],n["--persona-button-primary-fg"]=(Ce=n["--persona-components-button-primary-foreground"])!=null?Ce:n["--persona-text-inverse"],n["--persona-button-radius"]=(X=(de=n["--persona-components-button-primary-borderRadius"])!=null?de:n["--persona-palette-radius-full"])!=null?X:"9999px",n["--persona-panel-radius"]=(Ct=($e=n["--persona-components-panel-borderRadius"])!=null?$e:n["--persona-radius-xl"])!=null?Ct:"0.75rem",n["--persona-panel-border"]=(G=n["--persona-components-panel-border"])!=null?G:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Mn=(Oe=n["--persona-components-panel-shadow"])!=null?Oe:n["--persona-palette-shadows-xl"])!=null?Mn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-input-radius"]=(ln=(Dt=n["--persona-components-input-borderRadius"])!=null?Dt:n["--persona-radius-lg"])!=null?ln:"0.5rem",n["--persona-message-user-radius"]=(Xn=(Hn=n["--persona-components-message-user-borderRadius"])!=null?Hn:n["--persona-radius-lg"])!=null?Xn:"0.5rem",n["--persona-message-assistant-radius"]=(oe=(H=n["--persona-components-message-assistant-borderRadius"])!=null?H:n["--persona-radius-lg"])!=null?oe:"0.5rem",n["--persona-header-bg"]=(Be=n["--persona-components-header-background"])!=null?Be:n["--persona-surface"],n["--persona-header-border"]=(Xe=n["--persona-components-header-border"])!=null?Xe:n["--persona-divider"],n["--persona-header-icon-bg"]=(Fe=n["--persona-components-header-iconBackground"])!=null?Fe:n["--persona-primary"],n["--persona-header-icon-fg"]=(_e=n["--persona-components-header-iconForeground"])!=null?_e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(rt=n["--persona-components-header-titleForeground"])!=null?rt:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(At=n["--persona-components-header-subtitleForeground"])!=null?At:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ft=n["--persona-components-header-actionIconForeground"])!=null?Ft:n["--persona-muted"];let r=(Kt=e.components)==null?void 0:Kt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let s=(K=e.components)==null?void 0:K.introCard;n["--persona-intro-card-bg"]=(gt=n["--persona-components-introCard-background"])!=null?gt:n["--persona-surface"],n["--persona-intro-card-radius"]=(nt=n["--persona-components-introCard-borderRadius"])!=null?nt:"1rem",n["--persona-intro-card-padding"]=(Ut=n["--persona-components-introCard-padding"])!=null?Ut:"1.5rem",n["--persona-intro-card-shadow"]=(ye=(se=s==null?void 0:s.shadow)!=null?se:n["--persona-components-introCard-shadow"])!=null?ye:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(wt=n["--persona-components-input-background"])!=null?wt:n["--persona-surface"],n["--persona-input-placeholder"]=(_t=n["--persona-components-input-placeholder"])!=null?_t:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Zt=n["--persona-components-message-user-background"])!=null?Zt:n["--persona-accent"],n["--persona-message-user-text"]=(yn=n["--persona-components-message-user-text"])!=null?yn:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Tt=n["--persona-components-message-user-shadow"])!=null?Tt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(St=n["--persona-components-message-assistant-background"])!=null?St:n["--persona-surface"],n["--persona-message-assistant-text"]=(ht=n["--persona-components-message-assistant-text"])!=null?ht:n["--persona-text"],n["--persona-message-assistant-border"]=(bt=n["--persona-components-message-assistant-border"])!=null?bt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(qt=n["--persona-components-message-assistant-shadow"])!=null?qt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Bn=(et=n["--persona-components-scrollToBottom-background"])!=null?et:n["--persona-button-primary-bg"])!=null?Bn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bn=(Qn=n["--persona-components-scrollToBottom-foreground"])!=null?Qn:n["--persona-button-primary-fg"])!=null?bn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Dn=n["--persona-components-scrollToBottom-border"])!=null?Dn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ut=n["--persona-components-scrollToBottom-size"])!=null?ut:"40px",n["--persona-scroll-to-bottom-radius"]=(co=(Nn=(xr=n["--persona-components-scrollToBottom-borderRadius"])!=null?xr:n["--persona-button-radius"])!=null?Nn:n["--persona-radius-full"])!=null?co:"9999px",n["--persona-scroll-to-bottom-shadow"]=(Po=(kn=n["--persona-components-scrollToBottom-shadow"])!=null?kn:n["--persona-palette-shadows-sm"])!=null?Po:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Fr=n["--persona-components-scrollToBottom-padding"])!=null?Fr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Tr=n["--persona-components-scrollToBottom-gap"])!=null?Tr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(On=(xt=n["--persona-components-scrollToBottom-fontSize"])!=null?xt:n["--persona-palette-typography-fontSize-sm"])!=null?On:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Fn=n["--persona-components-scrollToBottom-iconSize"])!=null?Fn:"14px",n["--persona-tool-bubble-shadow"]=(xn=n["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Pt=n["--persona-components-reasoningBubble-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Yn=n["--persona-components-composer-shadow"])!=null?Yn:"none",n["--persona-md-inline-code-bg"]=(Zn=n["--persona-components-markdown-inlineCode-background"])!=null?Zn:n["--persona-container"],n["--persona-md-inline-code-color"]=(_n=n["--persona-components-markdown-inlineCode-foreground"])!=null?_n:n["--persona-text"],n["--persona-md-link-color"]=(Mr=(_r=n["--persona-components-markdown-link-foreground"])!=null?_r:n["--persona-accent"])!=null?Mr:"#0f0f0f";let o=n["--persona-components-markdown-heading-h1-fontSize"];o&&(n["--persona-md-h1-size"]=o);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=($r=n["--persona-components-markdown-codeBlock-background"])!=null?$r:n["--persona-container"],n["--persona-md-code-block-border-color"]=($n=n["--persona-components-markdown-codeBlock-borderColor"])!=null?$n:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Wt=n["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",n["--persona-md-table-header-bg"]=(vn=n["--persona-components-markdown-table-headerBackground"])!=null?vn:n["--persona-container"],n["--persona-md-table-border-color"]=(er=n["--persona-components-markdown-table-borderColor"])!=null?er:n["--persona-border"],n["--persona-md-hr-color"]=(jr=n["--persona-components-markdown-hr-color"])!=null?jr:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(kr=n["--persona-components-markdown-blockquote-borderColor"])!=null?kr:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Ur=n["--persona-components-markdown-blockquote-background"])!=null?Ur:"transparent",n["--persona-md-blockquote-text-color"]=(vr=n["--persona-components-markdown-blockquote-textColor"])!=null?vr:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(jn=n["--persona-components-collapsibleWidget-container"])!=null?jn:n["--persona-surface"],n["--cw-surface"]=(lr=n["--persona-components-collapsibleWidget-surface"])!=null?lr:n["--persona-surface"],n["--cw-border"]=(ft=n["--persona-components-collapsibleWidget-border"])!=null?ft:n["--persona-border"],n["--persona-message-border"]=(Jt=n["--persona-components-message-border"])!=null?Jt:n["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(n["--persona-icon-btn-bg"]=p.background),p.border&&(n["--persona-icon-btn-border"]=p.border),p.color&&(n["--persona-icon-btn-color"]=p.color),p.padding&&(n["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(n["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(n["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(n["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(n["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let S=v.toolbar;S.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,n["--persona-dropdown-bg"]=(Gt=n["--persona-dropdown-bg"])!=null?Gt:S.copyMenuBackground),S.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,n["--persona-dropdown-border"]=(Un=n["--persona-dropdown-border"])!=null?Un:S.copyMenuBorder),S.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,n["--persona-dropdown-shadow"]=(qr=n["--persona-dropdown-shadow"])!=null?qr:S.copyMenuShadow),S.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(tr=n["--persona-dropdown-radius"])!=null?tr:S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(cr=n["--persona-dropdown-item-hover-bg"])!=null?cr:S.copyMenuItemHoverBackground),S.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(v!=null&&v.tab){let S=v.tab;S.background&&(n["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(n["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(n["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(n["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(n["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(n["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(n["--persona-artifact-tab-list-padding"]=S.listPadding)}if(v!=null&&v.pane){let S=v.pane;if(S.toolbarBackground){let zn=(qn=Jo(e,S.toolbarBackground))!=null?qn:S.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zn}}return n}var yh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var bh={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"}}},Up=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ba=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},xh=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ba()},qp=e=>xh(e),vh=e=>Rs(e),wh=e=>{var n;let t=Rs(void 0,{validate:!1});return Rs({...e,palette:{...t.palette,colors:{...bh.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},Hs=e=>{let t=qp(e),n=Up(e==null?void 0:e.theme),r=Up(e==null?void 0:e.darkTheme);return t==="dark"?wh(Ws(n!=null?n:{},r!=null?r:{})):vh(n)},Ch=e=>Ii(e),Eo=(e,t)=>{var o;let n=Hs(t),r=Ch(n);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=t==null?void 0:t.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Wi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ba())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ba());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Ah}from"idiomorph";var Da=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Ah.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Na={index:-1,draft:""};function zp(e){let{direction:t,history:n,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(n.length===0)return{handled:!1,state:o};if(t==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<n.length-1){let i=o.index+1;return{handled:!0,value:n[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Na}}}function Vp(e,t){var n,r,s,o,a,i,d,l,u,p,f,m,v,x,E,A,I,P,N,L,w,W,F,_,B,j,q,re,Ie,Re,Ne,ce,ve,Me,Le,ne,ke,V;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(E=(x=e.toolCall)==null?void 0:x.name)!=null?E:"",(P=(I=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:I.length)!=null?P:0,(W=(w=(L=(N=e.toolCall)==null?void 0:N.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?W:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:(_=e.toolCall)!=null&&_.args?JSON.stringify(e.toolCall.args).length:0,(q=(j=(B=e.reasoning)==null?void 0:B.chunks)==null?void 0:j.length)!=null?q:0,(Ne=(Re=(Ie=(re=e.reasoning)==null?void 0:re.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:Re.length)!=null?Ne:0,(Le=(Me=(ve=(ce=e.reasoning)==null?void 0:ce.chunks)==null?void 0:ve[e.reasoning.chunks.length-1])==null?void 0:Me.slice(-32))!=null?Le:"",(ke=(ne=e.contentParts)==null?void 0:ne.length)!=null?ke:0,(V=e.stopReason)!=null?V:"",t].join("\0")}function Kp(){return new Map}function Jp(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Gp(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Xp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Oa(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Bs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ds(e,t){return Bs(e)-e.scrollTop<=t}function Fa(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:n}:!t&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function _a(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&r?"resume":"none"}var fn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},hn=1e5,Zr=hn+1;var Ns={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Sh=["pre","code","a","script","style"],$a=e=>{var t,n,r,s,o;return{type:(t=e==null?void 0:e.type)!=null?t:Ns.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:Ns.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ns.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Ns.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Ns.buffer}},Yp=[{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"}],Os=new Map;for(let e of Yp)Os.set(e.name,e);var Eh=e=>{Os.set(e.name,e)},Th=e=>{Yp.some(t=>t.name===e)||Os.delete(e)},Mh=()=>Array.from(Os.keys()),Fs=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=Os.get(e))!=null?r:null},ja=(e,t,n,r,s)=>{if(!s)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(t==="line"){let o=e.lastIndexOf(`
15
+ `);return o<0?"":e.slice(0,o)}return e},kh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=t,s},Lh=(e,t,n,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=t,s},Ri=/\s/,Ph=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Ih=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(Ri.test(o[i])){let l=i;for(;l<o.length&&Ri.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!Ri.test(o[u]);)l.appendChild(kh(r,o[u],t,n.value)),n.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},Wh=(e,t,n)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Lh(r,l,t,n.value)),n.value+=1));s.replaceChild(a,e)},_s=(e,t,n,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((p=r==null?void 0:r.skipTags)!=null?p:Sh).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Ph(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=t==="char"?Ih:Wh;for(let m of i)u(m,n,l);return s.innerHTML},Ua=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},$s=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Qp=new WeakMap,Rh=(e,t)=>{var o;if(!e.styles)return;let n=Qp.get(t);if(n||(n=new Set,Qp.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:(o=t.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},Hi=new WeakMap,Hh=(e,t)=>{if(!e.onAttach)return;let n=Hi.get(t);if(n||(n=new Map,Hi.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Zp=e=>{let t=Hi.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Bi=(e,t)=>{Rh(e,t),Hh(e,t)};function Di(e,t=hn){let n=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=s}}var js=0,eo=null;function Ni(e=document){var n;if(js++,js===1){let r=e.body,o=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;eo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,js=Math.max(0,js-1),js===0&&eo)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=eo.originalOverflow,s.style.position=eo.originalPosition,s.style.top=eo.originalTop,s.style.width=eo.originalWidth,o.scrollTo(0,eo.scrollY),eo=null}}}var qa={side:"right",width:"420px",animate:!0,reveal:"resize"},an=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},to=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},yr=e=>{var n,r,s,o,a;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:qa.side,width:(s=t==null?void 0:t.width)!=null?s:qa.width,animate:(o=t==null?void 0:t.animate)!=null?o:qa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:qa.reveal}};var br={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Us=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
16
16
  <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>
17
17
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
18
18
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -20,14 +20,14 @@ _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;this
20
20
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
21
21
  </span>
22
22
  <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>
23
- `,t.addEventListener("click",n);let r=o=>{var R,H,L,w,B,F,$,W,O,V,oe,Ie,Pe,ze;let a=(R=o.launcher)!=null?R:{},i=on(o),d=t.querySelector("[data-role='launcher-title']");if(d){let pe=(H=a.title)!=null?H:"Chat Assistant";d.textContent=pe,d.setAttribute("title",pe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let pe=(L=a.subtitle)!=null?L:"Get answers fast";l.textContent=pe,l.setAttribute("title",pe)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let pe=(w=a.agentIconSize)!=null?w:"40px";if(p.style.height=pe,p.style.width=pe,p.innerHTML="",a.agentIconName){let ce=parseFloat(pe)||24,Ee=fe(a.agentIconName,ce*.6,"var(--persona-text-inverse, #ffffff)",2);Ee?(p.appendChild(Ee),p.style.display=""):(p.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let pe=($=a.agentIconSize)!=null?$:"40px";f.style.height=pe,f.style.width=pe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let pe=(W=a.callToActionIconSize)!=null?W:"32px";m.style.height=pe,m.style.width=pe,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let ce=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ce=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Ee=parseFloat(pe)||24,je=Math.max(Ee-ce,8),te=fe(a.callToActionIconName,je,"currentColor",2);te?m.appendChild(te):m.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&cr[a.position]?cr[a.position]:cr["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",S="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?S:`${x} ${v}`,i||(t.style.zIndex=String((oe=a.zIndex)!=null?oe:gn));let A="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Ie=a.border)!=null?Ie:A,t.style.boxShadow=(Pe=a.shadow)!=null?Pe:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(ze=a.collapsedMaxWidth)!=null?ze:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Th="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ja=(e,n={})=>{var x,S,A,k,R,H;let{showClose:t=!0,wrapperClassName:r=Th,buttonSize:s,iconSize:o="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(S=s!=null?s:a.closeButtonSize)!=null?S:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(A=a.closeButtonTooltipText)!=null?A:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(R=a.closeButtonIconName)!=null?R:"x",m=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||An.actionIconColor;let v=fe(f,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let L=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${L} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let L=null,w=()=>{if(L)return;let F=l.ownerDocument,$=F.body;if(!$)return;L=br(F,"div","persona-clear-chat-tooltip"),L.textContent=u;let W=br(F,"div");W.className="persona-clear-chat-tooltip-arrow",L.appendChild(W);let O=l.getBoundingClientRect();L.style.position="fixed",L.style.zIndex=String(Yr),L.style.left=`${O.left+O.width/2}px`,L.style.top=`${O.top-8}px`,L.style.transform="translate(-50%, -100%)",$.appendChild(L)},B=()=>{L&&L.parentNode&&(L.parentNode.removeChild(L),L=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",B),l.addEventListener("focus",w),l.addEventListener("blur",B),d._cleanupTooltip=()=>{B(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",B),l.removeEventListener("focus",w),l.removeEventListener("blur",B)}}return{button:l,wrapper:d}},Mh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ua=(e,n={})=>{var L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe;let{wrapperClassName:t=Mh,buttonSize:r,iconSize:s="20px"}=n,a=(w=((L=e==null?void 0:e.launcher)!=null?L:{}).clearChat)!=null?w:{},i=(B=r!=null?r:a.size)!=null?B:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",l=($=a.iconColor)!=null?$:"",u=(W=a.backgroundColor)!=null?W:"",p=(O=a.borderWidth)!=null?O:"",f=(V=a.borderColor)!=null?V:"",m=(oe=a.borderRadius)!=null?oe:"",v=(Ie=a.paddingX)!=null?Ie:"",x=(Pe=a.paddingY)!=null?Pe:"",S=(ze=a.tooltipText)!=null?ze:"Clear chat",A=(pe=a.showTooltip)!=null?pe:!0,k=h("div",t),R=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");R.style.height=i,R.style.width=i,R.type="button",R.setAttribute("aria-label",S),R.style.color=l||An.actionIconColor;let H=fe(d,s,"currentColor",1);if(H&&(H.style.display="block",R.appendChild(H)),u&&(R.style.backgroundColor=u,R.classList.remove("hover:persona-bg-gray-100")),p||f){let ce=p||"0px",Ee=f||"transparent";R.style.border=`${ce} solid ${Ee}`,R.classList.remove("persona-border-none")}if(m&&(R.style.borderRadius=m,R.classList.remove("persona-rounded-full")),v&&(R.style.paddingLeft=v,R.style.paddingRight=v),x&&(R.style.paddingTop=x,R.style.paddingBottom=x),k.appendChild(R),A&&S){let ce=null,Ee=()=>{if(ce)return;let te=R.ownerDocument,xe=te.body;if(!xe)return;ce=br(te,"div","persona-clear-chat-tooltip"),ce.textContent=S;let G=br(te,"div");G.className="persona-clear-chat-tooltip-arrow",ce.appendChild(G);let ae=R.getBoundingClientRect();ce.style.position="fixed",ce.style.zIndex=String(Yr),ce.style.left=`${ae.left+ae.width/2}px`,ce.style.top=`${ae.top-8}px`,ce.style.transform="translate(-50%, -100%)",xe.appendChild(ce)},je=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};k.addEventListener("mouseenter",Ee),k.addEventListener("mouseleave",je),R.addEventListener("focus",Ee),R.addEventListener("blur",je),k._cleanupTooltip=()=>{je(),k.removeEventListener("mouseenter",Ee),k.removeEventListener("mouseleave",je),R.removeEventListener("focus",Ee),R.removeEventListener("blur",je)}}return{button:R,wrapper:k}};var An={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))"},eo=e=>{var L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe,ce,Ee,je;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(L=n==null?void 0:n.launcher)!=null?L:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(B=s.closeButtonPlacement)!=null?B:"inline",i=(F=s.headerIconHidden)!=null?F:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let te=parseFloat(o)||24,xe=fe(d,te*.6,"currentColor",1);xe?l.replaceChildren(xe):l.textContent=(W=($=n==null?void 0:n.launcher)==null?void 0:$.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=n==null?void 0:n.launcher)!=null&&O.iconUrl){let te=h("img");te.src=n.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=o,te.style.width=o,l.replaceChildren(te)}else l.textContent=(oe=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?oe:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=An.titleColor,p.textContent=(Pe=(Ie=n==null?void 0:n.launcher)==null?void 0:Ie.title)!=null?Pe:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=An.subtitleColor,f.textContent=(pe=(ze=n==null?void 0:n.launcher)==null?void 0:ze.subtitle)!=null?pe:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let m=(ce=s.clearChat)!=null?ce:{},v=(Ee=m.enabled)!=null?Ee:!0,x=(je=m.placement)!=null?je:"inline",S=null,A=null;if(v){let xe=Ua(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=xe.button,A=xe.wrapper,x==="top-right"&&(A.style.right="48px"),x==="inline"&&r.appendChild(A)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:H}=ja(n,{showClose:t,wrapperClassName:k});return a!=="top-right"&&r.appendChild(H),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:R,closeButtonWrapper:H,clearChatButton:S,clearChatButtonWrapper:A}},Vo=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Eo(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Yr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of n){if(m.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let S=fe(m.icon,16,"currentColor",1.5);S&&v.appendChild(S)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",S=>{S.stopPropagation(),u(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function _t(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=fe(n,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function qa(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=fe(n,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function za(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=_t({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function Hi(e){var m,v;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let u=h("span","persona-combo-btn-label");u.textContent=n,l.appendChild(u);let p=fe(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,S;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Eo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let S=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Jp=e=>{var r;let n=eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function kh(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=fe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=Eo({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Gp=e=>{var k,R,H,L,w,B,F,$,W;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=n==null?void 0:n.launcher)!=null?k:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=Hi({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=An.titleColor,u=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=An.titleColor,u.textContent=(L=a.title)!=null?L:"Chat Assistant",l.appendChild(u),kh(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||V()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let O=s==null?void 0:s.titleRowHover;O&&(l.style.borderRadius=(B=O.borderRadius)!=null?B:"10px",l.style.padding=(F=O.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,oe;l.style.backgroundColor=(V=O.background)!=null?V:"",l.style.borderColor=(oe=O.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=($=a.closeButtonSize)!=null?$:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||An.actionIconColor;let v=(W=a.closeButtonIconName)!=null?W:"x",x=fe(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let S=h("div");S.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:S,headerTitle:u,headerSubtitle:A,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Bi={default:Jp,minimal:Gp},Xp=e=>{var n;return(n=Bi[e])!=null?n:Bi.default},_s=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Xp(r)({config:e,showClose:(d=(i=n==null?void 0:n.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:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Va=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},Ka=e=>{var L,w,B,F,$,W,O,V,oe,Ie,Pe,ze;let n=(L=e==null?void 0:e.sendButton)!=null?L:{},t=(w=n.useIcon)!=null?w:!1,r=(B=n.iconText)!=null?B:"\u2191",s=n.iconName,o=(F=n.stopIconName)!=null?F:"square",a=($=n.tooltipText)!=null?$:"Send message",i=(W=n.stopTooltipText)!=null?W:"Stop generating",d=(V=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?V:"Send",l=(Ie=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?Ie:"Stop",u=(Pe=n.showTooltip)!=null?Pe:!1,p=(ze=n.size)!=null?ze:"40px",f=n.backgroundColor,m=n.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",t?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let S=null,A=null;if(t){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let pe=parseFloat(p)||24,ce=(m==null?void 0:m.trim())||"currentColor";s?(S=fe(s,pe,ce,2),S?x.appendChild(S):x.textContent=r):x.textContent=r,A=fe(o,pe,ce,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let k=null;u&&a&&(k=h("div","persona-send-button-tooltip"),k.textContent=a,v.appendChild(k)),x.setAttribute("aria-label",a),v.appendChild(x);let R="send";return{button:x,wrapper:v,setMode:pe=>{if(pe===R)return;R=pe;let ce=pe==="stop"?i:a;if(x.setAttribute("aria-label",ce),k&&(k.textContent=ce),t){if(S&&A){let Ee=pe==="stop"?A:S;x.replaceChildren(Ee)}}else x.textContent=pe==="stop"?l:d}}},Ja=e=>{var k,R,H,L,w,B,F,$,W,O,V,oe;let n=(k=e==null?void 0:e.voiceRecognition)!=null?k:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((R=n.provider)==null?void 0:R.type)==="runtype";if(!(r||s))return null;let a=(L=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?L:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=n.iconName)!=null?w:"mic",u=(B=n.iconSize)!=null?B:a,p=parseFloat(u)||24,f=($=n.backgroundColor)!=null?$:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,m=(O=n.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=fe(l,p,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let S=(V=n.tooltipText)!=null?V:"Start voice recognition";if(((oe=n.showTooltip)!=null?oe:!1)&&S){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=S,i.appendChild(Ie)}return{button:d,wrapper:i}},Ga=e=>{var v,x,S,A,k,R,H,L;let n=(v=e==null?void 0:e.attachments)!=null?v:{};if(n.enabled!==!0)return null;let t=(S=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?S:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((A=n.allowedTypes)!=null?A:Rr).join(","),s.multiple=((k=n.maxFiles)!=null?k:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(R=n.buttonTooltipText)!=null?R:"Attach file");let i=(H=n.buttonIconName)!=null?H:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=fe(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let f=(L=n.buttonTooltipText)!=null?L:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},Xa=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},Ya=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var js=e=>{var v,x,S,A,k,R;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=Ya(),s=h("form","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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Va(n);a();let i=Ka(n),d=Ja(n),l=Ga(n),u=Xa(n);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),p.append(f,m),s.append(p),s.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,u),{footer:t,suggestions:r,composerForm:s,textarea:o,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:u,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:p,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var Yp=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=fe("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=fe("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},Qp=e=>{var v,x,S,A,k,R;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=Ya();r.style.display="none";let s=Xa(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=Va(n);o.style.maxHeight="100px",a();let i=Ka(n),d=Ja(n),l=Ga(n);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&t.append(l.previewsContainer),t.append(u,r,s);let m=u;return{footer:t,suggestions:r,composerForm:u,textarea:o,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:s,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Zp=e=>{var u,p,f,m,v,x,S,A,k,R,H,L,w,B,F,$,W;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=on(e);if(Zr(e)){let O=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},V=h("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=O.expandedSize)!=null?v:"anchored",V.style.zIndex=String((S=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?S:gn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",V.appendChild(oe);let Ie=h("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(A=O.expandedSize)!=null?A:"anchored",Ie.style.zIndex=String((R=(k=e==null?void 0:e.launcher)==null?void 0:k.zIndex)!=null?R:gn),{wrapper:V,panel:oe,pillRoot:Ie}}if(t){let O=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(V),{wrapper:O,panel:V}}if(!n){let O=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(L=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?L:"100%";return O.style.width=oe,V.style.width="100%",O.appendChild(V),{wrapper:O,panel:V}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&cr[s.position]?cr[s.position]:cr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((F=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?F:gn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:Gn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Lh=(e,n)=>{var H,L,w,B,F,$,W,O,V;let t=h("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:s}=ja(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(L=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:L.enabled)!=null?w:!0,a=null,i=null;if(o){let oe=Ua(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","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");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(F=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?F:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(W=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",u.append(p,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let S=h("div","persona-composer-overlay persona-pointer-events-none");S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20";let A=Qp({config:e}),{root:k,textNode:R}=Yp();return t.append(d,s,l,S),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:m,composerOverlay:S,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:k,peekTextNode:R}},eu=(e,n=!0)=>{var S,A,k,R,H,L,w,B,F;if(Zr(e))return Lh(e,n);let t=h("div","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");t.setAttribute("data-persona-theme-zone","container");let r=(S=e==null?void 0:e.layout)==null?void 0:S.header,s=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,o=r?_s(e,r,{showClose:n}):eo({config:e,showClose:n}),a=h("div","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");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(R=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?R:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(L=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((B=e==null?void 0:e.copy)==null?void 0:B.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=js({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;s?Vo(t,o,e):(o.header.style.display="none",Vo(t,o,e)),t.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(m.footer.style.display="none"),t.append(m.footer),t.append(x),{container:t,body:a,messagesWrapper:u,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Ph=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Ih=(e,n)=>{if(!e)return null;let t=Ph(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},Wh=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},Rh=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Di=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},Ni=320,nu=320,Hh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Bh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),Dh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),Nh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),Oh=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ni}px`,l.style.maxHeight=`${nu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),Rh(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},Fh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!Di(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ni}px`,n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},$h=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!Di(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ni}px`,s.style.maxHeight=`${nu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},_h=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!Di(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Ko=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="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 s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},ru=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Ko};if(n){let s=n(r);if(s!==null)return s}return Ko()},jh=(e,n)=>{let t=h("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=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},tu=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Uh=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="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"),e==="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"),e==="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},ou=(e,n,t)=>{var m,v,x,S,A,k;let r=(m=n.showCopy)!=null?m:!0,s=(v=n.showUpvote)!=null?v:!0,o=(x=n.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let R=h("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(S=n.visibility)!=null?S:"hover",i=(A=n.align)!=null?A:"right",d=(k=n.layout)!=null?k:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(R,H,L)=>{let w=_t({icon:R,label:H,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",L),w};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Us=(e,n,t,r,s,o)=>{var te,xe,G,ae,He,ue,Re,tt,K,se,Oe,J,z,we,$e,ne,Te;let a=t!=null?t:{},i=(te=a.layout)!=null?te:"bubble",d=a.avatar,l=a.timestamp,u=(xe=d==null?void 0:d.show)!=null?xe:!1,p=(G=l==null?void 0:l.show)!=null?G:!1,f=(ae=d==null?void 0:d.position)!=null?ae:"left",m=(He=l==null?void 0:l.position)!=null?He:"below",v=Uh(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Hh(e),A=(Re=(ue=e.content)==null?void 0:ue.trim())!=null?Re:"",R=S.length>0&&A===Ea,H=Oa((K=(tt=o==null?void 0:o.widgetConfig)==null?void 0:tt.features)==null?void 0:K.streamAnimation),L=(J=(Oe=(se=o==null?void 0:o.widgetConfig)==null?void 0:se.features)==null?void 0:Oe.streamAnimation)==null?void 0:J.plugins,w=e.role==="assistant"&&H.type!=="none"?Ds(H.type,L):null,B=e.role==="assistant"&&((z=w==null?void 0:w.isAnimating)==null?void 0:z.call(w,e))===!0,F=e.role==="assistant"&&w!==null&&(!!e.streaming||B);F&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),F&&w&&(w.containerClass&&$.classList.add(w.containerClass),$.style.setProperty("--persona-stream-step",`${H.speed}ms`),$.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let W=F?Fa((we=e.content)!=null?we:"",H.buffer,w,e,!!e.streaming):($e=e.content)!=null?$e:"",O=n({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=O;F&&(w==null?void 0:w.wrap)==="char"?V=Ns(O,"char",e.id,{skipTags:w.skipTags}):F&&(w==null?void 0:w.wrap)==="word"&&(V=Ns(O,"word",e.id,{skipTags:w.skipTags}));let oe=null;if(R?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",$.appendChild(oe)):$.innerHTML=V,F&&(w!=null&&w.useCaret)&&!R&&A){let ve=$a(),Ht=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),ie=Ht[Ht.length-1];if(ie!=null&&ie.parentNode)ie.parentNode.insertBefore(ve,ie.nextSibling);else{let re=$.lastElementChild;re?re.appendChild(ve):$.appendChild(ve)}}if(p&&m==="inline"&&e.createdAt){let ve=tu(e,l);ve.classList.add("persona-ml-2","persona-inline"),$.appendChild(ve)}if(S.length>0){let ve=Oh(S,!R&&!!A,()=>{R&&oe&&(oe.style.display="")});ve?x.appendChild(ve):R&&oe&&(oe.style.display="")}let Ie=Bh(e);if(Ie.length>0){let ve=Fh(Ie);ve&&x.appendChild(ve)}let Pe=Dh(e);if(Pe.length>0){let ve=$h(Pe);ve&&x.appendChild(ve)}let ze=Nh(e);if(ze.length>0){let ve=_h(ze);ve&&x.appendChild(ve)}if(x.appendChild($),p&&m==="below"&&e.createdAt){let ve=tu(e,l);ve.classList.add("persona-mt-1"),x.appendChild(ve)}let pe=e.role==="assistant"?Ih(e.stopReason,(Te=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.copy)==null?void 0:Te.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ve=!!(W&&W.trim()),Ht=H.placeholder==="skeleton",ie=Ht&&H.buffer==="line"&&ve;if(ve)ie&&x.appendChild(Os());else if(Ht)x.appendChild(Os());else{let re=ru("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);re&&x.appendChild(re)}}if(pe&&e.stopReason&&!e.streaming&&(A||($.style.display="none"),x.appendChild(Wh(e.stopReason,pe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let ve=ou(e,r,s);x.appendChild(ve)}if(!u||e.role==="system")return x;let Ee=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),je=jh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Ee.append(x,je):Ee.append(je,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ee},qh=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Us(e,n,t,r,s,o)};var Jo=new Set,zh=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Vh=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
24
- `):""},su=(e,n)=>{let t=Jo.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)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 l=fe(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Oi=(e,n)=>{var Pe,ze,pe,ce,Ee,je,te,xe,G,ae,He;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let s=(ze=(Pe=n==null?void 0:n.features)==null?void 0:Pe.reasoningDisplay)!=null?ze:{},o=s.expandable!==!1,a=o&&Jo.has(e.id),i=t.status!=="complete",d=Vh(e,(pe=s.previewMaxLines)!=null?pe:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(ce=n==null?void 0:n.reasoning)!=null?ce:{},v=String((Ee=t.startedAt)!=null?Ee:Date.now()),x=()=>{let ue=h("span","");return ue.setAttribute("data-tool-elapsed",v),ue.textContent=wa(t),ue},S=(je=m.renderCollapsedSummary)==null?void 0:je.call(m,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:wa(t),createElapsedElement:x});typeof S=="string"&&S.trim()?(p.textContent=S,u.appendChild(p)):S instanceof HTMLElement?u.appendChild(S):(p.textContent=f,u.appendChild(p));let A=h("span","persona-text-xs persona-text-persona-primary");A.textContent=Cp(t),u.appendChild(A);let k=(te=s.loadingAnimation)!=null?te:"none",R=m.activeTextTemplate,H=m.completeTextTemplate,L=i?R:H,w=S instanceof HTMLElement,B=(ue,Re,tt)=>{let K=tt;for(let se of Re){let Oe=h("span","persona-tool-char");Oe.style.setProperty("--char-index",String(K)),Oe.textContent=se===" "?"\xA0":se,ue.appendChild(Oe),K++}return K},F=(ue,Re)=>{p.textContent="";let tt=Ca(ue,""),K=0;for(let se of tt){let Oe=se.styles.length>0?(()=>{let J=h("span",se.styles.map(z=>`persona-tool-text-${z}`).join(" "));return p.appendChild(J),J})():p;if(se.isDuration&&i)Oe.appendChild(x());else{let J=se.isDuration?wa(t):se.text;Re?K=B(Oe,J,K):Oe.appendChild(document.createTextNode(J))}}};if(!w&&L)if(A.style.display="none",p.style.display="",i&&k!=="none"){let ue=(xe=m.loadingAnimationDuration)!=null?xe:2e3;p.setAttribute("data-preserve-animation","true"),k==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),F(L,!1)):(p.classList.add(`persona-tool-loading-${k}`),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),k==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),F(L,!0))}else F(L,!1);else if(!w&&i&&k!=="none"){p.style.display="";let ue=(G=m.loadingAnimationDuration)!=null?G:2e3;if(p.setAttribute("data-preserve-animation","true"),k==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`);else{p.classList.add(`persona-tool-loading-${k}`),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),k==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Re=p.textContent||f;p.textContent="",B(p,Re,0)}t.status==="complete"&&(p.style.display="none")}else w||(t.status==="complete"?p.style.display="none":p.style.display="");let $=null;if(o){$=h("div","persona-flex persona-items-center");let Re=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?$.appendChild(Re):$.textContent=a?"Hide":"Show";let tt=h("div","persona-flex persona-items-center persona-ml-auto");tt.append($),l.append(u,tt)}else l.append(u);let W=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let ue=(He=(ae=n==null?void 0:n.reasoning)==null?void 0:ae.renderCollapsedPreview)==null?void 0:He.call(ae,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});zh(W,ue)||(W.textContent=d),W.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,W),r;let O=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let V=t.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let Re=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?$.appendChild(Re):$.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(l,W,O),r};var Go=new Set,Kh=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Jh=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
25
- `);let s=$o(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
26
- `):""},Gh=(e,n)=>{var u,p,f,m,v;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=Jh(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?Ap(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(m=n==null?void 0:n.toolCall)!=null?m:{},l=a;return s==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=yi(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=yi(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},au=(e,n,t)=>{var u;let r=Go.has(e),s=(u=t==null?void 0:t.toolCall)!=null?u:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=fe(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Fi=(e,n)=>{var V,oe,Ie,Pe,ze,pe,ce,Ee,je;let t=e.toolCall,r=(V=n==null?void 0:n.toolCall)!=null?V:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(Ie=(oe=n==null?void 0:n.features)==null?void 0:oe.toolCallDisplay)!=null?Ie:{},a=o.expandable!==!1,i=a&&Go.has(e.id),{summary:d,previewText:l,isActive:u}=Gh(e,n),p=h("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");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((Pe=t.startedAt)!=null?Pe:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",v),te.textContent=Es(t),te},S=(pe=r.renderCollapsedSummary)==null?void 0:pe.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(ze=o.collapsedMode)!=null?ze:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Es(t),createElapsedElement:x});typeof S=="string"&&S.trim()?(m.textContent=S,f.appendChild(m)):S instanceof HTMLElement?f.appendChild(S):(m.textContent=d,f.appendChild(m));let A=(ce=o.loadingAnimation)!=null?ce:"none",k=r.activeTextTemplate,R=r.completeTextTemplate,H=u?k:R,L=S instanceof HTMLElement,w=(te,xe,G)=>{let ae=G;for(let He of xe){let ue=h("span","persona-tool-char");ue.style.setProperty("--char-index",String(ae)),ue.textContent=He===" "?"\xA0":He,te.appendChild(ue),ae++}return ae},B=(te,xe)=>{var ue;m.textContent="";let G=((ue=t.name)==null?void 0:ue.trim())||"tool",ae=Ca(te,G),He=0;for(let Re of ae){let tt=Re.styles.length>0?(()=>{let K=h("span",Re.styles.map(se=>`persona-tool-text-${se}`).join(" "));return m.appendChild(K),K})():m;if(Re.isDuration&&u)tt.appendChild(x());else{let K=Re.isDuration?Es(t):Re.text;xe?He=w(tt,K,He):tt.appendChild(document.createTextNode(K))}}};if(!L)if(u&&A!=="none"){let te=(Ee=r.loadingAnimationDuration)!=null?Ee:2e3;if(m.setAttribute("data-preserve-animation","true"),A==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${te}ms`),H&&B(H,!1);else if(m.classList.add(`persona-tool-loading-${A}`),m.style.setProperty("--persona-tool-anim-duration",`${te}ms`),A==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),H)B(H,!0);else{let xe=m.textContent||d;m.textContent="",w(m,xe,0)}}else H&&B(H,!1);let F=null;if(a){F=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",xe=fe(i?"chevron-up":"chevron-down",16,te,2);xe?F.appendChild(xe):F.textContent=i?"Hide":"Show";let G=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");G.append(F),p.append(f,G)}else p.append(f);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let te=(je=r.renderCollapsedPreview)==null?void 0:je.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});Kh($,te)||($.textContent=l),$.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,$),s;let W=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),t.name){let te=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?te.style.color=r.contentTextColor:r.headerTextColor&&(te.style.color=r.headerTextColor),te.textContent=t.name,W.appendChild(te)}if(t.args!==void 0){let te=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Arguments";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(G.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(G.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(G.style.color=r.codeBlockTextColor),G.textContent=$o(t.args),te.append(xe,G),W.appendChild(te)}if(t.chunks&&t.chunks.length){let te=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Activity";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(G.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(G.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(G.style.color=r.codeBlockTextColor),G.textContent=t.chunks.join(""),te.append(xe,G),W.appendChild(te)}if(t.status==="complete"&&t.result!==void 0){let te=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Result";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(G.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(G.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(G.style.color=r.codeBlockTextColor),G.textContent=$o(t.result),te.append(xe,G),W.appendChild(te)}if(t.status==="complete"&&typeof t.duration=="number"){let te=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(te.style.color=r.contentTextColor),te.textContent=`Duration: ${t.duration}ms`,W.appendChild(te)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",xe=fe(i?"chevron-up":"chevron-down",16,te,2);xe?F.appendChild(xe):F.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(p,$,W),s};import{parse as Xh,ARR as Yh,OBJ as Qh,STR as Zh}from"partial-json";var lu="ask_user_question",$i=8,Xo="data-persona-ask-sheet-for",ey="Other",ty="Other\u2026",cu="Type your own answer here",du="Send",ny="Next",ry="Back",oy="Submit all",sy="Skip",ay=3,_i="data-ask-current-index",ji="data-ask-question-count",pu="data-ask-answers",Ui="data-ask-grouped",uu="data-ask-layout",iy=e=>e.layout==="pills"?"pills":"rows",ly=e=>e.getAttribute(uu)==="pills"?"pills":"rows",iu=!1,mu=e=>e.replace(/["\\]/g,"\\$&"),to=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===lu,Qa=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},no=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=Xh(s,Zh|Qh|Yh);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},qs=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>$i&&!iu&&(iu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${$i}.`)),n.slice(0,$i)},cy=e=>{var n;return(n=qs(e)[0])!=null?n:null},dy=(e,n)=>{var t;return(t=qs(e)[n])!=null?t:null},gu=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},fu=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},py=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=fu(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},uy=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},my=(e,n,t,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<ay;m++)o.appendChild(uy(r));return o}if(d.forEach((m,v)=>{o.appendChild(py(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?ey:ty;if(r==="rows"){let v=h("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=h("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(u=n.freeTextPlaceholder)!=null?u:cu,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:m),x.appendChild(S),v.appendChild(x);let A=fu(r,a,d.length);A&&v.appendChild(A),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=n.freeTextLabel)!=null?f:m,o.appendChild(v)}}return o},hu=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:cu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:du,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},gy=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:du,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},fy=(e,n,t)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=t.backLabel)!=null?l:ry,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:sy,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:oy:(f=t.nextLabel)!=null?f:ny,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},To=e=>{let n=e.getAttribute(pu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},yu=(e,n)=>{e.setAttribute(pu,JSON.stringify(n))},Xn=e=>{var t;let n=Number((t=e.getAttribute(_i))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},hy=(e,n)=>{e.setAttribute(_i,String(Math.max(0,Math.floor(n))))},Yo=e=>{var t;let n=Number((t=e.getAttribute(ji))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},ro=e=>e.getAttribute(Ui)==="true",yy=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},by=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},Za=(e,n)=>{let{payload:t}=no(n),r=qs(t),s=To(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},bu=e=>{let n=To(e),t=Xn(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},xu=e=>{if(!ro(e))return;let n=To(e),t=Xn(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},qi=(e,n,t)=>{let r=Qa(t),s=ly(e),{payload:o,complete:a}=no(n),i=ro(e),d=Xn(e),l=Yo(e),u=i?dy(o,d):cy(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let k=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=k,v.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let k=my(u,r,a,s);x.replaceWith(k)}if(s!=="rows"){let k=e.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(hu(r,s))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!S?e.appendChild(gy(r)):(!p||i)&&S&&S.remove(),e.setAttribute("data-multi-select",p?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let k=fy(d,l,r);A?A.replaceWith(k):e.appendChild(k)}else A&&A.remove();bu(e),xu(e)},xy=(e,n,t)=>{let r=Qa(n),s=iy(r),o=e.toolCall.id,a=qs(t),i=Math.max(1,a.length),d=i>1,l=yy(e,a),u=d?by(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Xo,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(ji,String(i)),p.setAttribute(_i,String(u)),p.setAttribute(Ui,d?"true":"false"),p.setAttribute(uu,s),yu(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),gu(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),p.appendChild(f);let S=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),p.appendChild(S),s!=="rows"&&p.appendChild(hu(r,s)),qi(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},vy=(e,n,t)=>{let{payload:r}=no(n),s=Math.max(1,qs(r).length);s>Yo(e)&&(e.setAttribute(ji,String(s)),s>1&&!ro(e)&&e.setAttribute(Ui,"true")),qi(e,n,t)},wy=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=Qa(n);gu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=no(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},zs=(e,n,t)=>{if(!t||!to(e)||Qa(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Xo}]`).forEach(l=>{l.getAttribute(Xo)!==s&&l.remove()});let a=t.querySelector(`[${Xo}="${mu(s)}"]`);if(a){vy(a,e,n);return}let{payload:i}=no(e),d=xy(e,n,i);t.appendChild(d)},Mo=(e,n)=>{if(!e)return;let t=n?`[${Xo}="${mu(n)}"]`:`[${Xo}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},zi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),oo=(e,n)=>{let t=To(e),r=Xn(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,yu(e,t),bu(e),xu(e)},ei=(e,n,t,r)=>{let s=Yo(e),o=Math.max(0,Math.min(s-1,r));hy(e,o),qi(e,n,t)};var Vi=(e,n)=>{var x,S,A,k,R,H,L,w,B,F,$,W;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(S=r==null?void 0:r.borderColor)!=null?S:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("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",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=r==null?void 0:r.titleColor)!=null?A:"currentColor",u=fe(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",f.appendChild(m),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}p.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=t.description,p.appendChild(v),t.parameters){let O=h("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&&(O.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(O.style.color=r.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=$o(t.parameters),p.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let V=h("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");V.type="button",V.style.backgroundColor=(R=r==null?void 0:r.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(H=r==null?void 0:r.approveButtonTextColor)!=null?H:"#ffffff",V.setAttribute("data-approval-action","approve");let oe=fe("shield-check",14,(L=r==null?void 0:r.approveButtonTextColor)!=null?L:"#ffffff",2);oe&&(oe.style.marginRight="4px",V.appendChild(oe));let Ie=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");V.appendChild(Ie);let Pe=h("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");Pe.type="button",Pe.style.backgroundColor=(B=r==null?void 0:r.denyButtonColor)!=null?B:"transparent",Pe.style.color=(F=r==null?void 0:r.denyButtonTextColor)!=null?F:"var(--persona-feedback-error, #dc2626)",Pe.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Pe.setAttribute("data-approval-action","deny");let ze=fe("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);ze&&(ze.style.marginRight="4px",Pe.appendChild(ze));let pe=document.createTextNode((W=r==null?void 0:r.denyLabel)!=null?W:"Deny");Pe.appendChild(pe),O.append(V,Pe),p.appendChild(O)}return a.append(i,p),o.appendChild(a),o};var vu=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){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'}};r.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(v),n.push(v)}),e.appendChild(u)}}};var Vs=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}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 n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;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=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ks=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.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((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function Qo(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Cy={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)"}},Ay={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Sy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ey=100;function Ty(e,n){let t={...Cy,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Ay}function My(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function ky(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Ly(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Py(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Iy(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Wy(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("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=h("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 Ki(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Qo(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var V,oe;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=fe(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&x.appendChild(S);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(V=r.timestampFormat)!=null?V:"relative";A.textContent=k==="relative"?My(e.timestamp,t):ky(e.timestamp);let R=null;r.showSequenceNumbers!==!1&&(R=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(n+1));let H=Ty(e.type,r.badgeColors),L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=H.bg,L.style.color=H.text,L.style.borderColor=H.text+"50",L.textContent=e.type;let w=(oe=r.descriptionFields)!=null?oe:Sy,B=Ly(e.payload,w),F=null;B&&(F=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=B);let $=h("div","persona-flex-1 persona-min-w-0"),W=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=fe("clipboard","12px","currentColor",1.5);return O&&W.appendChild(O),W.addEventListener("click",async Ie=>{Ie.stopPropagation(),await Py(Iy(e)),W.innerHTML="";let Pe=fe("check","12px","currentColor",1.5);Pe&&W.appendChild(Pe),setTimeout(()=>{W.innerHTML="";let ze=fe("clipboard","12px","currentColor",1.5);ze&&W.appendChild(ze)},1500)}),v.appendChild(x),v.appendChild(A),R&&v.appendChild(R),v.appendChild(L),F&&v.appendChild(F),v.appendChild($),v.appendChild(W),m.appendChild(v),d&&m.appendChild(Wy(e,a,i)),m}}function wu(e){var m,v,x,S,A;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[]}=e,a=(m=s==null?void 0:s.features)==null?void 0:m.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",l=(x=a==null?void 0:a.label)!=null?x:"",u=(A=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?A:{},p=o.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let k=p.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=u.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Qo(R,k==null?void 0:k.panel);let H=[],L="",w="",B=null,F=[],$={},W=0,O=Ba(),V=0,oe=0,Ie=!1,Pe=null,ze=!1,pe=0,ce=new Set,Ee=new Map,je="",te="",xe=null,G,ae,He,ue,Re;function tt(){let P=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),he=h("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");Qo(he,k==null?void 0:k.headerBar);let ge=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");ge.textContent="Events",G=h("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"),G.textContent="0";let dt=h("div","persona-flex-1");ae=h("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 Ke=h("option","");Ke.value="",Ke.textContent="All events",ae.appendChild(Ke),He=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),He.type="button",He.title="Copy All";let an=fe("clipboard-copy","12px","currentColor",1.5);an&&He.appendChild(an);let At=h("span","persona-text-xs");At.textContent="Copy All",He.appendChild(At),he.appendChild(ge),he.appendChild(G),he.appendChild(dt),he.appendChild(ae),he.appendChild(He);let bt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Qo(bt,k==null?void 0:k.searchBar);let Mt=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),ut=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Mt&&ut.appendChild(Mt),ue=h("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"),Qo(ue,k==null?void 0:k.searchInput),ue.type="text",ue.placeholder="Search event payloads...",Re=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Re.type="button",Re.style.display="none";let Vt=fe("x","12px","currentColor",2);return Vt&&Re.appendChild(Vt),bt.appendChild(ut),bt.appendChild(ue),bt.appendChild(Re),P.appendChild(he),P.appendChild(bt),P}let K,se=o.find(P=>P.renderEventStreamToolbar);if(se!=null&&se.renderEventStreamToolbar&&s){let P=se.renderEventStreamToolbar({config:s,defaultRenderer:()=>tt(),eventCount:n.getSize(),filteredCount:0,onFilterChange:he=>{L=he,re(),zt()},onSearchChange:he=>{w=he,re(),zt()}});K=P!=null?P:tt()}else K=tt();let Oe=h("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");Oe.style.display="none";let J=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let we=h("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");Qo(we,k==null?void 0:k.scrollIndicator),we.style.display="none",we.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let $e=fe(d,"14px","currentColor",2);$e&&we.appendChild($e);let ne=h("span","");ne.textContent=l,we.appendChild(ne);let Te=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Te.style.display="none",J.appendChild(z),J.appendChild(Te),J.appendChild(we),R.setAttribute("tabindex","0"),R.appendChild(K),R.appendChild(Oe),R.appendChild(J);function ve(){let P=n.getAll(),he={};for(let At of P)he[At.type]=(he[At.type]||0)+1;let ge=Object.keys(he).sort(),dt=ge.length!==F.length||!ge.every((At,bt)=>At===F[bt]),Ke=!dt&&ge.some(At=>he[At]!==$[At]),It=P.length!==Object.values($).reduce((At,bt)=>At+bt,0);if(!dt&&!Ke&&!It||(F=ge,$=he,!ae))return;let an=ae.value;if(ae.options[0].textContent="All events",dt){for(;ae.options.length>1;)ae.remove(1);for(let At of ge){let bt=h("option","");bt.value=At,bt.textContent=`${At} (${he[At]||0})`,ae.appendChild(bt)}an&&ge.includes(an)?ae.value=an:an&&(ae.value="",L="")}else for(let At=1;At<ae.options.length;At++){let bt=ae.options[At];bt.textContent=`${bt.value} (${he[bt.value]||0})`}}function Ht(){let P=n.getAll();if(L&&(P=P.filter(he=>he.type===L)),w){let he=w.toLowerCase();P=P.filter(ge=>ge.type.toLowerCase().includes(he)||ge.payload.toLowerCase().includes(he))}return P}function ie(){return L!==""||w!==""}function re(){W=0,V=0,O.resume(),we.style.display="none"}function sn(P){ce.has(P)?ce.delete(P):ce.add(P),xe=P;let he=z.scrollTop,ge=O.isFollowing();ze=!0,O.pause(),zt(),z.scrollTop=he,ge&&O.resume(),ze=!1}function Nt(){return Rs(z,50)}function zt(){oe=Date.now(),Ie=!1,ve();let P=n.getEvictedCount();P>0?(Oe.textContent=`${P.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",H=Ht();let he=H.length,ge=n.getSize()>0;G&&(G.textContent=String(n.getSize())),he===0&&ge&&ie()?(Te.textContent=w?`No events matching '${w}'`:"No events matching filter",Te.style.display="",z.style.display="none"):(Te.style.display="none",z.style.display=""),He&&(He.title=ie()?`Copy Filtered (${he})`:"Copy All"),i&&!O.isFollowing()&&he>W&&(V+=he-W,ne.textContent=l?`${l}${V>0?` (${V})`:""}`:"",we.style.display=""),W=he;let dt=n.getAll(),Ke=dt.length>0?dt[0].timestamp:0,It=new Set(H.map(bt=>bt.id));for(let bt of ce)It.has(bt)||ce.delete(bt);let an=L!==je||w!==te,At=Ee.size===0&&H.length>0;if(an||At||H.length===0){z.innerHTML="",Ee.clear();let bt=document.createDocumentFragment();for(let Mt=0;Mt<H.length;Mt++){let ut=Ki(H[Mt],Mt,Ke,u,ce,sn,o,s);Ee.set(H[Mt].id,ut),bt.appendChild(ut)}z.appendChild(bt),je=L,te=w,xe=null}else{if(xe!==null){let Mt=Ee.get(xe);if(Mt&&Mt.parentNode===z){let ut=H.findIndex(Vt=>Vt.id===xe);if(ut>=0){let Vt=Ki(H[ut],ut,Ke,u,ce,sn,o,s);z.insertBefore(Vt,Mt),Mt.remove(),Ee.set(xe,Vt)}}xe=null}let bt=new Set(H.map(Mt=>Mt.id));for(let[Mt,ut]of Ee)bt.has(Mt)||(ut.remove(),Ee.delete(Mt));for(let Mt=0;Mt<H.length;Mt++){let ut=H[Mt];if(!Ee.has(ut.id)){let Vt=Ki(ut,Mt,Ke,u,ce,sn,o,s);Ee.set(ut.id,Vt),z.appendChild(Vt)}}}O.isFollowing()&&(z.scrollTop=z.scrollHeight)}function vr(){if(Date.now()-oe>=Ey){Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),zt();return}Ie||(Ie=!0,Pe=requestAnimationFrame(()=>{Pe=null,zt()}))}let dr=(P,he)=>{if(!He)return;He.innerHTML="";let ge=fe(P,"12px","currentColor",1.5);ge&&He.appendChild(ge);let dt=h("span","persona-text-xs");dt.textContent="Copy All",He.appendChild(dt),setTimeout(()=>{He.innerHTML="";let Ke=fe("clipboard-copy","12px","currentColor",1.5);Ke&&He.appendChild(Ke);let It=h("span","persona-text-xs");It.textContent="Copy All",He.appendChild(It),He.disabled=!1},he)},Ue=async()=>{if(He){He.disabled=!0;try{let P;ie()?P=H:t?(P=await t(),P.length===0&&(P=n.getAll())):P=n.getAll();let he=P.map(ge=>{try{return JSON.parse(ge.payload)}catch{return ge.payload}});await navigator.clipboard.writeText(JSON.stringify(he,null,2)),dr("check",1500)}catch{dr("x",1500)}}},U=()=>{ae&&(L=ae.value,re(),zt())},Ae=()=>{!ue||!Re||(Re.style.display=ue.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{w=ue.value,re(),zt()},150))},Be=()=>{!ue||!Re||(ue.value="",w="",Re.style.display="none",B&&clearTimeout(B),re(),zt())},De=()=>{if(ze)return;let P=z.scrollTop,{action:he,nextLastScrollTop:ge}=Da({following:O.isFollowing(),currentScrollTop:P,lastScrollTop:pe,nearBottom:Nt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});pe=ge,he==="resume"?(O.resume(),V=0,we.style.display="none"):he==="pause"&&(O.pause(),i&&(ne.textContent=l,we.style.display=""))},_e=P=>{let he=Na({following:O.isFollowing(),deltaY:P.deltaY,nearBottom:Nt(),resumeWhenNearBottom:!0});he==="pause"?(O.pause(),i&&(ne.textContent=l,we.style.display="")):he==="resume"&&(O.resume(),V=0,we.style.display="none")},ct=()=>{i&&(z.scrollTop=z.scrollHeight,O.resume(),V=0,we.style.display="none")},nt=P=>{let he=P.target;if(!he||he.closest("button"))return;let ge=he.closest("[data-event-id]");if(!ge)return;let dt=ge.getAttribute("data-event-id");dt&&sn(dt)},Ct=P=>{if((P.metaKey||P.ctrlKey)&&P.key==="f"){P.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}P.key==="Escape"&&(ue&&document.activeElement===ue?(Be(),ue.blur(),R.focus()):r&&r())};He&&He.addEventListener("click",Ue),ae&&ae.addEventListener("change",U),ue&&ue.addEventListener("input",Ae),Re&&Re.addEventListener("click",Be),z.addEventListener("scroll",De),z.addEventListener("wheel",_e,{passive:!0}),z.addEventListener("click",nt),we.addEventListener("click",ct),R.addEventListener("keydown",Ct);function jt(){B&&clearTimeout(B),Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),Ie=!1,Ee.clear(),He&&He.removeEventListener("click",Ue),ae&&ae.removeEventListener("change",U),ue&&ue.removeEventListener("input",Ae),Re&&Re.removeEventListener("click",Be),z.removeEventListener("scroll",De),z.removeEventListener("wheel",_e),z.removeEventListener("click",nt),we.removeEventListener("click",ct),R.removeEventListener("keydown",Ct)}return{element:R,update:vr,destroy:jt}}}function Cu(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${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 l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(l.append(u,p),i.append(d,l),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Au=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>Cu(e,n)});if(u)return u}return Cu(e,n)};var Ji=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},so=new Ji;so.register("PersonaArtifactCard",Au);function Ry(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function Su(e,n){var He,ue,Re,tt;let t=(ue=(He=e.features)==null?void 0:He.artifacts)==null?void 0:ue.layout,s=((Re=t==null?void 0:t.toolbarPreset)!=null?Re:"default")==="document",o=(tt=t==null?void 0:t.panePadding)==null?void 0:tt.trim(),a=e.markdown?Oo(e.markdown):null,i=Cs(e.sanitize),d=K=>{let se=a?a(K):Fo(K);return i?i(se):se},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let p=h("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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let x="rendered",S=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),A=s?_t({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):_t({icon:"eye",label:"Rendered view"}),k=s?_t({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):_t({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,B=!!(L&&w&&w.length>0),F=null,$,W=null,O=null;if(s&&(H||L)&&!B){if($=H?qa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let K=fe("chevron-down",14,"currentColor",2);K&&$.appendChild(K)}}else s&&B?(F=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=H?qa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=_t({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append($,W)):s?$=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=_t({icon:"copy",label:"Copy"});let V=s?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"}),oe=s?_t({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:"Close"}),Ie=()=>{var z,we,$e;let K=(z=je.find(ne=>ne.id===te))!=null?z:je[je.length-1],se=(we=K==null?void 0:K.id)!=null?we:null,Oe=(K==null?void 0:K.artifactType)==="markdown"&&($e=K.markdown)!=null?$e:"",J=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Oe,jsonPayload:J,id:se}},Pe=async()=>{var z;let{markdown:K,jsonPayload:se}=Ie(),Oe=(z=je.find(we=>we.id===te))!=null?z:je[je.length-1],J=(Oe==null?void 0:Oe.artifactType)==="markdown"?K:Oe?se:"";try{await navigator.clipboard.writeText(J)}catch{}};if($.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&B){let{markdown:se,jsonPayload:Oe,id:J}=Ie();try{await K({actionId:"primary",artifactId:J,markdown:se,jsonPayload:Oe})}catch{}return}await Pe()}),W&&(w!=null&&w.length)){let K=()=>{var Oe;return(Oe=p.closest("[data-persona-root]"))!=null?Oe:document.body},se=()=>{O=Eo({items:w.map(Oe=>({id:Oe.id,label:Oe.label})),onSelect:async Oe=>{let{markdown:J,jsonPayload:z,id:we}=Ie(),$e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:Oe,artifactId:we,markdown:J,jsonPayload:z}):Oe==="markdown"||Oe==="md"?await navigator.clipboard.writeText(J):Oe==="json"||Oe==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(J||z)}catch{}},anchor:F!=null?F:W,position:"bottom-right",portal:K()})};p.isConnected?se():requestAnimationFrame(se),W.addEventListener("click",Oe=>{Oe.stopPropagation(),O==null||O.toggle()})}V.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}G()}),oe.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let ze=()=>{s&&(A.setAttribute("aria-pressed",x==="rendered"?"true":"false"),k.setAttribute("aria-pressed",x==="source"?"true":"false"))};A.addEventListener("click",()=>{x="rendered",ze(),G()}),k.addEventListener("click",()=>{x="source",ze(),G()});let pe=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),S.append(A,k),F?R.append(F,V,oe):R.append($,V,oe),f.append(S,pe,R),ze()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ce=h("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"),Ee=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ce.style.paddingLeft=o,ce.style.paddingRight=o,Ee.style.padding=o),p.appendChild(f),p.appendChild(ce),p.appendChild(Ee);let je=[],te=null,xe=!1,G=()=>{var J,z,we,$e;let K=s&&je.length<=1;ce.classList.toggle("persona-hidden",K),ce.replaceChildren();for(let ne of je){let Te=h("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");Te.type="button",Te.textContent=ne.title||ne.id.slice(0,8),ne.id===te&&Te.classList.add("persona-bg-persona-container","persona-border-persona-border"),Te.addEventListener("click",()=>n.onSelect(ne.id)),ce.appendChild(Te)}Ee.replaceChildren();let se=te&&je.find(ne=>ne.id===te)||je[je.length-1];if(!se)return;if(s){let ne=se.artifactType==="markdown"?"MD":(J=se.component)!=null?J:"Component",ve=(se.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";pe.textContent=`${ve} \xB7 ${ne}`}else m.textContent="Artifacts";if(se.artifactType==="markdown"){if(s&&x==="source"){let Te=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Te.textContent=(z=se.markdown)!=null?z:"",Ee.appendChild(Te);return}let ne=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ne.innerHTML=d((we=se.markdown)!=null?we:""),Ee.appendChild(ne);return}let Oe=se.component?so.get(se.component):void 0;if(Oe){let Te={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let ve=Oe(($e=se.props)!=null?$e:{},Te);if(ve){Ee.appendChild(ve);return}}catch{}}Ee.appendChild(Ry(se))},ae=()=>{var se;let K=je.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Oe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,z=((se=Oe==null?void 0:Oe.classList.contains("persona-artifact-narrow-host"))!=null?se:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&z&&xe?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var se,Oe,J;je=K.artifacts,te=(J=(Oe=K.selectedId)!=null?Oe:(se=K.artifacts[K.artifacts.length-1])==null?void 0:se.id)!=null?J:null,je.length>0&&(xe=!0),G(),ae()},setMobileOpen(K){xe=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ae()}}}function Yn(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Eu(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Yn(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Hy(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ti(e,n){var d,l,u,p,f,m,v,x,S,A;if(!Yn(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Hy(e),Eu(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(A=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:A.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Eu(e,n)}var Tu=["panel","seamless"];function ni(e,n){var i,d,l,u,p,f;for(let m of Tu)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!Yn(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=Tu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Mu(e,n){var t,r,s;return!n||!Yn(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function By(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function Dy(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function Ny(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Oy(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function ku(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Lu(e,n,t,r,s,o){let a=By(s,200),i=Oy(n,t,r,200);i=Math.max(a,i);let d=Dy(o);return d!==null&&(i=Math.min(i,d)),Ny(e,a,i)}var Pu={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"}},Gi=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,S;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=Pu[a])!=null?x:Pu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let A=h("p","persona-text-sm persona-text-persona-muted");A.textContent=i.description,d.appendChild(A)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(A=>{var w,B;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${A.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=A.label,k.appendChild(R);let H=(w=A.type)!=null?w:"text",L;H==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=H),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${n.id}-${a}-${A.name}`,L.name=A.name,L.placeholder=(B=A.placeholder)!=null?B:"",A.required&&(L.required=!0),k.appendChild(L),u.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(S=i.submitLabel)!=null?S:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async A=>{var L,w;A.preventDefault();let k=(L=t.formEndpoint)!=null?L:"/form",R=new FormData(u),H={};R.forEach((B,F)=>{H[F]=B}),H.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let B=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!B.ok)throw new Error(`Form submission failed (${B.status})`);let F=await B.json();f.textContent=(w=F.message)!=null?w:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(B){f.textContent=B instanceof Error?B.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Xi=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},ri=new Xi;var Iu=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Fy=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},$y=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},oi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Fy(e),t=$y(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Yi=e=>typeof e=="string"?e:e==null?"":String(e),Zo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Yi(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Yi(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Yi(t.text)}}},Wu=e=>Array.isArray(e)?e.map(n=>String(n)):[],si=e=>{let n=new Set(Wu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Wu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var _y=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},jy=e=>e.map(n=>({...n,streaming:!1})),Uy=e=>e.map(n=>({...n,status:"complete"})),Qi=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?_y(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?jy(t.messages):void 0,artifacts:t.artifacts?Uy(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as qy,STR as zy,OBJ as Vy}from"partial-json";function Ky(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Jy(e,n){if(!Ky(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function Zi(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=qy(t,zy|Vy),o=Jy(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function Gy(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function el(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=so.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Xy(){let e=Zi();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ru(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function tl(e){let n=Ru(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function nl(e){let n=Ru(e);if(!n)return null;try{let t=JSON.parse(n);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:n}}}catch{}return null}var Yy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function rl(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Yy}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,m.appendChild(x),f.appendChild(m);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let w=1;w<=5;w++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),B.title=l[w-1],B.dataset.rating=String(w),B.innerHTML=`
23
+ `,n.addEventListener("click",t);let r=o=>{var P,N,L,w,W,F,_,B,j,q,re,Ie,Re,Ne;let a=(P=o.launcher)!=null?P:{},i=an(o),d=n.querySelector("[data-role='launcher-title']");if(d){let ce=(N=a.title)!=null?N:"Chat Assistant";d.textContent=ce,d.setAttribute("title",ce)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ce=(L=a.subtitle)!=null?L:"Get answers fast";l.textContent=ce,l.setAttribute("title",ce)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ce=(w=a.agentIconSize)!=null?w:"40px";if(p.style.height=ce,p.style.width=ce,p.innerHTML="",a.agentIconName){let ve=parseFloat(ce)||24,Me=be(a.agentIconName,ve*.6,"var(--persona-text-inverse, #ffffff)",2);Me?(p.appendChild(Me),p.style.display=""):(p.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",p.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ce=(_=a.agentIconSize)!=null?_:"40px";f.style.height=ce,f.style.width=ce,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ce=(B=a.callToActionIconSize)!=null?B:"32px";m.style.height=ce,m.style.width=ce,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let ve=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ve=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Me=parseFloat(ce)||24,Le=Math.max(Me-ve,8),ne=be(a.callToActionIconName,Le,"currentColor",2);ne?m.appendChild(ne):m.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else m.textContent=(q=a.callToActionIconText)!=null?q:"\u2197"}let v=a.position&&br[a.position]?br[a.position]:br["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${x} ${v}`,i||(n.style.zIndex=String((re=a.zIndex)!=null?re:hn));let A="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Ie=a.border)!=null?Ie:A,n.style.boxShadow=(Re=a.shadow)!=null?Re:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(Ne=a.collapsedMaxWidth)!=null?Ne:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:s}};var Bh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",za=(e,t={})=>{var x,E,A,I,P,N;let{showClose:n=!0,wrapperClassName:r=Bh,buttonSize:s,iconSize:o="28px"}=t,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(E=s!=null?s:a.closeButtonSize)!=null?E:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(A=a.closeButtonTooltipText)!=null?A:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0;l.setAttribute("aria-label",u),l.style.display=n?"":"none";let f=(P=a.closeButtonIconName)!=null?P:"x",m=(N=a.closeButtonIconText)!=null?N:"\xD7";l.style.color=a.closeButtonColor||Tn.actionIconColor;let v=be(f,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let L=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${L} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let L=null,w=()=>{if(L)return;let F=l.ownerDocument,_=F.body;if(!_)return;L=Sr(F,"div","persona-clear-chat-tooltip"),L.textContent=u;let B=Sr(F,"div");B.className="persona-clear-chat-tooltip-arrow",L.appendChild(B);let j=l.getBoundingClientRect();L.style.position="fixed",L.style.zIndex=String(Zr),L.style.left=`${j.left+j.width/2}px`,L.style.top=`${j.top-8}px`,L.style.transform="translate(-50%, -100%)",_.appendChild(L)},W=()=>{L&&L.parentNode&&(L.parentNode.removeChild(L),L=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",W),l.addEventListener("focus",w),l.addEventListener("blur",W),d._cleanupTooltip=()=>{W(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",W),l.removeEventListener("focus",w),l.removeEventListener("blur",W)}}return{button:l,wrapper:d}},Dh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Va=(e,t={})=>{var L,w,W,F,_,B,j,q,re,Ie,Re,Ne,ce;let{wrapperClassName:n=Dh,buttonSize:r,iconSize:s="20px"}=t,a=(w=((L=e==null?void 0:e.launcher)!=null?L:{}).clearChat)!=null?w:{},i=(W=r!=null?r:a.size)!=null?W:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",l=(_=a.iconColor)!=null?_:"",u=(B=a.backgroundColor)!=null?B:"",p=(j=a.borderWidth)!=null?j:"",f=(q=a.borderColor)!=null?q:"",m=(re=a.borderRadius)!=null?re:"",v=(Ie=a.paddingX)!=null?Ie:"",x=(Re=a.paddingY)!=null?Re:"",E=(Ne=a.tooltipText)!=null?Ne:"Clear chat",A=(ce=a.showTooltip)!=null?ce:!0,I=h("div",n),P=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");P.style.height=i,P.style.width=i,P.type="button",P.setAttribute("aria-label",E),P.style.color=l||Tn.actionIconColor;let N=be(d,s,"currentColor",1);if(N&&(N.style.display="block",P.appendChild(N)),u&&(P.style.backgroundColor=u,P.classList.remove("hover:persona-bg-gray-100")),p||f){let ve=p||"0px",Me=f||"transparent";P.style.border=`${ve} solid ${Me}`,P.classList.remove("persona-border-none")}if(m&&(P.style.borderRadius=m,P.classList.remove("persona-rounded-full")),v&&(P.style.paddingLeft=v,P.style.paddingRight=v),x&&(P.style.paddingTop=x,P.style.paddingBottom=x),I.appendChild(P),A&&E){let ve=null,Me=()=>{if(ve)return;let ne=P.ownerDocument,ke=ne.body;if(!ke)return;ve=Sr(ne,"div","persona-clear-chat-tooltip"),ve.textContent=E;let V=Sr(ne,"div");V.className="persona-clear-chat-tooltip-arrow",ve.appendChild(V);let pe=P.getBoundingClientRect();ve.style.position="fixed",ve.style.zIndex=String(Zr),ve.style.left=`${pe.left+pe.width/2}px`,ve.style.top=`${pe.top-8}px`,ve.style.transform="translate(-50%, -100%)",ke.appendChild(ve)},Le=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};I.addEventListener("mouseenter",Me),I.addEventListener("mouseleave",Le),P.addEventListener("focus",Me),P.addEventListener("blur",Le),I._cleanupTooltip=()=>{Le(),I.removeEventListener("mouseenter",Me),I.removeEventListener("mouseleave",Le),P.removeEventListener("focus",Me),P.removeEventListener("blur",Le)}}return{button:P,wrapper:I}};var Tn={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))"},no=e=>{var L,w,W,F,_,B,j,q,re,Ie,Re,Ne,ce,ve,Me,Le;let{config:t,showClose:n=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(L=t==null?void 0:t.launcher)!=null?L:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(W=s.closeButtonPlacement)!=null?W:"inline",i=(F=s.headerIconHidden)!=null?F:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ne=parseFloat(o)||24,ke=be(d,ne*.6,"currentColor",1);ke?l.replaceChildren(ke):l.textContent=(B=(_=t==null?void 0:t.launcher)==null?void 0:_.agentIconText)!=null?B:"\u{1F4AC}"}else if((j=t==null?void 0:t.launcher)!=null&&j.iconUrl){let ne=h("img");ne.src=t.launcher.iconUrl,ne.alt="",ne.className="persona-rounded-xl persona-object-cover",ne.style.height=o,ne.style.width=o,l.replaceChildren(ne)}else l.textContent=(re=(q=t==null?void 0:t.launcher)==null?void 0:q.agentIconText)!=null?re:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=Tn.titleColor,p.textContent=(Re=(Ie=t==null?void 0:t.launcher)==null?void 0:Ie.title)!=null?Re:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=Tn.subtitleColor,f.textContent=(ce=(Ne=t==null?void 0:t.launcher)==null?void 0:Ne.subtitle)!=null?ce:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let m=(ve=s.clearChat)!=null?ve:{},v=(Me=m.enabled)!=null?Me:!0,x=(Le=m.placement)!=null?Le:"inline",E=null,A=null;if(v){let ke=Va(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=ke.button,A=ke.wrapper,x==="top-right"&&(A.style.right="48px"),x==="inline"&&r.appendChild(A)}let I=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:P,wrapper:N}=za(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&r.appendChild(N),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:P,closeButtonWrapper:N,clearChatButton:E,clearChatButtonWrapper:A}},Go=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function To(e){let{items:t,onSelect:n,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Zr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of t){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let E=be(m.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),u(),n(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function jt(e){let{icon:t,label:n,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=be(t,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ka(e){let{icon:t,label:n,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",n),t){let f=be(t,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=n,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function Ja(e){let{items:t,selectedId:n,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=n,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of t){let p;u.icon?p=jt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function Oi(e){var m,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let u=h("span","persona-combo-btn-label");u.textContent=t,l.appendChild(u);let p=be(n,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,E;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=To({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let E=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var eu=e=>{var r;let t=no({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let s=t.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>n()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n())}))}return t};function Nh(e,t,n){var r,s,o;if(t!=null&&t.length)for(let a of t){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=be(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=To({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var tu=e=>{var I,P,N,L,w,W,F,_,B;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(I=t==null?void 0:t.launcher)!=null?I:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=Oi({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Tn.titleColor,u=(N=l.querySelector(".persona-combo-btn-label"))!=null?N:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Tn.titleColor,u.textContent=(L=a.title)!=null?L:"Chat Assistant",l.appendChild(u),Nh(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let q=s.onTitleClick;l.addEventListener("click",re=>{re.target.closest("button")||q()}),l.addEventListener("keydown",re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),q())})}let j=s==null?void 0:s.titleRowHover;j&&(l.style.borderRadius=(W=j.borderRadius)!=null?W:"10px",l.style.padding=(F=j.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var q,re;l.style.backgroundColor=(q=j.background)!=null?q:"",l.style.borderColor=(re=j.border)!=null?re:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(_=a.closeButtonSize)!=null?_:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Tn.actionIconColor;let v=(B=a.closeButtonIconName)!=null?B:"x",x=be(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let E=h("div");E.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:E,headerTitle:u,headerSubtitle:A,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Fi={default:eu,minimal:tu},nu=e=>{var t;return(t=Fi[e])!=null?t:Fi.default},qs=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",o=nu(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(o.iconHolder.style.display="none"),t.showTitle===!1&&(o.headerTitle.style.display="none"),t.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(o.closeButton.style.display="none"),t.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Ga=e=>{var a,i;let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let s=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},o=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,s());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:o}},Xa=e=>{var L,w,W,F,_,B,j,q,re,Ie,Re,Ne;let t=(L=e==null?void 0:e.sendButton)!=null?L:{},n=(w=t.useIcon)!=null?w:!1,r=(W=t.iconText)!=null?W:"\u2191",s=t.iconName,o=(F=t.stopIconName)!=null?F:"square",a=(_=t.tooltipText)!=null?_:"Send message",i=(B=t.stopTooltipText)!=null?B:"Stop generating",d=(q=(j=e==null?void 0:e.copy)==null?void 0:j.sendButtonLabel)!=null?q:"Send",l=(Ie=(re=e==null?void 0:e.copy)==null?void 0:re.stopButtonLabel)!=null?Ie:"Stop",u=(Re=t.showTooltip)!=null?Re:!1,p=(Ne=t.size)!=null?Ne:"40px",f=t.backgroundColor,m=t.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",n?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");x.type="submit",x.setAttribute("data-persona-composer-submit","");let E=null,A=null;if(n){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let ce=parseFloat(p)||24,ve=(m==null?void 0:m.trim())||"currentColor";s?(E=be(s,ce,ve,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,A=be(o,ce,ve,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");t.borderWidth&&(x.style.borderWidth=t.borderWidth,x.style.borderStyle="solid"),t.borderColor&&(x.style.borderColor=t.borderColor),t.paddingX?(x.style.paddingLeft=t.paddingX,x.style.paddingRight=t.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),t.paddingY?(x.style.paddingTop=t.paddingY,x.style.paddingBottom=t.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let I=null;u&&a&&(I=h("div","persona-send-button-tooltip"),I.textContent=a,v.appendChild(I)),x.setAttribute("aria-label",a),v.appendChild(x);let P="send";return{button:x,wrapper:v,setMode:ce=>{if(ce===P)return;P=ce;let ve=ce==="stop"?i:a;if(x.setAttribute("aria-label",ve),I&&(I.textContent=ve),n){if(E&&A){let Me=ce==="stop"?A:E;x.replaceChildren(Me)}}else x.textContent=ce==="stop"?l:d}}},Qa=e=>{var I,P,N,L,w,W,F,_,B,j,q,re;let t=(I=e==null?void 0:e.voiceRecognition)!=null?I:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(r||s))return null;let a=(L=(N=e==null?void 0:e.sendButton)==null?void 0:N.size)!=null?L:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=t.iconName)!=null?w:"mic",u=(W=t.iconSize)!=null?W:a,p=parseFloat(u)||24,f=(_=t.backgroundColor)!=null?_:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,m=(j=t.iconColor)!=null?j:(B=e==null?void 0:e.sendButton)==null?void 0:B.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=be(l,p,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),t.borderWidth&&(d.style.borderWidth=t.borderWidth,d.style.borderStyle="solid"),t.borderColor&&(d.style.borderColor=t.borderColor),t.paddingX&&(d.style.paddingLeft=t.paddingX,d.style.paddingRight=t.paddingX),t.paddingY&&(d.style.paddingTop=t.paddingY,d.style.paddingBottom=t.paddingY),i.appendChild(d);let E=(q=t.tooltipText)!=null?q:"Start voice recognition";if(((re=t.showTooltip)!=null?re:!1)&&E){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=E,i.appendChild(Ie)}return{button:d,wrapper:i}},Ya=e=>{var v,x,E,A,I,P,N,L;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(E=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?E:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((A=t.allowedTypes)!=null?A:Nr).join(","),s.multiple=((I=t.maxFiles)!=null?I:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(P=t.buttonTooltipText)!=null?P:"Attach file");let i=(N=t.buttonIconName)!=null?N:"paperclip",d=n,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=be(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let f=(L=t.buttonTooltipText)!=null?L:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},Za=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=t.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=h("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},ei=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var zs=e=>{var v,x,E,A,I,P;let{config:t}=e,n=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");n.setAttribute("data-persona-theme-zone","composer");let r=ei(),s=h("form","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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Ga(t);a();let i=Xa(t),d=Qa(t),l=Ya(t),u=Za(t);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),p.append(f,m),s.append(p),s.addEventListener("click",N=>{N.target!==i.button&&N.target!==i.wrapper&&N.target!==(d==null?void 0:d.button)&&N.target!==(d==null?void 0:d.wrapper)&&N.target!==(l==null?void 0:l.button)&&N.target!==(l==null?void 0:l.wrapper)&&o.focus()}),n.append(r,s,u),{footer:n,suggestions:r,composerForm:s,textarea:o,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:u,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:p,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var ru=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let t=h("span","persona-pill-peek__icon"),n=be("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=be("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(t,r,s),{root:e,textNode:r}},ou=e=>{var v,x,E,A,I,P;let{config:t}=e,n=h("div","persona-widget-footer persona-widget-footer--pill");n.setAttribute("data-persona-theme-zone","composer");let r=ei();r.style.display="none";let s=Za(t);s.style.display="none";let{textarea:o,attachAutoResize:a}=Ga(t);o.style.maxHeight="100px",a();let i=Xa(t),d=Qa(t),l=Ya(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",N=>{N.target!==i.button&&N.target!==i.wrapper&&N.target!==(d==null?void 0:d.button)&&N.target!==(d==null?void 0:d.wrapper)&&N.target!==(l==null?void 0:l.button)&&N.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&n.append(l.previewsContainer),n.append(u,r,s);let m=u;return{footer:n,suggestions:r,composerForm:u,textarea:o,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:s,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(I=l==null?void 0:l.input)!=null?I:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var su=e=>{var u,p,f,m,v,x,E,A,I,P,N,L,w,W,F,_,B;let t=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,n=an(e);if(to(e)){let j=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},q=h("div","persona-widget-wrapper persona-fixed persona-transition");q.setAttribute("data-persona-composer-bar",""),q.dataset.state="collapsed",q.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",q.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:hn);let re=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");re.style.width="100%",q.appendChild(re);let Ie=h("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(A=j.expandedSize)!=null?A:"anchored",Ie.style.zIndex=String((P=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?P:hn),{wrapper:q,panel:re,pillRoot:Ie}}if(n){let j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),q=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(q),{wrapper:j,panel:q}}if(!t){let j=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),q=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),re=(L=(N=e==null?void 0:e.launcher)==null?void 0:N.width)!=null?L:"100%";return j.style.width=re,q.style.width="100%",j.appendChild(q),{wrapper:j,panel:q}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&br[s.position]?br[s.position]:br["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((F=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?F:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(B=(_=e==null?void 0:e.launcher)==null?void 0:_.width)!=null?B:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Oh=(e,t)=>{var N,L,w,W,F,_,B,j,q;let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=za(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(L=(N=e==null?void 0:e.launcher)==null?void 0:N.clearChat)==null?void 0:L.enabled)!=null?w:!0,a=null,i=null;if(o){let re=Va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=re.button,i=re.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","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");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(F=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?F:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(B=(_=e==null?void 0:e.copy)==null?void 0:_.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",u.append(p,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((q=e==null?void 0:e.copy)==null?void 0:q.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let E=h("div","persona-composer-overlay persona-pointer-events-none");E.setAttribute("data-persona-composer-overlay",""),E.style.position="absolute",E.style.left="0",E.style.right="0",E.style.bottom="0",E.style.zIndex="20";let A=ou({config:e}),{root:I,textNode:P}=ru();return n.append(d,s,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:m,composerOverlay:E,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:I,peekTextNode:P}},au=(e,t=!0)=>{var E,A,I,P,N,L,w,W,F;if(to(e))return Oh(e,t);let n=h("div","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");n.setAttribute("data-persona-theme-zone","container");let r=(E=e==null?void 0:e.layout)==null?void 0:E.header,s=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,o=r?qs(e,r,{showClose:t}):no({config:e,showClose:t}),a=h("div","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");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=an(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(P=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(L=(N=e==null?void 0:e.copy)==null?void 0:N.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((W=e==null?void 0:e.copy)==null?void 0:W.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=zs({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;s?Go(n,o,e):(o.header.style.display="none",Go(n,o,e)),n.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(m.footer.style.display="none"),n.append(m.footer),n.append(x),{container:n,body:a,messagesWrapper:u,composerOverlay:x,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Fh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},_h=(e,t)=>{if(!e)return null;let n=Fh(e);if(n===null)return null;let r=t==null?void 0:t[e],s=r!==void 0?r:n;return s||null},$h=(e,t)=>{let n=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},jh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},_i=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},$i=320,lu=320,Uh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),qh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Vh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Kh=(e,t,n)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${$i}px`,l.style.maxHeight=`${lu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),jh(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return n==null||n(),null}},Jh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!_i(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${$i}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Gh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!_i(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${$i}px`,s.style.maxHeight=`${lu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!_i(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(s),e},cu=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Xo};if(t){let s=t(r);if(s!==null)return s}return Xo()},Qh=(e,t)=>{let n=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},iu=(e,t)=>{let n=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},Yh=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},du=(e,t,n)=>{var m,v,x,E,A,I;let r=(m=t.showCopy)!=null?m:!0,s=(v=t.showUpvote)!=null?v:!0,o=(x=t.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let P=h("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let a=(E=t.visibility)!=null?E:"hover",i=(A=t.align)!=null?A:"right",d=(I=t.layout)!=null?I:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(P,N,L)=>{let w=jt({icon:P,label:N,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",L),w};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Vs=(e,t,n,r,s,o)=>{var ne,ke,V,pe,fe,me,ue,Ge,z,te,We,ge,ie,ae,Qe,Ce,de;let a=n!=null?n:{},i=(ne=a.layout)!=null?ne:"bubble",d=a.avatar,l=a.timestamp,u=(ke=d==null?void 0:d.show)!=null?ke:!1,p=(V=l==null?void 0:l.show)!=null?V:!1,f=(pe=d==null?void 0:d.position)!=null?pe:"left",m=(fe=l==null?void 0:l.position)!=null?fe:"below",v=Yh(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Uh(e),A=(ue=(me=e.content)==null?void 0:me.trim())!=null?ue:"",P=E.length>0&&A===ka,N=$a((z=(Ge=o==null?void 0:o.widgetConfig)==null?void 0:Ge.features)==null?void 0:z.streamAnimation),L=(ge=(We=(te=o==null?void 0:o.widgetConfig)==null?void 0:te.features)==null?void 0:We.streamAnimation)==null?void 0:ge.plugins,w=e.role==="assistant"&&N.type!=="none"?Fs(N.type,L):null,W=e.role==="assistant"&&((ie=w==null?void 0:w.isAnimating)==null?void 0:ie.call(w,e))===!0,F=e.role==="assistant"&&w!==null&&(!!e.streaming||W);F&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),F&&w&&(w.containerClass&&_.classList.add(w.containerClass),_.style.setProperty("--persona-stream-step",`${N.speed}ms`),_.style.setProperty("--persona-stream-duration",`${N.duration}ms`));let B=F?ja((ae=e.content)!=null?ae:"",N.buffer,w,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",j=t({text:B,message:e,streaming:!!e.streaming,raw:e.rawContent}),q=j;F&&(w==null?void 0:w.wrap)==="char"?q=_s(j,"char",e.id,{skipTags:w.skipTags}):F&&(w==null?void 0:w.wrap)==="word"&&(q=_s(j,"word",e.id,{skipTags:w.skipTags}));let re=null;if(P?(re=document.createElement("div"),re.innerHTML=q,re.style.display="none",_.appendChild(re)):_.innerHTML=q,F&&(w!=null&&w.useCaret)&&!P&&A){let X=Ua(),$e=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ct=$e[$e.length-1];if(Ct!=null&&Ct.parentNode)Ct.parentNode.insertBefore(X,Ct.nextSibling);else{let G=_.lastElementChild;G?G.appendChild(X):_.appendChild(X)}}if(p&&m==="inline"&&e.createdAt){let X=iu(e,l);X.classList.add("persona-ml-2","persona-inline"),_.appendChild(X)}if(E.length>0){let X=Kh(E,!P&&!!A,()=>{P&&re&&(re.style.display="")});X?x.appendChild(X):P&&re&&(re.style.display="")}let Ie=qh(e);if(Ie.length>0){let X=Jh(Ie);X&&x.appendChild(X)}let Re=zh(e);if(Re.length>0){let X=Gh(Re);X&&x.appendChild(X)}let Ne=Vh(e);if(Ne.length>0){let X=Xh(Ne);X&&x.appendChild(X)}if(x.appendChild(_),p&&m==="below"&&e.createdAt){let X=iu(e,l);X.classList.add("persona-mt-1"),x.appendChild(X)}let ce=e.role==="assistant"?_h(e.stopReason,(de=(Ce=o==null?void 0:o.widgetConfig)==null?void 0:Ce.copy)==null?void 0:de.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(B&&B.trim()),$e=N.placeholder==="skeleton",Ct=$e&&N.buffer==="line"&&X;if(X)Ct&&x.appendChild($s());else if($e)x.appendChild($s());else{let G=cu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);G&&x.appendChild(G)}}if(ce&&e.stopReason&&!e.streaming&&(A||(_.style.display="none"),x.appendChild($h(e.stopReason,ce))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=du(e,r,s);x.appendChild(X)}if(!u||e.role==="system")return x;let Me=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Le=Qh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Me.append(x,Le):Me.append(Le,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Me},Zh=(e,t,n,r,s,o)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Vs(e,t,n,r,s,o)};var Qo=new Set,ey=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ty=(e,t)=>{var r,s;let n=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
24
+ `):""},pu=(e,t)=>{let n=Qo.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),o=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=be(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",o&&(o.style.display=n?"none":o.textContent||o.childNodes.length?"":"none")},ji=(e,t)=>{var Re,Ne,ce,ve,Me,Le,ne,ke,V,pe,fe;let n=e.reasoning,r=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let s=(Ne=(Re=t==null?void 0:t.features)==null?void 0:Re.reasoningDisplay)!=null?Ne:{},o=s.expandable!==!1,a=o&&Qo.has(e.id),i=n.status!=="complete",d=ty(e,(ce=s.previewMaxLines)!=null?ce:3),l=h("button",o?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(ve=t==null?void 0:t.reasoning)!=null?ve:{},v=String((Me=n.startedAt)!=null?Me:Date.now()),x=()=>{let me=h("span","");return me.setAttribute("data-tool-elapsed",v),me.textContent=Sa(n),me},E=(Le=m.renderCollapsedSummary)==null?void 0:Le.call(m,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Sa(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(p.textContent=E,u.appendChild(p)):E instanceof HTMLElement?u.appendChild(E):(p.textContent=f,u.appendChild(p));let A=h("span","persona-text-xs persona-text-persona-primary");A.textContent=kp(n),u.appendChild(A);let I=(ne=s.loadingAnimation)!=null?ne:"none",P=m.activeTextTemplate,N=m.completeTextTemplate,L=i?P:N,w=E instanceof HTMLElement,W=(me,ue,Ge)=>{let z=Ge;for(let te of ue){let We=h("span","persona-tool-char");We.style.setProperty("--char-index",String(z)),We.textContent=te===" "?"\xA0":te,me.appendChild(We),z++}return z},F=(me,ue)=>{p.textContent="";let Ge=Ea(me,""),z=0;for(let te of Ge){let We=te.styles.length>0?(()=>{let ge=h("span",te.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return p.appendChild(ge),ge})():p;if(te.isDuration&&i)We.appendChild(x());else{let ge=te.isDuration?Sa(n):te.text;ue?z=W(We,ge,z):We.appendChild(document.createTextNode(ge))}}};if(!w&&L)if(A.style.display="none",p.style.display="",i&&I!=="none"){let me=(ke=m.loadingAnimationDuration)!=null?ke:2e3;p.setAttribute("data-preserve-animation","true"),I==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${me}ms`),F(L,!1)):(p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${me}ms`),I==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),F(L,!0))}else F(L,!1);else if(!w&&i&&I!=="none"){p.style.display="";let me=(V=m.loadingAnimationDuration)!=null?V:2e3;if(p.setAttribute("data-preserve-animation","true"),I==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${me}ms`);else{p.classList.add(`persona-tool-loading-${I}`),p.style.setProperty("--persona-tool-anim-duration",`${me}ms`),I==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ue=p.textContent||f;p.textContent="",W(p,ue,0)}n.status==="complete"&&(p.style.display="none")}else w||(n.status==="complete"?p.style.display="none":p.style.display="");let _=null;if(o){_=h("div","persona-flex persona-items-center");let ue=be(a?"chevron-up":"chevron-down",16,"currentColor",2);ue?_.appendChild(ue):_.textContent=a?"Hide":"Show";let Ge=h("div","persona-flex persona-items-center persona-ml-auto");Ge.append(_),l.append(u,Ge)}else l.append(u);let B=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","reasoning"),B.style.display="none",B.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let me=(fe=(pe=t==null?void 0:t.reasoning)==null?void 0:pe.renderCollapsedPreview)==null?void 0:fe.call(pe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});ey(B,me)||(B.textContent=d),B.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,B),r;let j=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let q=n.chunks.join(""),re=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return re.textContent=q||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(re),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),_){_.innerHTML="";let ue=be(a?"chevron-up":"chevron-down",16,"currentColor",2);ue?_.appendChild(ue):_.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",B.style.display=a?"none":B.textContent||B.childNodes.length?"":"none"})(),r.append(l,B,j),r};var Yo=new Set,ny=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ry=(e,t)=>{var o;let n=e.toolCall;if(!n)return"";let r=((o=n.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
25
+ `);let s=Uo(n.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
26
+ `):""},oy=(e,t)=>{var u,p,f,m,v;let n=e.toolCall,r=(u=t==null?void 0:t.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=ry(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Lp(n):"";if(!n)return{summary:a,previewText:o,isActive:!1};let i=n.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},l=a;return s==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=wi(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=wi(n,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},uu=(e,t,n)=>{var u;let r=Yo.has(e),s=(u=n==null?void 0:n.toolCall)!=null?u:{},o=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=be(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Ui=(e,t)=>{var q,re,Ie,Re,Ne,ce,ve,Me,Le;let n=e.toolCall,r=(q=t==null?void 0:t.toolCall)!=null?q:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!n)return s;let o=(Ie=(re=t==null?void 0:t.features)==null?void 0:re.toolCallDisplay)!=null?Ie:{},a=o.expandable!==!1,i=a&&Yo.has(e.id),{summary:d,previewText:l,isActive:u}=oy(e,t),p=h("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");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((Re=n.startedAt)!=null?Re:Date.now()),x=()=>{let ne=h("span","");return ne.setAttribute("data-tool-elapsed",v),ne.textContent=ks(n),ne},E=(ce=r.renderCollapsedSummary)==null?void 0:ce.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Ne=o.collapsedMode)!=null?Ne:"tool-call",isActive:u,config:t!=null?t:{},elapsed:ks(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(m.textContent=E,f.appendChild(m)):E instanceof HTMLElement?f.appendChild(E):(m.textContent=d,f.appendChild(m));let A=(ve=o.loadingAnimation)!=null?ve:"none",I=r.activeTextTemplate,P=r.completeTextTemplate,N=u?I:P,L=E instanceof HTMLElement,w=(ne,ke,V)=>{let pe=V;for(let fe of ke){let me=h("span","persona-tool-char");me.style.setProperty("--char-index",String(pe)),me.textContent=fe===" "?"\xA0":fe,ne.appendChild(me),pe++}return pe},W=(ne,ke)=>{var me;m.textContent="";let V=((me=n.name)==null?void 0:me.trim())||"tool",pe=Ea(ne,V),fe=0;for(let ue of pe){let Ge=ue.styles.length>0?(()=>{let z=h("span",ue.styles.map(te=>`persona-tool-text-${te}`).join(" "));return m.appendChild(z),z})():m;if(ue.isDuration&&u)Ge.appendChild(x());else{let z=ue.isDuration?ks(n):ue.text;ke?fe=w(Ge,z,fe):Ge.appendChild(document.createTextNode(z))}}};if(!L)if(u&&A!=="none"){let ne=(Me=r.loadingAnimationDuration)!=null?Me:2e3;if(m.setAttribute("data-preserve-animation","true"),A==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),N&&W(N,!1);else if(m.classList.add(`persona-tool-loading-${A}`),m.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),A==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),N)W(N,!0);else{let ke=m.textContent||d;m.textContent="",w(m,ke,0)}}else N&&W(N,!1);let F=null;if(a){F=h("div","persona-flex persona-items-center");let ne=r.toggleTextColor||r.headerTextColor||"currentColor",ke=be(i?"chevron-up":"chevron-down",16,ne,2);ke?F.appendChild(ke):F.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(F),p.append(f,V)}else p.append(f);let _=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(_.setAttribute("data-persona-collapsed-preview","tool"),_.style.display="none",_.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let ne=(Le=r.renderCollapsedPreview)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:u,config:t!=null?t:{}});ny(_,ne)||(_.textContent=l),_.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,_),s;let B=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(B.style.display=i?"":"none",r.contentBackgroundColor&&(B.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(B.style.color=r.contentTextColor),r.contentPaddingX&&(B.style.paddingLeft=r.contentPaddingX,B.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(B.style.paddingTop=r.contentPaddingY,B.style.paddingBottom=r.contentPaddingY),n.name){let ne=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ne.style.color=r.contentTextColor:r.headerTextColor&&(ne.style.color=r.headerTextColor),ne.textContent=n.name,B.appendChild(ne)}if(n.args!==void 0){let ne=h("div","persona-space-y-1"),ke=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ke.style.color=r.labelTextColor),ke.textContent="Arguments";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=Uo(n.args),ne.append(ke,V),B.appendChild(ne)}if(n.chunks&&n.chunks.length){let ne=h("div","persona-space-y-1"),ke=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ke.style.color=r.labelTextColor),ke.textContent="Activity";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=n.chunks.join(""),ne.append(ke,V),B.appendChild(ne)}if(n.status==="complete"&&n.result!==void 0){let ne=h("div","persona-space-y-1"),ke=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ke.style.color=r.labelTextColor),ke.textContent="Result";let V=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(V.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(V.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(V.style.color=r.codeBlockTextColor),V.textContent=Uo(n.result),ne.append(ke,V),B.appendChild(ne)}if(n.status==="complete"&&typeof n.duration=="number"){let ne=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ne.style.color=r.contentTextColor),ne.textContent=`Duration: ${n.duration}ms`,B.appendChild(ne)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let ne=r.toggleTextColor||r.headerTextColor||"currentColor",ke=be(i?"chevron-up":"chevron-down",16,ne,2);ke?F.appendChild(ke):F.textContent=i?"Hide":"Show"}B.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),s.append(p,_,B),s};import{parse as sy,ARR as ay,OBJ as iy,STR as ly}from"partial-json";var gu="ask_user_question",qi=8,Zo="data-persona-ask-sheet-for",cy="Other",dy="Other\u2026",fu="Type your own answer here",hu="Send",py="Next",uy="Back",my="Submit all",gy="Skip",fy=3,zi="data-ask-current-index",Vi="data-ask-question-count",yu="data-ask-answers",Ki="data-ask-grouped",bu="data-ask-layout",hy=e=>e.layout==="pills"?"pills":"rows",yy=e=>e.getAttribute(bu)==="pills"?"pills":"rows",mu=!1,xu=e=>e.replace(/["\\]/g,"\\$&"),ro=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===gu,ti=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},oo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=sy(s,ly|iy|ay);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},Ks=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>qi&&!mu&&(mu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${qi}.`)),t.slice(0,qi)},by=e=>{var t;return(t=Ks(e)[0])!=null?t:null},xy=(e,t)=>{var n;return(n=Ks(e)[t])!=null?n:null},vu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},wu=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},vy=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=wu(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},wy=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Cy=(e,t,n,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<fy;m++)o.appendChild(wy(r));return o}if(d.forEach((m,v)=>{o.appendChild(vy(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?cy:dy;if(r==="rows"){let v=h("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=h("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(u=t.freeTextPlaceholder)!=null?u:fu,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(p=t.freeTextLabel)!=null?p:m),x.appendChild(E),v.appendChild(x);let A=wu(r,a,d.length);A&&v.appendChild(A),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=t.freeTextLabel)!=null?f:m,o.appendChild(v)}}return o},Cu=(e,t)=>{var o,a;let r=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:fu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:hu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Ay=e=>{var r;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:hu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Sy=(e,t,n)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:uy,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:gy,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(p=n.submitAllLabel)!=null?p:my:(f=n.nextLabel)!=null?f:py,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Mo=e=>{let t=e.getAttribute(yu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Au=(e,t)=>{e.setAttribute(yu,JSON.stringify(t))},ar=e=>{var n;let t=Number((n=e.getAttribute(zi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ey=(e,t)=>{e.setAttribute(zi,String(Math.max(0,Math.floor(t))))},es=e=>{var n;let t=Number((n=e.getAttribute(Vi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},so=e=>e.getAttribute(Ki)==="true",Ty=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},My=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ni=(e,t)=>{let{payload:n}=oo(t),r=Ks(n),s=Mo(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Su=e=>{let t=Mo(e),n=ar(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Eu=e=>{if(!so(e))return;let t=Mo(e),n=ar(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ji=(e,t,n)=>{let r=ti(n),s=yy(e),{payload:o,complete:a}=oo(t),i=so(e),d=ar(e),l=es(e),u=i?xy(o,d):by(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let I=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=I,v.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let I=Cy(u,r,a,s);x.replaceWith(I)}if(s!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(Cu(r,s))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!E?e.appendChild(Ay(r)):(!p||i)&&E&&E.remove(),e.setAttribute("data-multi-select",p?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=Sy(d,l,r);A?A.replaceWith(I):e.appendChild(I)}else A&&A.remove();Su(e),Eu(e)},ky=(e,t,n)=>{let r=ti(t),s=hy(r),o=e.toolCall.id,a=Ks(n),i=Math.max(1,a.length),d=i>1,l=Ty(e,a),u=d?My(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Zo,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(Vi,String(i)),p.setAttribute(zi,String(u)),p.setAttribute(Ki,d?"true":"false"),p.setAttribute(bu,s),Au(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),vu(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),p.appendChild(f);let E=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),p.appendChild(E),s!=="rows"&&p.appendChild(Cu(r,s)),Ji(p,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Ly=(e,t,n)=>{let{payload:r}=oo(t),s=Math.max(1,Ks(r).length);s>es(e)&&(e.setAttribute(Vi,String(s)),s>1&&!so(e)&&e.setAttribute(Ki,"true")),Ji(e,t,n)},Py=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=ti(t);vu(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=oo(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Js=(e,t,n)=>{if(!n||!ro(e)||ti(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${Zo}]`).forEach(l=>{l.getAttribute(Zo)!==s&&l.remove()});let a=n.querySelector(`[${Zo}="${xu(s)}"]`);if(a){Ly(a,e,t);return}let{payload:i}=oo(e),d=ky(e,t,i);n.appendChild(d)},ko=(e,t)=>{if(!e)return;let n=t?`[${Zo}="${xu(t)}"]`:`[${Zo}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Gi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ao=(e,t)=>{let n=Mo(e),r=ar(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Au(e,n),Su(e),Eu(e)},ri=(e,t,n,r)=>{let s=es(e),o=Math.max(0,Math.min(s-1,r));Ey(e,o),Ji(e,t,n)};var Xi=(e,t)=>{var x,E,A,I,P,N,L,w,W,F,_,B;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,s=(n==null?void 0:n.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!n)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=r==null?void 0:r.titleColor)!=null?A:"currentColor",u=be(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(I=r==null?void 0:r.title)!=null?I:"Approval Required",f.appendChild(m),!s){let j=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");j.setAttribute("data-approval-status",n.status),n.status==="approved"?(j.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",j.style.color="var(--persona-palette-colors-success-700, #15803d)",j.textContent="Approved"):n.status==="denied"?(j.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",j.style.color="var(--persona-palette-colors-error-700, #b91c1c)",j.textContent="Denied"):n.status==="timeout"&&(j.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",j.style.color="var(--persona-palette-colors-warning-700, #b45309)",j.textContent="Timeout"),f.appendChild(j)}p.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=n.description,p.appendChild(v),n.parameters){let j=h("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&&(j.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(j.style.color=r.parameterTextColor),j.style.fontSize="0.75rem",j.style.lineHeight="1rem",j.textContent=Uo(n.parameters),p.appendChild(j)}if(s){let j=h("div","persona-flex persona-gap-2 persona-mt-2");j.setAttribute("data-approval-buttons","true");let q=h("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");q.type="button",q.style.backgroundColor=(P=r==null?void 0:r.approveButtonColor)!=null?P:"var(--persona-approval-approve-bg, #22c55e)",q.style.color=(N=r==null?void 0:r.approveButtonTextColor)!=null?N:"#ffffff",q.setAttribute("data-approval-action","approve");let re=be("shield-check",14,(L=r==null?void 0:r.approveButtonTextColor)!=null?L:"#ffffff",2);re&&(re.style.marginRight="4px",q.appendChild(re));let Ie=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");q.appendChild(Ie);let Re=h("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");Re.type="button",Re.style.backgroundColor=(W=r==null?void 0:r.denyButtonColor)!=null?W:"transparent",Re.style.color=(F=r==null?void 0:r.denyButtonTextColor)!=null?F:"var(--persona-feedback-error, #dc2626)",Re.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Re.setAttribute("data-approval-action","deny");let Ne=be("shield-x",14,(_=r==null?void 0:r.denyButtonTextColor)!=null?_:"var(--persona-feedback-error, #dc2626)",2);Ne&&(Ne.style.marginRight="4px",Re.appendChild(Ne));let ce=document.createTextNode((B=r==null?void 0:r.denyLabel)!=null?B:"Deny");Re.appendChild(ce),j.append(q,Re),p.appendChild(j)}return a.append(i,p),o.appendChild(a),o};var Tu=e=>{let t=[];return{buttons:t,render:(r,s,o,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){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'}};r.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(v),t.push(v)}),e.appendChild(u)}}};var Gs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xs=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{t(o.result)},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)r.put(s)}catch{}}};var Iy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Wy=new Set(["step_start","execution_start"]),Ry=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Hy=new Set(["step_complete","agent_turn_complete"]),By=new Set(["flow_complete","agent_complete"]),Mu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Lu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Lo=(e,t)=>{let n=e[t];return Lu(n)?n:void 0};function Qi(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function oi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Dy(e,t){return typeof t.type=="string"?t.type:e}function Ny(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Oy(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function ku(e){var r,s,o,a,i;let t=Lo(e,"result"),n=[Lo(e,"tokens"),Lo(e,"totalTokens"),t?Lo(t,"tokens"):void 0,Lo(e,"usage"),t?Lo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(s=(r=Gn(d.output))!=null?r:Gn(d.outputTokens))!=null?s:Gn(d.completionTokens);if(l!==void 0)return l}return(i=(o=Gn(e.outputTokens))!=null?o:Gn(e.completionTokens))!=null?i:t?(a=Gn(t.outputTokens))!=null?a:Gn(t.completionTokens):void 0}function Fy(e){var n,r,s,o,a;let t=Lo(e,"result");return(a=(s=(r=(n=Gn(e.executionTime))!=null?n:Gn(e.executionTimeMs))!=null?r:Gn(e.execution_time))!=null?s:Gn(e.duration))!=null?a:t?(o=Gn(t.executionTime))!=null?o:Gn(t.executionTimeMs):void 0}function _y(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(t=_y){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:oi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var o;if(!Lu(n)){Mu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Dy(t,n),s=this.now();if(Iy.has(r)){this.startRun(s);return}if(Wy.has(r)){this.run||this.startRun(s);return}if(Ry.has(r)){if(!Oy(r,n))return;let a=Ny(n);if(!a)return;this.run||this.startRun(s);let i=this.run;(o=i.firstDeltaAt)!=null||(i.firstDeltaAt=s),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Qi(i.visibleCharCount),l=s-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:oi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Hy.has(r)){if(!this.run)return;let a=this.run,i=ku(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Qi(a.visibleCharCount),u=this.resolveDuration(a,n,s);this.metric={status:"running",tokensPerSecond:oi(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(By.has(r)){if(!this.run)return;let a=this.run,i=ku(n),d=i!=null?i:a.exactOutputTokens+Qi(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,s);this.metric={status:"complete",tokensPerSecond:oi(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(Mu.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let s=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=Fy(n);return o!=null?o:r-t.startedAt}};function ts(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var $y={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)"}},jy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Uy=["flowName","stepName","reasoningText","text","name","tool","toolName"],qy=100;function zy(e,t){let n={...$y,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return jy}function Vy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Ky(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),o=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${s}.${o}`}function Jy(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let s=r.split("."),o=n;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Gy(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function Xy(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Qy(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Yy(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Zy(e,t,n){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=t.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&n){let i=o.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("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=h("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 Yi(e,t,n,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ts(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var q,re;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=be(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(q=r.timestampFormat)!=null?q:"relative";A.textContent=I==="relative"?Vy(e.timestamp,n):Ky(e.timestamp);let P=null;r.showSequenceNumbers!==!1&&(P=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let N=zy(e.type,r.badgeColors),L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=N.bg,L.style.color=N.text,L.style.borderColor=N.text+"50",L.textContent=e.type;let w=(re=r.descriptionFields)!=null?re:Uy,W=Jy(e.payload,w),F=null;W&&(F=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=W);let _=h("div","persona-flex-1 persona-min-w-0"),B=h("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=be("clipboard","12px","currentColor",1.5);return j&&B.appendChild(j),B.addEventListener("click",async Ie=>{Ie.stopPropagation(),await Gy(Xy(e)),B.innerHTML="";let Re=be("check","12px","currentColor",1.5);Re&&B.appendChild(Re),setTimeout(()=>{B.innerHTML="";let Ne=be("clipboard","12px","currentColor",1.5);Ne&&B.appendChild(Ne)},1500)}),v.appendChild(x),v.appendChild(A),P&&v.appendChild(P),v.appendChild(L),F&&v.appendChild(F),v.appendChild(_),v.appendChild(B),m.appendChild(v),d&&m.appendChild(Zy(e,a,i)),m}}function Pu(e){var v,x,E,A,I;let{buffer:t,getFullHistory:n,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(v=s==null?void 0:s.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",u=(E=i==null?void 0:i.label)!=null?E:"",p=(I=(A=s==null?void 0:s.features)==null?void 0:A.eventStream)!=null?I:{},f=o.find(P=>P.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let P=f.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=p.classNames,N=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ts(N,P==null?void 0:P.panel);let L=[],w="",W="",F=null,_=[],B={},j=0,q=Oa(),re=0,Ie=0,Re=!1,Ne=null,ce=!1,ve=0,Me=new Set,Le=new Map,ne="",ke="",V=null,pe,fe,me,ue,Ge,z=null,te=null,We=null;function ge(){let se=h("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ye=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");ts(ye,P==null?void 0:P.headerBar);let wt=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(wt.textContent="Events",pe=h("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"),pe.textContent="0",a){te=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),te.style.cursor="help";let Bn=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Bn.textContent="Throughput",z=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),z.textContent="-- tok/s",We=h("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"),We.style.display="none",We.style.pointerEvents="none";let Qn=te,bn=We,Dn=()=>{if(!bn.textContent)return;let xr=Qn.getBoundingClientRect(),Nn=se.getBoundingClientRect();bn.style.left=`${xr.left-Nn.left}px`,bn.style.top=`${xr.bottom-Nn.top+4}px`,bn.style.display="block"},ut=()=>{bn.style.display="none"};te.addEventListener("mouseenter",Dn),te.addEventListener("mouseleave",ut),te.appendChild(Bn),te.appendChild(z)}let _t=h("div","persona-flex-1");fe=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Zt=h("option","");Zt.value="",Zt.textContent="All events",fe.appendChild(Zt),me=h("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"),me.type="button",me.title="Copy All";let Tt=be("clipboard-copy","12px","currentColor",1.5);Tt&&me.appendChild(Tt);let St=h("span","persona-text-xs");St.textContent="Copy All",me.appendChild(St),ye.appendChild(wt),ye.appendChild(pe),te&&ye.appendChild(te),ye.appendChild(_t),ye.appendChild(fe),ye.appendChild(me);let ht=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ts(ht,P==null?void 0:P.searchBar);let bt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),qt=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&qt.appendChild(bt),ue=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ts(ue,P==null?void 0:P.searchInput),ue.type="text",ue.placeholder="Search event payloads...",Ge=h("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"),Ge.type="button",Ge.style.display="none";let et=be("x","12px","currentColor",2);return et&&Ge.appendChild(et),ht.appendChild(qt),ht.appendChild(ue),ht.appendChild(Ge),se.appendChild(ye),se.appendChild(ht),We&&se.appendChild(We),se}let ie,ae=o.find(se=>se.renderEventStreamToolbar);if(ae!=null&&ae.renderEventStreamToolbar&&s){let se=ae.renderEventStreamToolbar({config:s,defaultRenderer:()=>ge(),eventCount:t.getSize(),filteredCount:0,onFilterChange:ye=>{w=ye,Hn(),oe()},onSearchChange:ye=>{W=ye,Hn(),oe()}});ie=se!=null?se:ge()}else ie=ge();let Qe=h("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");Qe.style.display="none";function Ce(){if(!a||!z||!te)return;let se=a();z.textContent=Qy(se);let ye=Yy(se);We&&(We.textContent=ye,ye||(We.style.display="none")),ye?te.setAttribute("aria-label",ye):te.removeAttribute("aria-label")}let de=h("div","persona-flex-1 persona-min-h-0 persona-relative"),X=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");X.style.height="100%";let $e=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ts($e,P==null?void 0:P.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let Ct=be(l,"14px","currentColor",2);Ct&&$e.appendChild(Ct);let G=h("span","");G.textContent=u,$e.appendChild(G);let Oe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Oe.style.display="none",de.appendChild(X),de.appendChild(Oe),de.appendChild($e),N.setAttribute("tabindex","0"),N.appendChild(ie),N.appendChild(Qe),N.appendChild(de);function Mn(){let se=t.getAll(),ye={};for(let St of se)ye[St.type]=(ye[St.type]||0)+1;let wt=Object.keys(ye).sort(),_t=wt.length!==_.length||!wt.every((St,ht)=>St===_[ht]),Zt=!_t&&wt.some(St=>ye[St]!==B[St]),yn=se.length!==Object.values(B).reduce((St,ht)=>St+ht,0);if(!_t&&!Zt&&!yn||(_=wt,B=ye,!fe))return;let Tt=fe.value;if(fe.options[0].textContent="All events",_t){for(;fe.options.length>1;)fe.remove(1);for(let St of wt){let ht=h("option","");ht.value=St,ht.textContent=`${St} (${ye[St]||0})`,fe.appendChild(ht)}Tt&&wt.includes(Tt)?fe.value=Tt:Tt&&(fe.value="",w="")}else for(let St=1;St<fe.options.length;St++){let ht=fe.options[St];ht.textContent=`${ht.value} (${ye[ht.value]||0})`}}function Dt(){let se=t.getAll();if(w&&(se=se.filter(ye=>ye.type===w)),W){let ye=W.toLowerCase();se=se.filter(wt=>wt.type.toLowerCase().includes(ye)||wt.payload.toLowerCase().includes(ye))}return se}function ln(){return w!==""||W!==""}function Hn(){j=0,re=0,q.resume(),$e.style.display="none"}function Xn(se){Me.has(se)?Me.delete(se):Me.add(se),V=se;let ye=X.scrollTop,wt=q.isFollowing();ce=!0,q.pause(),oe(),X.scrollTop=ye,wt&&q.resume(),ce=!1}function H(){return Ds(X,50)}function oe(){Ie=Date.now(),Re=!1,Ce(),Mn();let se=t.getEvictedCount();se>0?(Qe.textContent=`${se.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",L=Dt();let ye=L.length,wt=t.getSize()>0;pe&&(pe.textContent=String(t.getSize())),ye===0&&wt&&ln()?(Oe.textContent=W?`No events matching '${W}'`:"No events matching filter",Oe.style.display="",X.style.display="none"):(Oe.style.display="none",X.style.display=""),me&&(me.title=ln()?`Copy Filtered (${ye})`:"Copy All"),d&&!q.isFollowing()&&ye>j&&(re+=ye-j,G.textContent=u?`${u}${re>0?` (${re})`:""}`:"",$e.style.display=""),j=ye;let _t=t.getAll(),Zt=_t.length>0?_t[0].timestamp:0,yn=new Set(L.map(ht=>ht.id));for(let ht of Me)yn.has(ht)||Me.delete(ht);let Tt=w!==ne||W!==ke,St=Le.size===0&&L.length>0;if(Tt||St||L.length===0){X.innerHTML="",Le.clear();let ht=document.createDocumentFragment();for(let bt=0;bt<L.length;bt++){let qt=Yi(L[bt],bt,Zt,p,Me,Xn,o,s);Le.set(L[bt].id,qt),ht.appendChild(qt)}X.appendChild(ht),ne=w,ke=W,V=null}else{if(V!==null){let bt=Le.get(V);if(bt&&bt.parentNode===X){let qt=L.findIndex(et=>et.id===V);if(qt>=0){let et=Yi(L[qt],qt,Zt,p,Me,Xn,o,s);X.insertBefore(et,bt),bt.remove(),Le.set(V,et)}}V=null}let ht=new Set(L.map(bt=>bt.id));for(let[bt,qt]of Le)ht.has(bt)||(qt.remove(),Le.delete(bt));for(let bt=0;bt<L.length;bt++){let qt=L[bt];if(!Le.has(qt.id)){let et=Yi(qt,bt,Zt,p,Me,Xn,o,s);Le.set(qt.id,et),X.appendChild(et)}}}q.isFollowing()&&(X.scrollTop=X.scrollHeight)}function Be(){if(Date.now()-Ie>=qy){Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),oe();return}Re||(Re=!0,Ne=requestAnimationFrame(()=>{Ne=null,oe()}))}let Xe=(se,ye)=>{if(!me)return;me.innerHTML="";let wt=be(se,"12px","currentColor",1.5);wt&&me.appendChild(wt);let _t=h("span","persona-text-xs");_t.textContent="Copy All",me.appendChild(_t),setTimeout(()=>{me.innerHTML="";let Zt=be("clipboard-copy","12px","currentColor",1.5);Zt&&me.appendChild(Zt);let yn=h("span","persona-text-xs");yn.textContent="Copy All",me.appendChild(yn),me.disabled=!1},ye)},Fe=async()=>{if(me){me.disabled=!0;try{let se;ln()?se=L:n?(se=await n(),se.length===0&&(se=t.getAll())):se=t.getAll();let ye=se.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),Xe("check",1500)}catch{Xe("x",1500)}}},_e=()=>{fe&&(w=fe.value,Hn(),oe())},rt=()=>{!ue||!Ge||(Ge.style.display=ue.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{W=ue.value,Hn(),oe()},150))},At=()=>{!ue||!Ge||(ue.value="",W="",Ge.style.display="none",F&&clearTimeout(F),Hn(),oe())},Ft=()=>{if(ce)return;let se=X.scrollTop,{action:ye,nextLastScrollTop:wt}=Fa({following:q.isFollowing(),currentScrollTop:se,lastScrollTop:ve,nearBottom:H(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ve=wt,ye==="resume"?(q.resume(),re=0,$e.style.display="none"):ye==="pause"&&(q.pause(),d&&(G.textContent=u,$e.style.display=""))},Kt=se=>{let ye=_a({following:q.isFollowing(),deltaY:se.deltaY,nearBottom:H(),resumeWhenNearBottom:!0});ye==="pause"?(q.pause(),d&&(G.textContent=u,$e.style.display="")):ye==="resume"&&(q.resume(),re=0,$e.style.display="none")},K=()=>{d&&(X.scrollTop=X.scrollHeight,q.resume(),re=0,$e.style.display="none")},gt=se=>{let ye=se.target;if(!ye||ye.closest("button"))return;let wt=ye.closest("[data-event-id]");if(!wt)return;let _t=wt.getAttribute("data-event-id");_t&&Xn(_t)},nt=se=>{if((se.metaKey||se.ctrlKey)&&se.key==="f"){se.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}se.key==="Escape"&&(ue&&document.activeElement===ue?(At(),ue.blur(),N.focus()):r&&r())};me&&me.addEventListener("click",Fe),fe&&fe.addEventListener("change",_e),ue&&ue.addEventListener("input",rt),Ge&&Ge.addEventListener("click",At),X.addEventListener("scroll",Ft),X.addEventListener("wheel",Kt,{passive:!0}),X.addEventListener("click",gt),$e.addEventListener("click",K),N.addEventListener("keydown",nt);function Ut(){F&&clearTimeout(F),Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),Re=!1,Le.clear(),me&&me.removeEventListener("click",Fe),fe&&fe.removeEventListener("change",_e),ue&&ue.removeEventListener("input",rt),Ge&&Ge.removeEventListener("click",At),X.removeEventListener("scroll",Ft),X.removeEventListener("wheel",Kt),X.removeEventListener("click",gt),$e.removeEventListener("click",K),N.removeEventListener("keydown",nt)}return{element:N,update:Be,destroy:Ut}}}function Iu(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(l.append(u,p),i.append(d,l),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Wu=(e,t)=>{var r,s,o;let n=(o=(s=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Iu(e,t)});if(u)return u}return Iu(e,t)};var Zi=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},io=new Zi;io.register("PersonaArtifactCard",Wu);function eb(e){var s;let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),t.appendChild(n),t.appendChild(r),t}function Ru(e,t){var fe,me,ue,Ge;let n=(me=(fe=e.features)==null?void 0:fe.artifacts)==null?void 0:me.layout,s=((ue=n==null?void 0:n.toolbarPreset)!=null?ue:"default")==="document",o=(Ge=n==null?void 0:n.panePadding)==null?void 0:Ge.trim(),a=e.markdown?$o(e.markdown):null,i=Es(e.sanitize),d=z=>{let te=a?a(z):jo(z);return i?i(te):te},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};l&&l.addEventListener("click",()=>{var z;u(),(z=t.onDismiss)==null||z.call(t)});let p=h("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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var z;u(),(z=t.onDismiss)==null||z.call(t)});let x="rendered",E=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),A=s?jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):jt({icon:"eye",label:"Rendered view"}),I=s?jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):jt({icon:"code-2",label:"Source"}),P=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),N=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,L=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,w=n==null?void 0:n.documentToolbarCopyMenuItems,W=!!(L&&w&&w.length>0),F=null,_,B=null,j=null;if(s&&(N||L)&&!W){if(_=N?Ka({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let z=be("chevron-down",14,"currentColor",2);z&&_.appendChild(z)}}else s&&W?(F=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=N?Ka({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B=jt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append(_,B)):s?_=jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):_=jt({icon:"copy",label:"Copy"});let q=s?jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):jt({icon:"refresh-cw",label:"Refresh"}),re=s?jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):jt({icon:"x",label:"Close"}),Ie=()=>{var ie,ae,Qe;let z=(ie=Le.find(Ce=>Ce.id===ne))!=null?ie:Le[Le.length-1],te=(ae=z==null?void 0:z.id)!=null?ae:null,We=(z==null?void 0:z.artifactType)==="markdown"&&(Qe=z.markdown)!=null?Qe:"",ge=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:We,jsonPayload:ge,id:te}},Re=async()=>{var ie;let{markdown:z,jsonPayload:te}=Ie(),We=(ie=Le.find(ae=>ae.id===ne))!=null?ie:Le[Le.length-1],ge=(We==null?void 0:We.artifactType)==="markdown"?z:We?te:"";try{await navigator.clipboard.writeText(ge)}catch{}};if(_.addEventListener("click",async()=>{let z=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(z&&W){let{markdown:te,jsonPayload:We,id:ge}=Ie();try{await z({actionId:"primary",artifactId:ge,markdown:te,jsonPayload:We})}catch{}return}await Re()}),B&&(w!=null&&w.length)){let z=()=>{var We;return(We=p.closest("[data-persona-root]"))!=null?We:document.body},te=()=>{j=To({items:w.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:ge,jsonPayload:ie,id:ae}=Ie(),Qe=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Qe?await Qe({actionId:We,artifactId:ae,markdown:ge,jsonPayload:ie}):We==="markdown"||We==="md"?await navigator.clipboard.writeText(ge):We==="json"||We==="source"?await navigator.clipboard.writeText(ie):await navigator.clipboard.writeText(ge||ie)}catch{}},anchor:F!=null?F:B,position:"bottom-right",portal:z()})};p.isConnected?te():requestAnimationFrame(te),B.addEventListener("click",We=>{We.stopPropagation(),j==null||j.toggle()})}q.addEventListener("click",async()=>{var z;try{await((z=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:z.call(n))}catch{}V()}),re.addEventListener("click",()=>{var z;u(),(z=t.onDismiss)==null||z.call(t)});let Ne=()=>{s&&(A.setAttribute("aria-pressed",x==="rendered"?"true":"false"),I.setAttribute("aria-pressed",x==="source"?"true":"false"))};A.addEventListener("click",()=>{x="rendered",Ne(),V()}),I.addEventListener("click",()=>{x="source",Ne(),V()});let ce=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),E.append(A,I),F?P.append(F,q,re):P.append(_,q,re),f.append(E,ce,P),Ne()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ve=h("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"),Me=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ve.style.paddingLeft=o,ve.style.paddingRight=o,Me.style.padding=o),p.appendChild(f),p.appendChild(ve),p.appendChild(Me);let Le=[],ne=null,ke=!1,V=()=>{var ge,ie,ae,Qe;let z=s&&Le.length<=1;ve.classList.toggle("persona-hidden",z),ve.replaceChildren();for(let Ce of Le){let de=h("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");de.type="button",de.textContent=Ce.title||Ce.id.slice(0,8),Ce.id===ne&&de.classList.add("persona-bg-persona-container","persona-border-persona-border"),de.addEventListener("click",()=>t.onSelect(Ce.id)),ve.appendChild(de)}Me.replaceChildren();let te=ne&&Le.find(Ce=>Ce.id===ne)||Le[Le.length-1];if(!te)return;if(s){let Ce=te.artifactType==="markdown"?"MD":(ge=te.component)!=null?ge:"Component",X=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${X} \xB7 ${Ce}`}else m.textContent="Artifacts";if(te.artifactType==="markdown"){if(s&&x==="source"){let de=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");de.textContent=(ie=te.markdown)!=null?ie:"",Me.appendChild(de);return}let Ce=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ce.innerHTML=d((ae=te.markdown)!=null?ae:""),Me.appendChild(Ce);return}let We=te.component?io.get(te.component):void 0;if(We){let de={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=We((Qe=te.props)!=null?Qe:{},de);if(X){Me.appendChild(X);return}}catch{}}Me.appendChild(eb(te))},pe=()=>{var te;let z=Le.length>0;if(p.classList.toggle("persona-hidden",!z),l){let We=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,ie=((te=We==null?void 0:We.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;z&&ie&&ke?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(z){var te,We,ge;Le=z.artifacts,ne=(ge=(We=z.selectedId)!=null?We:(te=z.artifacts[z.artifacts.length-1])==null?void 0:te.id)!=null?ge:null,Le.length>0&&(ke=!0),V(),pe()},setMobileOpen(z){ke=z,!z&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):pe()}}}function ir(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Hu(e,t){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ir(t))return;let n=(a=(o=t.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),s=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function tb(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function si(e,t){var d,l,u,p,f,m,v,x,E,A;if(!ir(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),tb(e),Hu(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(A=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:A.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Hu(e,t)}var Bu=["panel","seamless"];function ai(e,t){var i,d,l,u,p,f;for(let m of Bu)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!ir(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",s=Bu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Du(e,t){var n,r,s;return!t||!ir(e)?!1:((s=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function nb(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function rb(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function ob(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function sb(e,t,n,r){let s=e-r-2*t-n;return Math.max(0,s)}function Nu(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Ou(e,t,n,r,s,o){let a=nb(s,200),i=sb(t,n,r,200);i=Math.max(a,i);let d=rb(o);return d!==null&&(i=Math.min(i,d)),ob(e,a,i)}var Fu={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"}},el=(e,t,n,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,E;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=Fu[a])!=null?x:Fu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let A=h("p","persona-text-sm persona-text-persona-muted");A.textContent=i.description,d.appendChild(A)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(A=>{var w,W;let I=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${t.id}-${a}-${A.name}`;let P=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=A.label,I.appendChild(P);let N=(w=A.type)!=null?w:"text",L;N==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=N),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${t.id}-${a}-${A.name}`,L.name=A.name,L.placeholder=(W=A.placeholder)!=null?W:"",A.required&&(L.required=!0),I.appendChild(L),u.appendChild(I)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async A=>{var L,w;A.preventDefault();let I=(L=n.formEndpoint)!=null?L:"/form",P=new FormData(u),N={};P.forEach((W,F)=>{N[F]=W}),N.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let W=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let F=await W.json();f.textContent=(w=F.message)!=null?w:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(W){f.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var tl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,s;return((r=n.priority)!=null?r:0)-((s=t.priority)!=null?s:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(o=>o.id));return[...n.filter(o=>!r.has(o.id)),...t].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},ii=new tl;var _u=()=>{let e=new Map,t=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>n(s,o)),n=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:t,off:n,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var ab=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ib=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let s=n;s<t.length;s+=1){let o=t[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return t.slice(n,s+1)}return null},li=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=ab(e),n=ib(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},nl=e=>typeof e=="string"?e:e==null?"":String(e),ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:nl(e.payload.text)},messageAndClick:(e,t)=>{var s;if(e.type!=="message_and_click")return;let n=e.payload,r=nl(n.element);if(r&&((s=t.document)!=null&&s.querySelector)){let o=t.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:nl(n.text)}}},$u=e=>Array.isArray(e)?e.map(t=>String(t)):[],ci=e=>{let t=new Set($u(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set($u(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||t.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;t.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var lb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},cb=e=>e.map(t=>({...t,streaming:!1})),db=e=>e.map(t=>({...t,status:"complete"})),rl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?lb(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let s={...n,messages:n.messages?cb(n.messages):void 0,artifacts:n.artifacts?db(n.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as pb,STR as ub,OBJ as mb}from"partial-json";function gb(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function fb(e,t){if(!gb(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function ol(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let s=pb(n,ub|mb),o=fb(s,n);o&&(e=o)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function hb(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function sl(e,t){let{config:n,message:r,onPropsUpdate:s}=t,o=io.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function yb(){let e=ol();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ju(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function al(e){let t=ju(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function il(e){let t=ju(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var bb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ll(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=bb}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,m.appendChild(x),f.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let w=1;w<=5;w++){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",`${w} star${w>1?"s":""}: ${l[w-1]}`),W.title=l[w-1],W.dataset.rating=String(w),W.innerHTML=`
27
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
28
28
  <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>
29
29
  </svg>
30
- `,B.addEventListener("click",()=>{p=w,A.forEach((F,$)=>{let W=$<w;F.classList.toggle("selected",W),F.setAttribute("aria-checked",$===w-1?"true":"false")})}),A.push(B),S.appendChild(B)}f.appendChild(S);let k=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),w.appendChild(k),f.appendChild(w)}let R=document.createElement("div");R.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{t==null||t(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(p===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=(k==null?void 0:k.value.trim())||void 0;await n(p,w),u.remove()}catch(w){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),R.appendChild(H),R.appendChild(L),f.appendChild(R),u.appendChild(f),u}function ol(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=s,v.appendChild(S),m.appendChild(v);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=u,k.appendChild(R),k.appendChild(H);let L=document.createElement("div");L.className="persona-feedback-numbers";let w=[];for(let O=0;O<=10;O++){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 ${O} out of 10`),V.textContent=String(O),V.dataset.rating=String(O),O<=6?V.classList.add("persona-feedback-detractor"):O<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=O,w.forEach((oe,Ie)=>{oe.classList.toggle("selected",Ie===O),oe.setAttribute("aria-checked",Ie===O?"true":"false")})}),w.push(V),L.appendChild(V)}A.appendChild(k),A.appendChild(L),m.appendChild(A);let B=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),O.appendChild(B),m.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{t==null||t(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let O=(B==null?void 0:B.value.trim())||void 0;await n(f,O),p.remove()}catch(O){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),F.appendChild($),F.appendChild(W),m.appendChild(F),p.appendChild(m),p}var es="persona-chat-history",Qy=30*1e3,Zy={"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 eb(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.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){n.push(i);continue}let d=(s=Zy[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function ai(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function tb(e){var n,t,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function nb(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var sl=e=>!e||typeof e!="object"?{}:{...e},Hu=e=>e.map(n=>({...n,streaming:!1})),Bu=(e,n,t)=>{let r=e!=null&&e.markdown?Oo(e.markdown):null,s=Cs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=Fo(a),s?s(d):d}};function Du(e){var i,d,l,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=fe(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,n.appendChild(p)}return n}var al=(e,n,t)=>{var Al,Sl,El,Tl,Ml,kl,Ll,Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Ol,Fl,$l,_l,jl,Ul,ql,zl,Vl,Kl,Jl,Gl,Xl,Yl,Ql,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Ei(n),s=ri.getForInstance(r.plugins);r.components&&so.registerAll(r.components);let o=Iu(),i=r.persistState===!1?null:(Al=r.storageAdapter)!=null?Al:Qi(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let g=r.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:b}=g;return b&&(u=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=c!=null?c:{messages:[],metadata:{}},y=p(g);y.metadata&&(d=sl(y.metadata)),(Sl=y.messages)!=null&&Sl.length&&(r={...r,initialMessages:y.messages}),(El=y.artifacts)!=null&&El.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Tl=y.selectedArtifactId)!=null?Tl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=p({messages:[],metadata:{}});(Ml=c.messages)!=null&&Ml.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var y;d=(y=c({...d}))!=null?y:{},Po()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[oi],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Zo.message,Zo.messageAndClick],S=si({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let A=(Ll=(kl=r.launcher)==null?void 0:kl.enabled)!=null?Ll:!0,k=(Il=(Pl=r.launcher)==null?void 0:Pl.autoExpand)!=null?Il:!1,R=(Wl=r.autoFocusInput)!=null?Wl:!1,H=k,L=A,w=(Hl=(Rl=r.layout)==null?void 0:Rl.header)==null?void 0:Hl.layout,B=!1,F=()=>Zr(r),$=()=>A||F(),W=F()?!1:A?k:!0,O=!1,V=null,oe=()=>{O=!0,V&&clearTimeout(V),V=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},Ie=Bu(r,S,oe),Pe=(Dl=(Bl=r.features)==null?void 0:Bl.showReasoning)!=null?Dl:!0,ze=(Ol=(Nl=r.features)==null?void 0:Nl.showToolCalls)!=null?Ol:!0,pe=($l=(Fl=r.features)==null?void 0:Fl.showEventStreamToggle)!=null?$l:!1,ce=(jl=(_l=r.features)==null?void 0:_l.scrollToBottom)!=null?jl:{},je=`${(ql=typeof r.persistState=="object"?(Ul=r.persistState)==null?void 0:Ul.keyPrefix:void 0)!=null?ql:"persona-"}event-stream`,te=pe?new Ks(je):null,xe=(Kl=(Vl=(zl=r.features)==null?void 0:zl.eventStream)==null?void 0:Vl.maxEvents)!=null?Kl:2e3,G=pe?new Vs(xe,te):null,ae=null,He=!1,ue=null,Re=0;te==null||te.open().then(()=>G==null?void 0:G.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let tt={onCopy:c=>{var g,y;o.emit("message:copy",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onCopy)==null||y.call(g,c)},onFeedback:c=>{var g,y;o.emit("message:feedback",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},K=(Jl=r.statusIndicator)!=null?Jl:{},se=c=>{var g,y,b,T;return c==="idle"?(g=K.idleText)!=null?g:mn.idle:c==="connecting"?(y=K.connectingText)!=null?y:mn.connecting:c==="connected"?(b=K.connectedText)!=null?b:mn.connected:c==="error"?(T=K.errorText)!=null?T:mn.error:mn[c]};function Oe(c,g,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let T=document.createElement("a");T.href=y.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=g,T.style.color="inherit",T.style.textDecoration="none",c.appendChild(T)}else c.textContent=g}let{wrapper:J,panel:z,pillRoot:we}=Zp(r),$e=eu(r,$()),{container:ne,body:Te,messagesWrapper:ve,suggestions:Ht,textarea:ie,sendButton:re,sendButtonWrapper:sn,composerForm:Nt,statusText:zt,introTitle:vr,introSubtitle:dr,closeButton:Ue,iconHolder:U,headerTitle:Ae,headerSubtitle:Be,header:De,footer:_e,actionsRow:ct,leftActions:nt,rightActions:Ct}=$e,jt=$e.setSendButtonMode,P=$e.micButton,he=$e.micButtonWrapper,ge=$e.attachmentButton,dt=$e.attachmentButtonWrapper,Ke=$e.attachmentInput,It=$e.attachmentPreviewsContainer;ne.classList.add("persona-relative"),Te.classList.add("persona-relative");let an=12,At=()=>{var c;return(c=ce.label)!=null?c:""},bt=()=>{var c;return(c=ce.iconName)!=null?c:"arrow-down"},Mt=()=>ce.enabled!==!1,ut=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");ut.type="button",ut.style.display="none",ut.setAttribute("data-persona-scroll-to-bottom","true");let Vt=h("span","persona-flex persona-items-center"),wr=h("span","");ut.append(Vt,wr),ne.appendChild(ut);let _n=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;ut.style.bottom=`${g+an}px`};_n();let Br=()=>{let c=!!At();ut.setAttribute("aria-label",At()||"Jump to latest"),ut.title=At(),ut.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Vt.innerHTML="";let g=fe(bt(),"14px","currentColor",2);g?(Vt.appendChild(g),Vt.style.display=""):Vt.style.display="none",wr.textContent=At(),wr.style.display=c?"":"none"};Br();let vt=null,pr=null,ur=s.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:r,defaultRenderer:()=>{let g=eo({config:r,showClose:$()});return Vo(ne,g,r),g.header},onClose:()=>Rt(!1,"user")});if(c){let g=ne.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let Cr=()=>{var g,y,b,T;if(!G)return;if(He=!0,!ae&&G&&(ae=wu({buffer:G,getFullHistory:()=>G.getAllFromStore(),onClose:()=>Qn(),config:r,plugins:s})),ae&&(Te.style.display="none",(g=_e.parentNode)==null||g.insertBefore(ae.element,_e),ae.update()),gt){gt.style.boxShadow=`inset 0 0 0 1.5px ${An.actionIconColor}`;let D=(T=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(N=>N&&gt.classList.add(N))}let c=()=>{if(!He)return;let D=Date.now();D-Re>=200&&(ae==null||ae.update(),Re=D),ue=requestAnimationFrame(c)};Re=0,ue=requestAnimationFrame(c),kr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Qn=()=>{var c,g,y;if(He){if(He=!1,ae&&ae.element.remove(),Te.style.display="",gt){gt.style.boxShadow="";let b=(y=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&gt.classList.remove(T))}ue!==null&&(cancelAnimationFrame(ue),ue=null),kr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},gt=null;if(pe){let c=(Xl=(Gl=r.features)==null?void 0:Gl.eventStream)==null?void 0:Xl.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");gt=h("button",g),gt.style.width="28px",gt.style.height="28px",gt.style.color=An.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let y=fe("activity","18px","currentColor",1.5);y&&gt.appendChild(y);let b=$e.clearChatButtonWrapper,T=$e.closeButtonWrapper,D=b||T;D&&D.parentNode===De?De.insertBefore(gt,D):De.appendChild(gt),gt.addEventListener("click",()=>{He?Qn():Cr()})}let io=c=>{var b,T,D;let g=r.attachments;if(!(g!=null&&g.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(y,N):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=h("input");N.type="file",N.accept=((b=g.allowedTypes)!=null?b:Rr).join(","),N.multiple=((T=g.maxFiles)!=null?T:4)>1,N.style.display="none",N.setAttribute("aria-label",(D=g.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(N)}},mr=s.find(c=>c.renderComposer);if(mr!=null&&mr.renderComposer){let c=r.composer,g=mr.renderComposer({config:r,defaultRenderer:()=>js({config:r}).footer,onSubmit:y=>{var N;if(!_||_.isStreaming())return;let b=y.trim(),T=(N=vt==null?void 0:vt.hasAttachments())!=null?N:!1;if(!b&&!T)return;ps();let D;T&&(D=[],D.push(...vt.getContentParts()),b&&D.push(Ta(b))),_.sendMessage(b,{contentParts:D}),T&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Yl=r.voiceRecognition)==null?void 0:Yl.enabled)===!0?()=>{pr==null||pr()}:void 0});g&&(_e.replaceWith(g),_e=g)}let lo=c=>{let g=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),T=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");g&&(Nt=g),y&&(ie=y),b&&(re=b),T&&(P=T,he=T.parentElement),D&&(zt=D);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Ht=N);let q=c.querySelector(".persona-attachment-button");q&&(ge=q,dt=q.parentElement),Ke=c.querySelector('input[type="file"]'),It=c.querySelector(".persona-attachment-previews");let I=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");I&&(ct=I)};io(_e),lo(_e);let Sn=(nc=(Ql=r.layout)==null?void 0:Ql.contentMaxWidth)!=null?nc:F()?(tc=(ec=(Zl=r.launcher)==null?void 0:Zl.composerBar)==null?void 0:ec.contentMaxWidth)!=null?tc:"720px":void 0;if(Sn&&(ve.style.maxWidth=Sn,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%"),Sn&&Nt&&!F()&&(Nt.style.maxWidth=Sn,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Sn&&Ht&&!F()&&(Ht.style.maxWidth=Sn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Sn&&It&&!F()&&(It.style.maxWidth=Sn,It.style.marginLeft="auto",It.style.marginRight="auto"),(rc=r.attachments)!=null&&rc.enabled&&Ke&&It){vt=qo.fromConfig(r.attachments),vt.setPreviewsContainer(It),Ke.addEventListener("change",y=>{let b=y.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,g=Du(c);ne.appendChild(g)}(()=>{var b,T;let c=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},g=D=>{switch(D){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ve;case"footer-top":return Ht;case"composer":return Nt;case"footer-bottom":return zt;default:return null}},y=(D,N)=>{var q;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")De.insertBefore(N,De.firstChild);else if(D==="header-right")De.appendChild(N);else{let I=De.querySelector(".persona-flex-col");I?(q=I.parentNode)==null||q.insertBefore(N,I.nextSibling):De.appendChild(N)}break;case"body-top":{let I=Te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(N):Te.insertBefore(N,Te.firstChild);break}case"body-bottom":Te.appendChild(N);break;case"footer-top":Ht.replaceWith(N);break;case"footer-bottom":zt.replaceWith(N);break;default:break}};for(let[D,N]of Object.entries(c))if(N)try{let q=N({config:r,defaultContent:()=>g(D)});q&&y(D,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,q)}})();let Dr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=y.getAttribute("data-bubble-type");D==="reasoning"?(Jo.has(T)?Jo.delete(T):Jo.add(T),su(T,b)):D==="tool"&&(Go.has(T)?Go.delete(T):Go.add(T),au(T,b,r)),Nn.delete(T)};ve.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dr(c))}),ve.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dr(c))});let Ar=new Map;ve.addEventListener("click",c=>{var N;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let D=y.getAttribute("data-action");if(D==="copy"){let I=_.getMessages().find(be=>be.id===T);if(I&&tt.onCopy){let be=I.content||"";navigator.clipboard.writeText(be).then(()=>{y.classList.add("persona-message-action-success");let le=fe("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ee=fe("copy",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),tt.onCopy(I)}}else if(D==="upvote"||D==="downvote"){let I=((N=Ar.get(T))!=null?N:null)===D,be=D==="upvote"?"thumbs-up":"thumbs-down";if(I){Ar.delete(T),y.classList.remove("persona-message-action-active");let le=fe(be,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=D==="upvote"?"downvote":"upvote",ee=b.querySelector(`[data-action="${le}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Xe=fe(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(ee.innerHTML="",ee.appendChild(Xe))}Ar.set(T,D),y.classList.add("persona-message-action-active");let me=fe(be,14,"currentColor",2);me&&(me.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(me)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ne=_.getMessages().find(et=>et.id===T);Ne&&tt.onFeedback&&tt.onFeedback({type:D,messageId:Ne.id,message:Ne})}}}),ve.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=y.getAttribute("data-approval-action");if(!D)return;let N=D==="approve"?"approved":"denied",I=_.getMessages().find(le=>le.id===T);if(!(I!=null&&I.approval))return;let be=b.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),I.approval.toolType==="webmcp"?_.resolveWebMcpApproval(T,N):_.resolveApproval(I.approval,N)});let yt=null,Pn=null,In={artifacts:[],selectedId:null},fn=!1,kt={current:null};ve.addEventListener("click",c=>{var ee,me,Ce,Ne,et;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Ce=(me=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:me.onArtifactAction)==null?void 0:Ce.call(me,{type:"download",artifactId:b}))===!0)return;let D=_.getArtifactById(b),N=D==null?void 0:D.markdown,q=(D==null?void 0:D.title)||"artifact";if(!N){let Xe=y.closest("[data-open-artifact]"),st=Xe==null?void 0:Xe.closest("[data-message-id]"),at=st==null?void 0:st.getAttribute("data-message-id");if(at){let ke=_.getMessages().find(qe=>qe.id===at);if(ke!=null&&ke.rawContent)try{let qe=JSON.parse(ke.rawContent);N=(Ne=qe==null?void 0:qe.props)==null?void 0:Ne.markdown,q=((et=qe==null?void 0:qe.props)==null?void 0:et.title)||q}catch{}}}if(!N)return;let I=new Blob([N],{type:"text/markdown"}),be=URL.createObjectURL(I),le=document.createElement("a");le.href=be,le.download=`${q}.md`,le.click(),URL.revokeObjectURL(be)}),ve.addEventListener("click",c=>{var D,N,q;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((q=(N=(D=r.features)==null?void 0:D.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:q.call(N,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),fn=!1,_.selectArtifact(b),Hn())}),ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let jn=$e.composerOverlay,Un=(c,g,y)=>{var q,I,be,le;let b=g.trim();if(!b||!kt.current)return;let T=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",D=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:y.structured,values:(I=y.values)!=null?I:y.source==="multi"?b.split(", "):[b],isFreeText:D,source:y.source},bubbles:!0,composed:!0})),Mo(jn,T);let N=kt.current.getMessages().find(ee=>{var me;return((me=ee.toolCall)==null?void 0:me.id)===T});(be=N==null?void 0:N.agentMetadata)!=null&&be.awaitingLocalTool?kt.current.resolveAskUserQuestion(N,(le=y.structured)!=null?le:b):kt.current.sendMessage(b)},Wn=c=>{var T;let g=kt.current;if(!g)return;let y=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",b=g.getMessages().find(D=>{var N;return((N=D.toolCall)==null?void 0:N.id)===y});b&&g.persistAskUserQuestionProgress(b,{answers:Za(c,b),currentIndex:Xn(c)})},Nr=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Sr=c=>{var T,D,N;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let g=Xn(c),y=Yo(c);if(g>=y-1)return;let b=(N=kt.current)==null?void 0:N.getMessages().find(q=>{var I;return((I=q.toolCall)==null?void 0:I.id)===c.getAttribute("data-tool-call-id")});b&&(ei(c,b,r,g+1),Wn(c))};jn.addEventListener("click",c=>{var D,N,q,I,be,le,ee,me,Ce,Ne,et,Xe,st,at;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),T==="dismiss"){let Le=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Mo(jn,Le);let ke=(N=kt.current)==null?void 0:N.getMessages().find(qe=>{var E;return((E=qe.toolCall)==null?void 0:E.id)===Le});(q=ke==null?void 0:ke.agentMetadata)!=null&&q.awaitingLocalTool&&((I=kt.current)==null||I.markAskUserQuestionResolved(ke),(be=kt.current)==null||be.resolveAskUserQuestion(ke,"(dismissed)"));return}if(T==="pick"){let Le=y.getAttribute("data-option-label");if(!Le)return;let ke=b.getAttribute("data-multi-select")==="true",qe=ro(b);if(qe&&ke){let E=To(b)[Xn(b)],Se=new Set(Array.isArray(E)?E:[]);Se.has(Le)?Se.delete(Le):Se.add(Le),oo(b,Array.from(Se)),Wn(b);return}if(qe){oo(b,Le),Wn(b),Sr(b);return}if(ke){let E=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",E?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!E);let Se=b.querySelector('[data-ask-user-action="submit-multi"]');Se&&(Se.disabled=zi(b).length===0);return}Un(b,Le,{source:"pick",values:[Le]});return}if(T==="submit-multi"){let Le=zi(b);if(Le.length===0)return;Un(b,Le.join(", "),{source:"multi",values:Le});return}if(T==="open-free-text"){let Le=b.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let ke=Le.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(T==="focus-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(T==="submit-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]'),ke=(le=Le==null?void 0:Le.value)!=null?le:"";if(!ke.trim())return;if(ro(b)){oo(b,ke.trim()),Wn(b),Sr(b);return}Un(b,ke,{source:"free-text"});return}if(T==="next"||T==="back"){if(!kt.current)return;let Le=(ee=b.getAttribute("data-tool-call-id"))!=null?ee:"",ke=kt.current.getMessages().find(Je=>{var ye;return((ye=Je.toolCall)==null?void 0:ye.id)===Le});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Ce=(me=qe==null?void 0:qe.value)==null?void 0:me.trim())!=null?Ce:"";if(E){let Je=To(b)[Xn(b)];(typeof Je!="string"||Je!==E)&&oo(b,E)}let Se=T==="next"?1:-1,We=Xn(b)+Se;ei(b,ke,r,We),Wn(b);return}if(T==="submit-all"){if(!kt.current)return;let Le=(Ne=b.getAttribute("data-tool-call-id"))!=null?Ne:"",ke=kt.current.getMessages().find(Je=>{var ye;return((ye=Je.toolCall)==null?void 0:ye.id)===Le});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Xe=(et=qe==null?void 0:qe.value)==null?void 0:et.trim())!=null?Xe:"";E&&oo(b,E);let Se=Za(b,ke);kt.current.persistAskUserQuestionProgress(ke,{answers:Se,currentIndex:Xn(b)});let We=Nr(Se);Un(b,We||"(submitted)",{source:"submit-all",structured:Se});return}if(T==="skip"){if(!kt.current)return;let Le=(st=b.getAttribute("data-tool-call-id"))!=null?st:"",ke=kt.current.getMessages().find(ye=>{var Tt;return((Tt=ye.toolCall)==null?void 0:Tt.id)===Le});if(!ke)return;let qe=ro(b),E=Xn(b),Se=Yo(b),We=E>=Se-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Mo(jn,Le),(at=ke.agentMetadata)!=null&&at.awaitingLocalTool&&(kt.current.markAskUserQuestionResolved(ke),kt.current.resolveAskUserQuestion(ke,"(dismissed)"));return}oo(b,"");let Je=b.querySelector('[data-ask-free-text-input="true"]');if(Je&&(Je.value=""),We){let ye=Za(b,ke),Tt=Nr(ye);Un(b,Tt||"(skipped)",{source:"submit-all",structured:ye});return}ei(b,ke,r,E+1),Wn(b);return}}),jn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let y=c.target;if(!((D=y.matches)!=null&&D.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let T=y.value;if(T.trim()){if(ro(b)){oo(b,T.trim()),Wn(b),Sr(b);return}Un(b,T,{source:"free-text"})}});let Or=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let y=jn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",Or);let Rn=null,Wt=null,hn=null,qn=null,Fr=()=>{};function Er(){qn==null||qn(),qn=null}let $r=()=>{var N;if(!Rn||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=Rn.firstElementChild;if(!b||b===Wt)return;let T=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${T}px`,Wt.style.zIndex="5";let D=b.offsetWidth-T/2;Wt.style.left=`${Math.max(0,D)}px`},gr=()=>{},Hn=()=>{var y,b,T,D,N;if(!yt||!Yn(r))return;ti(e,r),ni(e,r),gr();let c=(D=(T=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,g=z.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),yt.update(In),fn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(N=yt.backdrop)==null||N.classList.add("persona-hidden")):In.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),Fr()};if(Yn(r)){z.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ne),yt=Su(r,{onSelect:y=>{var b;return(b=kt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{fn=!0,Hn()}}),yt.element.classList.add("persona-hidden"),Rn=g,g.appendChild(c),g.appendChild(yt.element),yt.backdrop&&z.appendChild(yt.backdrop),z.appendChild(g),Fr=()=>{var b,T,D,N;if(!Rn||!yt)return;if(!(((D=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){hn==null||hn(),hn=null,Er(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let I=e.ownerDocument,be=(N=I.defaultView)!=null?N:window,le=ee=>{var st,at;if(!yt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||be.innerWidth<=640)return;ee.preventDefault(),Er();let me=ee.clientX,Ce=yt.element.getBoundingClientRect().width,Ne=(at=(st=r.features)==null?void 0:st.artifacts)==null?void 0:at.layout,et=Le=>{let ke=Rn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),E=qe?0:ku(Rn,be),Se=qe?0:q.getBoundingClientRect().width||6,We=Ce-(Le.clientX-me),Je=Lu(We,ke,E,Se,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);yt.element.style.width=`${Je}px`,yt.element.style.maxWidth="none",$r()},Xe=()=>{I.removeEventListener("pointermove",et),I.removeEventListener("pointerup",Xe),I.removeEventListener("pointercancel",Xe),qn=null;try{q.releasePointerCapture(ee.pointerId)}catch{}};qn=Xe,I.addEventListener("pointermove",et),I.addEventListener("pointerup",Xe),I.addEventListener("pointercancel",Xe);try{q.setPointerCapture(ee.pointerId)}catch{}};q.addEventListener("pointerdown",le),Wt=q,Rn.insertBefore(q,yt.element),hn=()=>{q.removeEventListener("pointerdown",le)}}if(Wt){let q=In.artifacts.length>0&&!fn;Wt.classList.toggle("persona-hidden",!q),$r()}},gr=()=>{var be,le,ee,me,Ce,Ne,et,Xe,st,at,Le,ke,qe,E;if(!A||!yt||((le=(be=r.launcher)==null?void 0:be.sidebarMode)!=null?le:!1)||on(r)&&lr(r).reveal==="emerge")return;let b=(ee=e.ownerDocument.defaultView)!=null?ee:window,T=(Ce=(me=r.launcher)==null?void 0:me.mobileFullscreen)!=null?Ce:!0,D=(et=(Ne=r.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?et:640;if(T&&b.innerWidth<=D||!Mu(r,A))return;let N=(at=(st=(Xe=r.launcher)==null?void 0:Xe.width)!=null?st:r.launcherWidth)!=null?at:Gn,q=(E=(qe=(ke=(Le=r.features)==null?void 0:Le.artifacts)==null?void 0:ke.layout)==null?void 0:qe.expandedPanelWidth)!=null?E:"min(720px, calc(100vw - 24px))";In.artifacts.length>0&&!fn?(z.style.width=q,z.style.maxWidth=q):(z.style.width=N,z.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(Pn=new ResizeObserver(()=>{Hn()}),Pn.observe(z))}else z.appendChild(ne),F()&&we&&($e.peekBanner&&we.appendChild($e.peekBanner),we.appendChild(_e));e.appendChild(J),we&&e.appendChild(we);let Zn=()=>{var Je,ye,Tt,ot,Xt,ln,Pt,xn,cn,Qe,it,vn,pn,fo,ho,yo,Do,No,Ut,bo,Xr,ht,Tn,Ir,wn,Mn,Bt,$t;if(F()){z.style.width="100%",z.style.maxWidth="100%";let Dt=(ye=(Je=r.launcher)==null?void 0:Je.composerBar)!=null?ye:{},qt=J.dataset.state==="expanded",kn=(Tt=Dt.expandedSize)!=null?Tt:"anchored";if(!(qt&&kn!=="fullscreen")){ne.style.background="",ne.style.border="",ne.style.borderRadius="",ne.style.overflow="",ne.style.boxShadow="";return}let Zt=(Xt=(ot=r.theme)==null?void 0:ot.components)==null?void 0:Xt.panel,yr=Is(r),Wr=(xo,ga)=>{var xs;return xo==null||xo===""?ga:(xs=zo(yr,xo))!=null?xs:xo},pa="1px solid var(--persona-border)",ua="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ma="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ne.style.background="var(--persona-surface, #ffffff)",ne.style.border=Wr(Zt==null?void 0:Zt.border,pa),ne.style.borderRadius=Wr(Zt==null?void 0:Zt.borderRadius,ma),ne.style.boxShadow=Wr(Zt==null?void 0:Zt.shadow,ua),ne.style.overflow="hidden";return}let c=on(r),g=(Pt=(ln=r.launcher)==null?void 0:ln.sidebarMode)!=null?Pt:!1,y=c||g||((cn=(xn=r.launcher)==null?void 0:xn.fullHeight)!=null?cn:!1),b=((Qe=r.launcher)==null?void 0:Qe.enabled)===!1,T=(vn=(it=r.theme)==null?void 0:it.components)==null?void 0:vn.panel,D=Is(r),N=(Dt,qt)=>{var kn;return Dt==null||Dt===""?qt:(kn=zo(D,Dt))!=null?kn:Dt},q=(pn=e.ownerDocument.defaultView)!=null?pn:window,I=(ho=(fo=r.launcher)==null?void 0:fo.mobileFullscreen)!=null?ho:!0,be=(Do=(yo=r.launcher)==null?void 0:yo.mobileBreakpoint)!=null?Do:640,le=q.innerWidth<=be,ee=I&&le&&A,me=(Ut=(No=r.launcher)==null?void 0:No.position)!=null?Ut:"bottom-left",Ce=me==="bottom-left"||me==="top-left",Ne=(Xr=(bo=r.launcher)==null?void 0:bo.zIndex)!=null?Xr:gn,et=g||ee?"none":"1px solid var(--persona-border)",Xe=ee?"none":g?Ce?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Xe="none",et="none");let st=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=N(T==null?void 0:T.border,et),Le=N(T==null?void 0:T.shadow,Xe),ke=N(T==null?void 0:T.borderRadius,st),qe=Te.scrollTop;e.style.cssText="",J.style.cssText="",z.style.cssText="",ne.style.cssText="",Te.style.cssText="",_e.style.cssText="";let E=()=>{var qt;if(qe<=0)return;((qt=Te.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Te.scrollTop===qe)return;let kn=Te.scrollHeight-Te.clientHeight;kn<=0||(Te.scrollTop=Math.min(qe,kn))})};if(ee){J.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"),J.style.cssText=`
30
+ `,W.addEventListener("click",()=>{p=w,A.forEach((F,_)=>{let B=_<w;F.classList.toggle("selected",B),F.setAttribute("aria-checked",_===w-1?"true":"false")})}),A.push(W),E.appendChild(W)}f.appendChild(E);let I=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),w.appendChild(I),f.appendChild(w)}let P=document.createElement("div");P.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=i,N.addEventListener("click",()=>{n==null||n(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=(I==null?void 0:I.value.trim())||void 0;await t(p,w),u.remove()}catch(w){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),P.appendChild(N),P.appendChild(L),f.appendChild(P),u.appendChild(f),u}function cl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,v.appendChild(E),m.appendChild(v);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let N=document.createElement("span");N.className="persona-feedback-label-high",N.textContent=u,I.appendChild(P),I.appendChild(N);let L=document.createElement("div");L.className="persona-feedback-numbers";let w=[];for(let j=0;j<=10;j++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${j} out of 10`),q.textContent=String(j),q.dataset.rating=String(j),j<=6?q.classList.add("persona-feedback-detractor"):j<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{f=j,w.forEach((re,Ie)=>{re.classList.toggle("selected",Ie===j),re.setAttribute("aria-checked",Ie===j?"true":"false")})}),w.push(q),L.appendChild(q)}A.appendChild(I),A.appendChild(L),m.appendChild(A);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=o,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),m.appendChild(j)}let F=document.createElement("div");F.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{n==null||n(),p.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await t(f,j),p.remove()}catch(j){B.disabled=!1,B.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),F.appendChild(_),F.appendChild(B),m.appendChild(F),p.appendChild(m),p}var rs="persona-chat-history",xb=30*1e3,vb={"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 wb(e){var r,s,o;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(s=vb[i.type])!=null?s:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&t.push(a);return t}function di(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Cb(e){var t,n,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Ab(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var dl=e=>!e||typeof e!="object"?{}:{...e},Uu=e=>e.map(t=>({...t,streaming:!1})),qu=(e,t,n)=>{let r=e!=null&&e.markdown?$o(e.markdown):null,s=Es(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(t){let f=t.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&n&&n())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=jo(a),s?s(d):d}};function zu(e){var i,d,l,u;let t=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=be(n,r,s,o);if(a&&t.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,t.appendChild(p)}return t}var pl=(e,t,n)=>{var Ll,Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Ol,Fl,_l,$l,jl,Ul,ql,zl,Vl,Kl,Jl,Gl,Xl,Ql,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,wc,Cc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Li(t),s=ii.getForInstance(r.plugins);r.components&&io.registerAll(r.components);let o=_u(),i=r.persistState===!1?null:(Ll=r.storageAdapter)!=null?Ll:rl(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let g=r.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:b}=g;return b&&(u=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=c!=null?c:{messages:[],metadata:{}},y=p(g);y.metadata&&(d=dl(y.metadata)),(Pl=y.messages)!=null&&Pl.length&&(r={...r,initialMessages:y.messages}),(Il=y.artifacts)!=null&&Il.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Wl=y.selectedArtifactId)!=null?Wl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=p({messages:[],metadata:{}});(Rl=c.messages)!=null&&Rl.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var y;d=(y=c({...d}))!=null?y:{},Wo()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[li],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],E=ci({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let A=(Bl=(Hl=r.launcher)==null?void 0:Hl.enabled)!=null?Bl:!0,I=(Nl=(Dl=r.launcher)==null?void 0:Dl.autoExpand)!=null?Nl:!1,P=(Ol=r.autoFocusInput)!=null?Ol:!1,N=I,L=A,w=(_l=(Fl=r.layout)==null?void 0:Fl.header)==null?void 0:_l.layout,W=!1,F=()=>to(r),_=()=>A||F(),B=F()?!1:A?I:!0,j=!1,q=null,re=()=>{j=!0,q&&clearTimeout(q),q=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},Ie=qu(r,E,re),Re=(jl=($l=r.features)==null?void 0:$l.showReasoning)!=null?jl:!0,Ne=(ql=(Ul=r.features)==null?void 0:Ul.showToolCalls)!=null?ql:!0,ce=(Vl=(zl=r.features)==null?void 0:zl.showEventStreamToggle)!=null?Vl:!1,ve=(Jl=(Kl=r.features)==null?void 0:Kl.scrollToBottom)!=null?Jl:{},Le=`${(Xl=typeof r.persistState=="object"?(Gl=r.persistState)==null?void 0:Gl.keyPrefix:void 0)!=null?Xl:"persona-"}event-stream`,ne=ce?new Xs(Le):null,ke=(Zl=(Yl=(Ql=r.features)==null?void 0:Ql.eventStream)==null?void 0:Yl.maxEvents)!=null?Zl:2e3,V=ce?new Gs(ke,ne):null,pe=ce?new Qs:null,fe=null,me=!1,ue=null,Ge=0;ne==null||ne.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let z={onCopy:c=>{var g,y;o.emit("message:copy",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onCopy)==null||y.call(g,c)},onFeedback:c=>{var g,y;o.emit("message:feedback",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},te=(ec=r.statusIndicator)!=null?ec:{},We=c=>{var g,y,b,k;return c==="idle"?(g=te.idleText)!=null?g:fn.idle:c==="connecting"?(y=te.connectingText)!=null?y:fn.connecting:c==="connected"?(b=te.connectedText)!=null?b:fn.connected:c==="error"?(k=te.errorText)!=null?k:fn.error:fn[c]};function ge(c,g,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=g,k.style.color="inherit",k.style.textDecoration="none",c.appendChild(k)}else c.textContent=g}let{wrapper:ie,panel:ae,pillRoot:Qe}=su(r),Ce=au(r,_()),{container:de,body:X,messagesWrapper:$e,suggestions:Ct,textarea:G,sendButton:Oe,sendButtonWrapper:Mn,composerForm:Dt,statusText:ln,introTitle:Hn,introSubtitle:Xn,closeButton:H,iconHolder:oe,headerTitle:Be,headerSubtitle:Xe,header:Fe,footer:_e,actionsRow:rt,leftActions:At,rightActions:Ft}=Ce,Kt=Ce.setSendButtonMode,K=Ce.micButton,gt=Ce.micButtonWrapper,nt=Ce.attachmentButton,Ut=Ce.attachmentButtonWrapper,se=Ce.attachmentInput,ye=Ce.attachmentPreviewsContainer;de.classList.add("persona-relative"),X.classList.add("persona-relative");let wt=12,_t=()=>{var c;return(c=ve.label)!=null?c:""},Zt=()=>{var c;return(c=ve.iconName)!=null?c:"arrow-down"},yn=()=>ve.enabled!==!1,Tt=h("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");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let St=h("span","persona-flex persona-items-center"),ht=h("span","");Tt.append(St,ht),de.appendChild(Tt);let bt=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;Tt.style.bottom=`${g+wt}px`};bt();let qt=()=>{let c=!!_t();Tt.setAttribute("aria-label",_t()||"Jump to latest"),Tt.title=_t(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),St.innerHTML="";let g=be(Zt(),"14px","currentColor",2);g?(St.appendChild(g),St.style.display=""):St.style.display="none",ht.textContent=_t(),ht.style.display=c?"":"none"};qt();let et=null,Bn=null,Qn=s.find(c=>c.renderHeader);if(Qn!=null&&Qn.renderHeader){let c=Qn.renderHeader({config:r,defaultRenderer:()=>{let g=no({config:r,showClose:_()});return Go(de,g,r),g.header},onClose:()=>Rt(!1,"user")});if(c){let g=de.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),Fe=c)}}let bn=()=>{var g,y,b,k;if(!V)return;if(me=!0,!fe&&V&&(fe=Pu({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>Dn(),config:r,plugins:s,getThroughput:()=>{var D;return(D=pe==null?void 0:pe.getMetric())!=null?D:{status:"idle"}}})),fe&&(X.style.display="none",(g=_e.parentNode)==null||g.insertBefore(fe.element,_e),fe.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Tn.actionIconColor}`;let D=(k=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:k.toggleButtonActive;D&&D.split(/\s+/).forEach(O=>O&&ut.classList.add(O))}let c=()=>{if(!me)return;let D=Date.now();D-Ge>=200&&(fe==null||fe.update(),Ge=D),ue=requestAnimationFrame(c)};Ge=0,ue=requestAnimationFrame(c),Wr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Dn=()=>{var c,g,y;if(me){if(me=!1,fe&&fe.element.remove(),X.style.display="",ut){ut.style.boxShadow="";let b=(y=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(k=>k&&ut.classList.remove(k))}ue!==null&&(cancelAnimationFrame(ue),ue=null),Wr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ce){let c=(nc=(tc=r.features)==null?void 0:tc.eventStream)==null?void 0:nc.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=h("button",g),ut.style.width="28px",ut.style.height="28px",ut.style.color=Tn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&ut.appendChild(y);let b=Ce.clearChatButtonWrapper,k=Ce.closeButtonWrapper,D=b||k;D&&D.parentNode===Fe?Fe.insertBefore(ut,D):Fe.appendChild(ut),ut.addEventListener("click",()=>{me?Dn():bn()})}let xr=c=>{var b,k,D;let g=r.attachments;if(!(g!=null&&g.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(y,O):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((b=g.allowedTypes)!=null?b:Nr).join(","),O.multiple=((k=g.maxFiles)!=null?k:4)>1,O.style.display="none",O.setAttribute("aria-label",(D=g.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(O)}},Nn=s.find(c=>c.renderComposer);if(Nn!=null&&Nn.renderComposer){let c=r.composer,g=Nn.renderComposer({config:r,defaultRenderer:()=>zs({config:r}).footer,onSubmit:y=>{var O;if(!S||S.isStreaming())return;let b=y.trim(),k=(O=et==null?void 0:et.hasAttachments())!=null?O:!1;if(!b&&!k)return;gs();let D;k&&(D=[],D.push(...et.getContentParts()),b&&D.push(La(b))),S.sendMessage(b,{contentParts:D}),k&&et.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{se==null||se.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((rc=r.voiceRecognition)==null?void 0:rc.enabled)===!0?()=>{Bn==null||Bn()}:void 0});g&&(_e.replaceWith(g),_e=g)}let co=c=>{let g=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),k=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");g&&(Dt=g),y&&(G=y),b&&(Oe=b),k&&(K=k,gt=k.parentElement),D&&(ln=D);let O=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Ct=O);let U=c.querySelector(".persona-attachment-button");U&&(nt=U,Ut=U.parentElement),se=c.querySelector('input[type="file"]'),ye=c.querySelector(".persona-attachment-previews");let R=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");R&&(rt=R)};xr(_e),co(_e);let kn=(lc=(oc=r.layout)==null?void 0:oc.contentMaxWidth)!=null?lc:F()?(ic=(ac=(sc=r.launcher)==null?void 0:sc.composerBar)==null?void 0:ac.contentMaxWidth)!=null?ic:"720px":void 0;if(kn&&($e.style.maxWidth=kn,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%"),kn&&Dt&&!F()&&(Dt.style.maxWidth=kn,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),kn&&Ct&&!F()&&(Ct.style.maxWidth=kn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),kn&&ye&&!F()&&(ye.style.maxWidth=kn,ye.style.marginLeft="auto",ye.style.marginRight="auto"),(cc=r.attachments)!=null&&cc.enabled&&se&&ye){et=Ko.fromConfig(r.attachments),et.setPreviewsContainer(ye),se.addEventListener("change",y=>{let b=y.target;et==null||et.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,g=zu(c);de.appendChild(g)}(()=>{var b,k;let c=(k=(b=r.layout)==null?void 0:b.slots)!=null?k:{},g=D=>{switch(D){case"body-top":return de.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return $e;case"footer-top":return Ct;case"composer":return Dt;case"footer-bottom":return ln;default:return null}},y=(D,O)=>{var U;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Fe.insertBefore(O,Fe.firstChild);else if(D==="header-right")Fe.appendChild(O);else{let R=Fe.querySelector(".persona-flex-col");R?(U=R.parentNode)==null||U.insertBefore(O,R.nextSibling):Fe.appendChild(O)}break;case"body-top":{let R=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(O):X.insertBefore(O,X.firstChild);break}case"body-bottom":X.appendChild(O);break;case"footer-top":Ct.replaceWith(O);break;case"footer-bottom":ln.replaceWith(O);break;default:break}};for(let[D,O]of Object.entries(c))if(O)try{let U=O({config:r,defaultContent:()=>g(D)});U&&y(D,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,U)}})();let Fr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let D=y.getAttribute("data-bubble-type");D==="reasoning"?(Qo.has(k)?Qo.delete(k):Qo.add(k),pu(k,b)):D==="tool"&&(Yo.has(k)?Yo.delete(k):Yo.add(k),uu(k,b,r)),dr.delete(k)};$e.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Fr(c))}),$e.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Fr(c))});let Tr=new Map;$e.addEventListener("click",c=>{var O;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let k=b.getAttribute("data-actions-for");if(!k)return;let D=y.getAttribute("data-action");if(D==="copy"){let R=S.getMessages().find(we=>we.id===k);if(R&&z.onCopy){let we=R.content||"";navigator.clipboard.writeText(we).then(()=>{y.classList.add("persona-message-action-success");let le=be("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ee=be("copy",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),z.onCopy(R)}}else if(D==="upvote"||D==="downvote"){let R=((O=Tr.get(k))!=null?O:null)===D,we=D==="upvote"?"thumbs-up":"thumbs-down";if(R){Tr.delete(k),y.classList.remove("persona-message-action-active");let le=be(we,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=D==="upvote"?"downvote":"upvote",ee=b.querySelector(`[data-action="${le}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Je=be(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Je&&(ee.innerHTML="",ee.appendChild(Je))}Tr.set(k,D),y.classList.add("persona-message-action-active");let he=be(we,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(he)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let He=S.getMessages().find(tt=>tt.id===k);He&&z.onFeedback&&z.onFeedback({type:D,messageId:He.id,message:He})}}}),$e.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let k=b.getAttribute("data-message-id");if(!k)return;let D=y.getAttribute("data-approval-action");if(!D)return;let O=D==="approve"?"approved":"denied",R=S.getMessages().find(le=>le.id===k);if(!(R!=null&&R.approval))return;let we=b.querySelector("[data-approval-buttons]");we&&we.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),R.approval.toolType==="webmcp"?S.resolveWebMcpApproval(k,O):S.resolveApproval(R.approval,O)});let xt=null,On=null,Fn={artifacts:[],selectedId:null},xn=!1,Pt={current:null};$e.addEventListener("click",c=>{var ee,he,Ae,He,tt;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Ae=(he=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ae.call(he,{type:"download",artifactId:b}))===!0)return;let D=S.getArtifactById(b),O=D==null?void 0:D.markdown,U=(D==null?void 0:D.title)||"artifact";if(!O){let Je=y.closest("[data-open-artifact]"),it=Je==null?void 0:Je.closest("[data-message-id]"),lt=it==null?void 0:it.getAttribute("data-message-id");if(lt){let Ee=S.getMessages().find(je=>je.id===lt);if(Ee!=null&&Ee.rawContent)try{let je=JSON.parse(Ee.rawContent);O=(He=je==null?void 0:je.props)==null?void 0:He.markdown,U=((tt=je==null?void 0:je.props)==null?void 0:tt.title)||U}catch{}}}if(!O)return;let R=new Blob([O],{type:"text/markdown"}),we=URL.createObjectURL(R),le=document.createElement("a");le.href=we,le.download=`${U}.md`,le.click(),URL.revokeObjectURL(we)}),$e.addEventListener("click",c=>{var D,O,U;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((U=(O=(D=r.features)==null?void 0:D.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:U.call(O,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,S.selectArtifact(b),jn())}),$e.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let Yn=Ce.composerOverlay,Zn=(c,g,y)=>{var U,R,we,le;let b=g.trim();if(!b||!Pt.current)return;let k=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",D=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:b,answers:y.structured,values:(R=y.values)!=null?R:y.source==="multi"?b.split(", "):[b],isFreeText:D,source:y.source},bubbles:!0,composed:!0})),ko(Yn,k);let O=Pt.current.getMessages().find(ee=>{var he;return((he=ee.toolCall)==null?void 0:he.id)===k});(we=O==null?void 0:O.agentMetadata)!=null&&we.awaitingLocalTool?Pt.current.resolveAskUserQuestion(O,(le=y.structured)!=null?le:b):Pt.current.sendMessage(b)},_n=c=>{var k;let g=Pt.current;if(!g)return;let y=(k=c.getAttribute("data-tool-call-id"))!=null?k:"",b=g.getMessages().find(D=>{var O;return((O=D.toolCall)==null?void 0:O.id)===y});b&&g.persistAskUserQuestionProgress(b,{answers:ni(c,b),currentIndex:ar(c)})},_r=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Mr=c=>{var k,D,O;if(((D=(k=r.features)==null?void 0:k.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let g=ar(c),y=es(c);if(g>=y-1)return;let b=(O=Pt.current)==null?void 0:O.getMessages().find(U=>{var R;return((R=U.toolCall)==null?void 0:R.id)===c.getAttribute("data-tool-call-id")});b&&(ri(c,b,r,g+1),_n(c))};Yn.addEventListener("click",c=>{var D,O,U,R,we,le,ee,he,Ae,He,tt,Je,it,lt;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let k=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),k==="dismiss"){let Te=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Te},bubbles:!0,composed:!0})),ko(Yn,Te);let Ee=(O=Pt.current)==null?void 0:O.getMessages().find(je=>{var T;return((T=je.toolCall)==null?void 0:T.id)===Te});(U=Ee==null?void 0:Ee.agentMetadata)!=null&&U.awaitingLocalTool&&((R=Pt.current)==null||R.markAskUserQuestionResolved(Ee),(we=Pt.current)==null||we.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(k==="pick"){let Te=y.getAttribute("data-option-label");if(!Te)return;let Ee=b.getAttribute("data-multi-select")==="true",je=so(b);if(je&&Ee){let T=Mo(b)[ar(b)],Se=new Set(Array.isArray(T)?T:[]);Se.has(Te)?Se.delete(Te):Se.add(Te),ao(b,Array.from(Se)),_n(b);return}if(je){ao(b,Te),_n(b),Mr(b);return}if(Ee){let T=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",T?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!T);let Se=b.querySelector('[data-ask-user-action="submit-multi"]');Se&&(Se.disabled=Gi(b).length===0);return}Zn(b,Te,{source:"pick",values:[Te]});return}if(k==="submit-multi"){let Te=Gi(b);if(Te.length===0)return;Zn(b,Te.join(", "),{source:"multi",values:Te});return}if(k==="open-free-text"){let Te=b.querySelector('[data-ask-free-text-row="true"]');if(Te){Te.classList.remove("persona-hidden");let Ee=Te.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(k==="focus-free-text"){let Te=b.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus();return}if(k==="submit-free-text"){let Te=b.querySelector('[data-ask-free-text-input="true"]'),Ee=(le=Te==null?void 0:Te.value)!=null?le:"";if(!Ee.trim())return;if(so(b)){ao(b,Ee.trim()),_n(b),Mr(b);return}Zn(b,Ee,{source:"free-text"});return}if(k==="next"||k==="back"){if(!Pt.current)return;let Te=(ee=b.getAttribute("data-tool-call-id"))!=null?ee:"",Ee=Pt.current.getMessages().find(ze=>{var xe;return((xe=ze.toolCall)==null?void 0:xe.id)===Te});if(!Ee)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),T=(Ae=(he=je==null?void 0:je.value)==null?void 0:he.trim())!=null?Ae:"";if(T){let ze=Mo(b)[ar(b)];(typeof ze!="string"||ze!==T)&&ao(b,T)}let Se=k==="next"?1:-1,Pe=ar(b)+Se;ri(b,Ee,r,Pe),_n(b);return}if(k==="submit-all"){if(!Pt.current)return;let Te=(He=b.getAttribute("data-tool-call-id"))!=null?He:"",Ee=Pt.current.getMessages().find(ze=>{var xe;return((xe=ze.toolCall)==null?void 0:xe.id)===Te});if(!Ee)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),T=(Je=(tt=je==null?void 0:je.value)==null?void 0:tt.trim())!=null?Je:"";T&&ao(b,T);let Se=ni(b,Ee);Pt.current.persistAskUserQuestionProgress(Ee,{answers:Se,currentIndex:ar(b)});let Pe=_r(Se);Zn(b,Pe||"(submitted)",{source:"submit-all",structured:Se});return}if(k==="skip"){if(!Pt.current)return;let Te=(it=b.getAttribute("data-tool-call-id"))!=null?it:"",Ee=Pt.current.getMessages().find(xe=>{var Lt;return((Lt=xe.toolCall)==null?void 0:Lt.id)===Te});if(!Ee)return;let je=so(b),T=ar(b),Se=es(b),Pe=T>=Se-1;if(!je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Te},bubbles:!0,composed:!0})),ko(Yn,Te),(lt=Ee.agentMetadata)!=null&&lt.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(Ee),Pt.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}ao(b,"");let ze=b.querySelector('[data-ask-free-text-input="true"]');if(ze&&(ze.value=""),Pe){let xe=ni(b,Ee),Lt=_r(xe);Zn(b,Lt||"(skipped)",{source:"submit-all",structured:xe});return}ri(b,Ee,r,T+1),_n(b);return}}),Yn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let y=c.target;if(!((D=y.matches)!=null&&D.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let k=y.value;if(k.trim()){if(so(b)){ao(b,k.trim()),_n(b),Mr(b);return}Zn(b,k,{source:"free-text"})}});let $r=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let y=Yn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",$r);let $n=null,Wt=null,vn=null,er=null,jr=()=>{};function kr(){er==null||er(),er=null}let Ur=()=>{var O;if(!$n||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=$n.firstElementChild;if(!b||b===Wt)return;let k=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${k}px`,Wt.style.zIndex="5";let D=b.offsetWidth-k/2;Wt.style.left=`${Math.max(0,D)}px`},vr=()=>{},jn=()=>{var y,b,k,D,O;if(!xt||!ir(r))return;si(e,r),ai(e,r),vr();let c=(D=(k=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:k.narrowHostMaxWidth)!=null?D:520,g=ae.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),xt.update(Fn),xn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(O=xt.backdrop)==null||O.classList.add("persona-hidden")):Fn.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),jr()};if(ir(r)){ae.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(de),xt=Ru(r,{onSelect:y=>{var b;return(b=Pt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{xn=!0,jn()}}),xt.element.classList.add("persona-hidden"),$n=g,g.appendChild(c),g.appendChild(xt.element),xt.backdrop&&ae.appendChild(xt.backdrop),ae.appendChild(g),jr=()=>{var b,k,D,O;if(!$n||!xt)return;if(!(((D=(k=(b=r.features)==null?void 0:b.artifacts)==null?void 0:k.layout)==null?void 0:D.resizable)===!0)){vn==null||vn(),vn=null,kr(),Wt&&(Wt.remove(),Wt=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!Wt){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let R=e.ownerDocument,we=(O=R.defaultView)!=null?O:window,le=ee=>{var it,lt;if(!xt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||we.innerWidth<=640)return;ee.preventDefault(),kr();let he=ee.clientX,Ae=xt.element.getBoundingClientRect().width,He=(lt=(it=r.features)==null?void 0:it.artifacts)==null?void 0:lt.layout,tt=Te=>{let Ee=$n.getBoundingClientRect().width,je=e.classList.contains("persona-artifact-appearance-seamless"),T=je?0:Nu($n,we),Se=je?0:U.getBoundingClientRect().width||6,Pe=Ae-(Te.clientX-he),ze=Ou(Pe,Ee,T,Se,He==null?void 0:He.resizableMinWidth,He==null?void 0:He.resizableMaxWidth);xt.element.style.width=`${ze}px`,xt.element.style.maxWidth="none",Ur()},Je=()=>{R.removeEventListener("pointermove",tt),R.removeEventListener("pointerup",Je),R.removeEventListener("pointercancel",Je),er=null;try{U.releasePointerCapture(ee.pointerId)}catch{}};er=Je,R.addEventListener("pointermove",tt),R.addEventListener("pointerup",Je),R.addEventListener("pointercancel",Je);try{U.setPointerCapture(ee.pointerId)}catch{}};U.addEventListener("pointerdown",le),Wt=U,$n.insertBefore(U,xt.element),vn=()=>{U.removeEventListener("pointerdown",le)}}if(Wt){let U=Fn.artifacts.length>0&&!xn;Wt.classList.toggle("persona-hidden",!U),Ur()}},vr=()=>{var we,le,ee,he,Ae,He,tt,Je,it,lt,Te,Ee,je,T;if(!A||!xt||((le=(we=r.launcher)==null?void 0:we.sidebarMode)!=null?le:!1)||an(r)&&yr(r).reveal==="emerge")return;let b=(ee=e.ownerDocument.defaultView)!=null?ee:window,k=(Ae=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?Ae:!0,D=(tt=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?tt:640;if(k&&b.innerWidth<=D||!Du(r,A))return;let O=(lt=(it=(Je=r.launcher)==null?void 0:Je.width)!=null?it:r.launcherWidth)!=null?lt:sr,U=(T=(je=(Ee=(Te=r.features)==null?void 0:Te.artifacts)==null?void 0:Ee.layout)==null?void 0:je.expandedPanelWidth)!=null?T:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!xn?(ae.style.width=U,ae.style.maxWidth=U):(ae.style.width=O,ae.style.maxWidth=O)},typeof ResizeObserver!="undefined"&&(On=new ResizeObserver(()=>{jn()}),On.observe(ae))}else ae.appendChild(de),F()&&Qe&&(Ce.peekBanner&&Qe.appendChild(Ce.peekBanner),Qe.appendChild(_e));e.appendChild(ie),Qe&&e.appendChild(Qe);let lr=()=>{var ze,xe,Lt,st,Qt,dn,It,Cn,pn,Ze,ct,An,mn,ho,yo,bo,Fo,_o,zt,xo,Yr,yt,Pn,Br,Sn,In,Ht,$t;if(F()){ae.style.width="100%",ae.style.maxWidth="100%";let Bt=(xe=(ze=r.launcher)==null?void 0:ze.composerBar)!=null?xe:{},Vt=ie.dataset.state==="expanded",Wn=(Lt=Bt.expandedSize)!=null?Lt:"anchored";if(!(Vt&&Wn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let nn=(Qt=(st=r.theme)==null?void 0:st.components)==null?void 0:Qt.panel,Ar=Hs(r),Dr=(vo,ya)=>{var Cs;return vo==null||vo===""?ya:(Cs=Jo(Ar,vo))!=null?Cs:vo},ga="1px solid var(--persona-border)",fa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ha="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=Dr(nn==null?void 0:nn.border,ga),de.style.borderRadius=Dr(nn==null?void 0:nn.borderRadius,ha),de.style.boxShadow=Dr(nn==null?void 0:nn.shadow,fa),de.style.overflow="hidden";return}let c=an(r),g=(It=(dn=r.launcher)==null?void 0:dn.sidebarMode)!=null?It:!1,y=c||g||((pn=(Cn=r.launcher)==null?void 0:Cn.fullHeight)!=null?pn:!1),b=((Ze=r.launcher)==null?void 0:Ze.enabled)===!1,k=(An=(ct=r.theme)==null?void 0:ct.components)==null?void 0:An.panel,D=Hs(r),O=(Bt,Vt)=>{var Wn;return Bt==null||Bt===""?Vt:(Wn=Jo(D,Bt))!=null?Wn:Bt},U=(mn=e.ownerDocument.defaultView)!=null?mn:window,R=(yo=(ho=r.launcher)==null?void 0:ho.mobileFullscreen)!=null?yo:!0,we=(Fo=(bo=r.launcher)==null?void 0:bo.mobileBreakpoint)!=null?Fo:640,le=U.innerWidth<=we,ee=R&&le&&A,he=(zt=(_o=r.launcher)==null?void 0:_o.position)!=null?zt:"bottom-left",Ae=he==="bottom-left"||he==="top-left",He=(Yr=(xo=r.launcher)==null?void 0:xo.zIndex)!=null?Yr:hn,tt=g||ee?"none":"1px solid var(--persona-border)",Je=ee?"none":g?Ae?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";c&&!ee&&(Je="none",tt="none");let it=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",lt=O(k==null?void 0:k.border,tt),Te=O(k==null?void 0:k.shadow,Je),Ee=O(k==null?void 0:k.borderRadius,it),je=X.scrollTop;e.style.cssText="",ie.style.cssText="",ae.style.cssText="",de.style.cssText="",X.style.cssText="",_e.style.cssText="";let T=()=>{var Vt;if(je<=0)return;((Vt=X.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(X.scrollTop===je)return;let Wn=X.scrollHeight-X.clientHeight;Wn<=0||(X.scrollTop=Math.min(je,Wn))})};if(ee){ie.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"),ie.style.cssText=`
31
31
  position: fixed !important;
32
32
  inset: 0 !important;
33
33
  width: 100% !important;
@@ -37,9 +37,9 @@ _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;this
37
37
  padding: 0 !important;
38
38
  display: flex !important;
39
39
  flex-direction: column !important;
40
- z-index: ${Ne} !important;
40
+ z-index: ${He} !important;
41
41
  background-color: var(--persona-surface, #ffffff) !important;
42
- `,z.style.cssText=`
42
+ `,ae.style.cssText=`
43
43
  position: relative !important;
44
44
  display: flex !important;
45
45
  flex-direction: column !important;
@@ -52,7 +52,7 @@ _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;this
52
52
  padding: 0 !important;
53
53
  box-shadow: none !important;
54
54
  border-radius: 0 !important;
55
- `,ne.style.cssText=`
55
+ `,de.style.cssText=`
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
58
  flex: 1 1 0% !important;
@@ -63,20 +63,20 @@ _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;this
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
66
- `,Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.overflowY="auto",_e.style.flexShrink="0",B=!0,E();return}let Se=(Tn=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?Tn:r==null?void 0:r.launcherWidth,We=Se!=null?Se:Gn;if(!g&&!c)b&&y?(z.style.width="100%",z.style.maxWidth="100%"):(z.style.width=We,z.style.maxWidth=We);else if(c)if(lr(r).reveal==="emerge"){let qt=lr(r).width;z.style.width=qt,z.style.maxWidth=qt}else z.style.width="100%",z.style.maxWidth="100%";if(gr(),z.style.boxShadow=Le,z.style.borderRadius=ke,ne.style.border=at,ne.style.borderRadius=ke,c&&!ee&&(T==null?void 0:T.border)===void 0&&(ne.style.border="none",lr(r).side==="right"?ne.style.borderLeft="1px solid var(--persona-border)":ne.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",b&&(J.style.overflow="hidden"),z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",z.style.overflow="hidden",ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.overflow="hidden",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.overflowY="auto",_e.style.flexShrink="0"),J.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"),!g&&!b&&!c&&((Ir=cr[me])!=null?Ir:cr["bottom-right"]).split(" ").forEach(qt=>J.classList.add(qt)),g){let Dt=(Mn=(wn=r.launcher)==null?void 0:wn.sidebarWidth)!=null?Mn:"420px";J.style.cssText=`
66
+ `,X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0",W=!0,T();return}let Se=(Pn=(yt=r==null?void 0:r.launcher)==null?void 0:yt.width)!=null?Pn:r==null?void 0:r.launcherWidth,Pe=Se!=null?Se:sr;if(!g&&!c)b&&y?(ae.style.width="100%",ae.style.maxWidth="100%"):(ae.style.width=Pe,ae.style.maxWidth=Pe);else if(c)if(yr(r).reveal==="emerge"){let Vt=yr(r).width;ae.style.width=Vt,ae.style.maxWidth=Vt}else ae.style.width="100%",ae.style.maxWidth="100%";if(vr(),ae.style.boxShadow=Te,ae.style.borderRadius=Ee,de.style.border=lt,de.style.borderRadius=Ee,c&&!ee&&(k==null?void 0:k.border)===void 0&&(de.style.border="none",yr(r).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",b&&(ie.style.overflow="hidden"),ae.style.display="flex",ae.style.flexDirection="column",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.maxHeight="100%",ae.style.height="100%",ae.style.overflow="hidden",de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0"),ie.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"),!g&&!b&&!c&&((Br=br[he])!=null?Br:br["bottom-right"]).split(" ").forEach(Vt=>ie.classList.add(Vt)),g){let Bt=(In=(Sn=r.launcher)==null?void 0:Sn.sidebarWidth)!=null?In:"420px";ie.style.cssText=`
67
67
  position: fixed !important;
68
68
  top: 0 !important;
69
69
  bottom: 0 !important;
70
- width: ${Dt} !important;
70
+ width: ${Bt} !important;
71
71
  height: 100vh !important;
72
72
  max-height: 100vh !important;
73
73
  margin: 0 !important;
74
74
  padding: 0 !important;
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
- z-index: ${Ne} !important;
78
- ${Ce?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
- `,z.style.cssText=`
77
+ z-index: ${He} !important;
78
+ ${Ae?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
79
+ `,ae.style.cssText=`
80
80
  position: relative !important;
81
81
  display: flex !important;
82
82
  flex-direction: column !important;
@@ -87,9 +87,9 @@ _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;this
87
87
  min-height: 0 !important;
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
- box-shadow: ${Le} !important;
91
- border-radius: ${ke} !important;
92
- `,z.style.setProperty("width","100%","important"),z.style.setProperty("max-width","100%","important"),ne.style.cssText=`
90
+ box-shadow: ${Te} !important;
91
+ border-radius: ${Ee} !important;
92
+ `,ae.style.setProperty("width","100%","important"),ae.style.setProperty("max-width","100%","important"),de.style.cssText=`
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
95
  flex: 1 1 0% !important;
@@ -98,29 +98,29 @@ _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;this
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${ke} !important;
102
- border: ${at} !important;
101
+ border-radius: ${Ee} !important;
102
+ border: ${lt} !important;
103
103
  `,_e.style.cssText=`
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!b&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",qt=g?"":"padding-top: 1.25em !important;",kn=g?"":`z-index: ${($t=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?$t:gn} !important;`;J.style.cssText+=Dt+qt+kn}E()};Zn(),So(e,r),ti(e,r),ni(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",Or)});let Kt=null,Jt=null;ft.push(()=>{Kt==null||Kt(),Kt=null,Jt==null||Jt(),Jt=null}),Pn&&ft.push(()=>{Pn==null||Pn.disconnect(),Pn=null}),ft.push(()=>{hn==null||hn(),hn=null,Er(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),pe&&ft.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),ae==null||ae.destroy(),ae=null,G==null||G.destroy(),G=null,te=null});let Bn=null,_r=()=>{Bn&&(Bn(),Bn=null),r.colorScheme==="auto"&&(Bn=ki(()=>{So(e,r)}))};_r(),ft.push(()=>{Bn&&(Bn(),Bn=null)});let zn=(oc=r.features)==null?void 0:oc.streamAnimation;if(zn!=null&&zn.type&&zn.type!=="none"){let c=Ds(zn.type,zn.plugins);c&&(Ii(c,e),ft.push(()=>Kp(e)))}let er=vu(Ht),Dn=null,_,de=!1,Nn=_p(),tr=new Map,fr=new Map,ns=0,nr=Ba(),rr=0,or=null,Tr=!1,co=!1,Js=4,rs=24,Gs=80,Lo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},os=(ac=(sc=r.voiceRecognition)==null?void 0:sc.autoResume)!=null?ac:!1,Vn=c=>{o.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},En=()=>{m(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},Xs=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=sl(d.voiceState),g=!!c.active,y=Number((T=c.timestamp)!=null?T:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<Qy&&setTimeout(()=>{var D,N;mt.active||(mt.manuallyDeactivated=!1,((N=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:N.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),Vn("restore"),_.isVoiceActive()&&j()}):go("restore"))},1e3)},Ys=()=>_?Hu(_.getMessages()).filter(c=>!c.__skipPersist):[];function Po(c){if(!(i!=null&&i.save))return;let y={messages:c?Hu(c):_?Ys():[],metadata:d,artifacts:In.artifacts,selectedArtifactId:In.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Mr=null,Qs=()=>J.querySelector("#persona-scroll-container")||Te,po=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),Tr=!1},ss=()=>{or!==null&&(cancelAnimationFrame(or),or=null),co=!1,po()},kr=()=>{if(!Mt()||He){ut.parentNode&&ut.remove(),ut.style.display="none";return}ut.parentNode!==ne&&ne.appendChild(ut),_n();let c=Ws(Te)>0;ut.style.display=nr.isFollowing()||!c?"none":""},as=()=>{nr.pause()&&(ss(),kr())},jr=()=>{nr.resume(),kr()},Ur=(c=!1)=>{nr.isFollowing()&&(!c&&!de||(or!==null&&(cancelAnimationFrame(or),or=null),co=!0,or=requestAnimationFrame(()=>{or=null,co=!1,nr.isFollowing()&&Zs(Qs(),c?220:140)})))},Zs=(c,g=500)=>{let y=c.scrollTop,b=Ws(c),T=b-y;if(Math.abs(T)<1){rr=c.scrollTop;return}if(Math.abs(T)>=Gs){po(),Tr=!0,c.scrollTop=b,rr=c.scrollTop,Tr=!1;return}po();let D=performance.now();Tr=!0;let N=I=>1-Math.pow(1-I,3),q=I=>{if(!nr.isFollowing()){po();return}let be=Ws(c);be!==b&&(b=be,T=b-y);let le=I-D,ee=Math.min(le/g,1),me=N(ee),Ce=y+T*me;c.scrollTop=Ce,rr=c.scrollTop,ee<1?Mr=requestAnimationFrame(q):(c.scrollTop=b,rr=c.scrollTop,Mr=null,Tr=!1)};Mr=requestAnimationFrame(q)},ea=c=>{let g=new Map;c.forEach(y=>{let b=Lo.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Lo.clear(),g.forEach((y,b)=>{Lo.set(b,y)})},uo=(c,g,y)=>{var Xe,st,at,Le,ke,qe;let b=document.createElement("div"),D=(()=>{var Se;let E=s.find(We=>We.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((Se=r.loadingIndicator)!=null&&Se.render)return r.loadingIndicator.render})(),N=(E,Se)=>Se==null?!1:typeof Se=="string"?(E.textContent=Se,!0):(E.appendChild(Se),!0),q=new Set,I=new Set,be=s.some(E=>E.renderAskUserQuestion),le=[],ee=[],me=r.enableComponentStreaming!==!1;if(g.forEach(E=>{var xn,cn,Qe,it,vn,pn,fo,ho,yo,Do,No,Ut,bo,Xr;q.add(E.id);let Se=be&&to(E),We=!Se&&E.role==="assistant"&&!E.variant&&me&&tl(E);if(!We&&fr.has(E.id)){let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),fr.delete(E.id)}let Je=to(E)?`:${(xn=E.agentMetadata)!=null&&xn.askUserQuestionAnswered?"a":"u"}:${(cn=E.agentMetadata)!=null&&cn.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",ye=$p(E,ns)+Je,Tt=Se||We?null:jp(Nn,E.id,ye);if(Tt){b.appendChild(Tt.cloneNode(!0)),to(E)&&((Qe=E.toolCall)!=null&&Qe.id)&&((it=E.agentMetadata)==null?void 0:it.awaitingLocalTool)===!0&&!((vn=E.agentMetadata)!=null&&vn.askUserQuestionAnswered)&&(I.add(E.toolCall.id),zs(E,r,$e.composerOverlay));return}let ot=null,Xt=s.find(ht=>!!(E.variant==="reasoning"&&ht.renderReasoning||E.variant==="tool"&&ht.renderToolCall||E.variant==="approval"&&ht.renderApproval||!E.variant&&ht.renderMessage)),ln=(pn=r.layout)==null?void 0:pn.messages;if(to(E)&&((fo=E.agentMetadata)==null?void 0:fo.askUserQuestionAnswered)===!0){tr.delete(E.id);let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(to(E)&&((yo=(ho=r.features)==null?void 0:ho.askUserQuestion)==null?void 0:yo.enabled)!==!1){let ht=s.find(Tn=>typeof Tn.renderAskUserQuestion=="function");if(ht&&kt.current){let Tn=tr.get(E.id),Ir=Tn!==ye,wn=null;if(Ir){let{payload:$t,complete:Dt}=no(E),qt=E.id,kn=()=>{var Fn;return(Fn=kt.current)==null?void 0:Fn.getMessages().find(Zt=>Zt.id===qt)};wn=ht.renderAskUserQuestion({message:E,payload:$t,complete:Dt,resolve:Fn=>{var yr;let Zt=kn();Zt&&((yr=kt.current)==null||yr.resolveAskUserQuestion(Zt,Fn))},dismiss:()=>{var Zt,yr,Wr;let Fn=kn();(Zt=Fn==null?void 0:Fn.agentMetadata)!=null&&Zt.awaitingLocalTool&&((yr=kt.current)==null||yr.markAskUserQuestionResolved(Fn),(Wr=kt.current)==null||Wr.resolveAskUserQuestion(Fn,"(dismissed)"))},config:r})}let Mn=Tn!=null;if(Ir&&wn===null&&!Mn){((Do=E.agentMetadata)==null?void 0:Do.awaitingLocalTool)===!0&&!((No=E.agentMetadata)!=null&&No.askUserQuestionAnswered)&&(I.add(E.toolCall.id),zs(E,r,$e.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${E.id}`,Bt.setAttribute("data-wrapper-id",E.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),b.appendChild(Bt),le.push({messageId:E.id,fingerprint:ye,bubble:wn});return}else{((Ut=E.agentMetadata)==null?void 0:Ut.awaitingLocalTool)===!0&&!((bo=E.agentMetadata)!=null&&bo.askUserQuestionAnswered)&&(I.add(E.toolCall.id),zs(E,r,$e.composerOverlay));return}}else if(Xt)if(E.variant==="reasoning"&&E.reasoning&&Xt.renderReasoning){if(!Pe)return;ot=Xt.renderReasoning({message:E,defaultRenderer:()=>Oi(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Xt.renderToolCall){if(!ze)return;ot=Xt.renderToolCall({message:E,defaultRenderer:()=>Fi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Xt.renderApproval){if(r.approval===!1)return;ot=Xt.renderApproval({message:E,defaultRenderer:()=>Vi(E,r),config:r})}else Xt.renderMessage&&(ot=Xt.renderMessage({message:E,defaultRenderer:()=>{let ht=Us(E,y,ln,r.messageActions,tt,{loadingIndicatorRenderer:D,widgetConfig:r});return E.role!=="user"&&Gi(ht,E,r,_),ht},config:r}));if(!ot&&We){let ht=nl(E);if(ht){let Tn=fr.get(E.id),Ir=Tn!==ye,wn=r.wrapComponentDirectiveInBubble!==!1,Mn=null;if(Ir){let Bt=el(ht,{config:r,message:E,transform:y});if(Bt)if(wn){let $t=document.createElement("div");if($t.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$t.id=`bubble-${E.id}`,$t.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),$t.appendChild(Dt)}$t.appendChild(Bt),Mn=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${E.id}`,$t.setAttribute("data-message-id",E.id),$t.setAttribute("data-persona-component-directive","true"),E.content&&E.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),$t.appendChild(Dt)}$t.appendChild(Bt),Mn=$t}}if(Mn||Tn!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${E.id}`,Bt.setAttribute("data-wrapper-id",E.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),wn||Bt.classList.add("persona-w-full"),b.appendChild(Bt),ee.push({messageId:E.id,fingerprint:ye,bubble:Mn});return}}}if(!ot)if(E.variant==="reasoning"&&E.reasoning){if(!Pe)return;ot=Oi(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!ze)return;ot=Fi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;ot=Vi(E,r)}else{let ht=(Xr=r.layout)==null?void 0:Xr.messages;ht!=null&&ht.renderUserMessage&&E.role==="user"?ot=ht.renderUserMessage({message:E,config:r,streaming:!!E.streaming}):ht!=null&&ht.renderAssistantMessage&&E.role==="assistant"?ot=ht.renderAssistantMessage({message:E,config:r,streaming:!!E.streaming}):ot=Us(E,y,ht,r.messageActions,tt,{loadingIndicatorRenderer:D,widgetConfig:r}),E.role!=="user"&&ot&&Gi(ot,E,r,_)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${E.id}`,Pt.setAttribute("data-wrapper-id",E.id),E.role==="user"&&Pt.classList.add("persona-justify-end"),(ot==null?void 0:ot.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(ot),Up(Nn,E.id,ye,Pt),b.appendChild(Pt)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Se=>{let We=Se.getAttribute("data-persona-ask-sheet-for");We&&!I.has(We)&&Mo($e.composerOverlay,We)}),(st=(Xe=r.features)==null?void 0:Xe.toolCallDisplay)!=null&&st.grouped){let E=[],Se=[];g.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&ze){Se.push(We);return}Se.length>1&&E.push(Se),Se=[]}),Se.length>1&&E.push(Se),E.forEach((We,Je)=>{var cn,Qe;let ye=We.map(it=>Array.from(b.children).find(vn=>vn instanceof HTMLElement&&vn.getAttribute("data-wrapper-id")===it.id)).filter(it=>!!it);if(ye.length<2)return;let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-tool-group-${Je}-${We[0].id}`,Tt.setAttribute("data-wrapper-id",`tool-group-${Je}-${We[0].id}`);let ot=document.createElement("div");ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",ot.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ln=`Called ${We.length} tools`,Pt=(Qe=(cn=r.toolCall)==null?void 0:cn.renderGroupedSummary)==null?void 0:Qe.call(cn,{messages:We,toolCalls:We.map(it=>it.toolCall).filter(it=>!!it),defaultSummary:ln,config:r});N(Xt,Pt)||(Xt.textContent=ln);let xn=document.createElement("div");xn.className="persona-tool-group-stack persona-flex persona-flex-col",ot.append(Xt,xn),Tt.appendChild(ot),ye[0].before(Tt),ye.forEach((it,vn)=>{let pn=document.createElement("div");pn.className="persona-tool-group-item persona-relative",pn.setAttribute("data-persona-tool-group-item","true"),vn<ye.length-1&&pn.setAttribute("data-persona-tool-group-connector","true"),pn.appendChild(it),xn.appendChild(pn)})})}qp(Nn,q);let Ce=g.some(E=>E.role==="assistant"&&E.streaming),Ne=g[g.length-1],et=(Ne==null?void 0:Ne.role)==="assistant"&&!Ne.streaming&&Ne.variant!=="approval";if(de&&g.some(E=>E.role==="user")&&!Ce&&!et){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:Ko},Se=s.find(Je=>Je.renderLoadingIndicator),We=null;if(Se!=null&&Se.renderLoadingIndicator&&(We=Se.renderLoadingIndicator(E)),We===null&&((at=r.loadingIndicator)!=null&&at.render)&&(We=r.loadingIndicator.render(E)),We===null&&(We=Ko()),We){let Je=document.createElement("div"),ye=((Le=r.loadingIndicator)==null?void 0:Le.showBubble)!==!1;Je.className=ye?["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(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(We);let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id="wrapper-typing-indicator",Tt.setAttribute("data-wrapper-id","typing-indicator"),Tt.appendChild(Je),b.appendChild(Tt)}}if(!de&&g.length>0){let E=g[g.length-1],Se={config:r,lastMessage:E,messageCount:g.length},We=s.find(ye=>ye.renderIdleIndicator),Je=null;if(We!=null&&We.renderIdleIndicator&&(Je=We.renderIdleIndicator(Se)),Je===null&&((ke=r.loadingIndicator)!=null&&ke.renderIdle)&&(Je=r.loadingIndicator.renderIdle(Se)),Je){let ye=document.createElement("div"),Tt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;ye.className=Tt?["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(" "),ye.setAttribute("data-idle-indicator","true"),ye.appendChild(Je);let ot=document.createElement("div");ot.className="persona-flex",ot.id="wrapper-idle-indicator",ot.setAttribute("data-wrapper-id","idle-indicator"),ot.appendChild(ye),b.appendChild(ot)}}if(Ra(c,b),le.length>0)for(let{messageId:E,fingerprint:Se,bubble:We}of le){let Je=c.querySelector(`#wrapper-${E}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",Se),tr.set(E,Se))}if(tr.size>0)for(let E of tr.keys())q.has(E)||tr.delete(E);if(ee.length>0)for(let{messageId:E,fingerprint:Se,bubble:We}of ee){let Je=c.querySelector(`#wrapper-${E}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",Se),fr.set(E,Se))}if(fr.size>0)for(let E of fr.keys())q.has(E)||fr.delete(E)},qr=null,ta=()=>{var y;if(qr)return;let c=b=>{let T=b.composedPath();T.includes(J)||we&&T.includes(we)||Rt(!1,"user")};qr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},is=()=>{var g;if(!qr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",qr,!0),qr=null};ft.push(()=>is());let zr=null,na=()=>{var y;if(zr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Rt(!1,"user"))};zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},ls=()=>{var g;if(!zr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",zr,!0),zr=null};ft.push(()=>ls());let Vr=!1,cs=new Set,ra=()=>{var g,y,b,T;let c=(b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},Lr=()=>{var st,at,Le,ke;if(!F())return;let c=$e.peekBanner,g=$e.peekTextNode;if(!c||!g)return;if(W){c.classList.remove("persona-pill-peek--visible");return}let y=(st=_==null?void 0:_.getMessages())!=null?st:[],b;for(let qe=y.length-1;qe>=0;qe--){let E=y[qe];if(E.role==="assistant"&&E.content){b=E;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let T=b.content,D=!!b.streaming,N=ra(),q=Oa(N),I=q.type!=="none"?Ds(q.type,N==null?void 0:N.plugins):null,be=((at=I==null?void 0:I.isAnimating)==null?void 0:at.call(I,b))===!0,le=I!==null&&(D||be);le&&I&&!cs.has(I.name)&&(Ii(I,e),cs.add(I.name));let ee=le&&(I!=null&&I.containerClass)?I.containerClass:null,me=(Le=g.dataset.personaPeekStreamClass)!=null?Le:null;me&&me!==ee&&(g.classList.remove(me),delete g.dataset.personaPeekStreamClass),ee&&me!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),le?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ce=le?Fa(T,q.buffer,I,b,D):T;if(le&&q.placeholder==="skeleton"&&D&&(!Ce||!Ce.trim())){let qe=document.createElement("div"),E=Os();E.classList.add("persona-pill-peek__skeleton"),qe.appendChild(E),Ra(g,qe)}else{let qe=Math.max(0,Ce.length-100),E=Ce.length>100?Ce.slice(-100):Ce,Se=Fo(E);if(!le||!I){let We=Ce.length>100?`\u2026${E}`:E;g.textContent!==We&&(g.textContent=We)}else{let We=Se;(I.wrap==="char"||I.wrap==="word")&&(We=Ns(Se,I.wrap,`peek-${b.id}`,{skipTags:I.skipTags,startIndex:qe}));let Je=document.createElement("div");if(Je.innerHTML=We,I.useCaret&&E.length>0){let ye=$a(),Tt=Je.querySelectorAll(".persona-stream-char, .persona-stream-word"),ot=Tt[Tt.length-1];ot!=null&&ot.parentNode?ot.parentNode.insertBefore(ye,ot.nextSibling):Je.appendChild(ye)}Ra(g,Je),(ke=I.onAfterRender)==null||ke.call(I,{container:g,bubble:c,messageId:b.id,message:b,speed:q.speed,duration:q.duration})}}let Xe=de||Vr;c.classList.toggle("persona-pill-peek--visible",Xe)};if(F()){let c=$e.peekBanner;if(c){let b=T=>{T.preventDefault(),T.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let g=()=>{Vr||(Vr=!0,Lr())},y=()=>{Vr&&(Vr=!1,Lr())};z.addEventListener("pointerenter",g),z.addEventListener("pointerleave",y),ft.push(()=>{z.removeEventListener("pointerenter",g),z.removeEventListener("pointerleave",y)}),we&&(we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),ft.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}))}let oa=c=>{var me,Ce,Ne,et,Xe,st,at,Le;let g=(Ce=(me=r.launcher)==null?void 0:me.composerBar)!=null?Ce:{},y=(Ne=g.expandedSize)!=null?Ne:"anchored",b=(et=g.bottomOffset)!=null?et:"16px",T=g.collapsedMaxWidth,D=(Xe=g.expandedMaxWidth)!=null?Xe:"880px",N=(st=g.expandedTopOffset)!=null?st:"5vh",q=(at=g.modalMaxWidth)!=null?at:"880px",I=(Le=g.modalMaxHeight)!=null?Le:"min(90vh, 800px)",be="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",ee=J.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",we){let ke=we.style;ke.bottom=b,ke.width=T!=null?T:""}if(c&&y!=="fullscreen"){if(y==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=q,ee.maxWidth=be,ee.maxHeight=I,ee.height=I;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${b} + ${le})`,ee.top=N,ee.width=D,ee.maxWidth=be}},Kr=()=>{var I,be,le,ee,me,Ce,Ne,et;if(!$())return;if(F()){let st=(le=((be=(I=r.launcher)==null?void 0:I.composerBar)!=null?be:{}).expandedSize)!=null?le:"anchored",at=W?"expanded":"collapsed";J.dataset.state=at,J.dataset.expandedSize=st,we&&(we.dataset.state=at,we.dataset.expandedSize=st),J.style.removeProperty("display"),J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),oa(W),ne.style.display=W?"flex":"none",Zn(),W?(ta(),na()):(is(),ls()),Lr();return}let c=on(r),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,y=(Ce=(me=r.launcher)==null?void 0:me.mobileBreakpoint)!=null?Ce:640,b=(et=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?et:!0,T=g.innerWidth<=y,D=b&&T&&A,N=lr(r).reveal;W?(J.style.removeProperty("display"),J.style.display=c?"flex":"",J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-95","persona-opacity-0"),z.classList.add("persona-scale-100","persona-opacity-100"),Me?Me.element.style.display="none":Ge&&(Ge.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!D?(J.style.removeProperty("display"),J.style.display="flex",J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(J.style.setProperty("display","none","important"),J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(J.style.display="",J.classList.add("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100"),z.classList.add("persona-scale-95","persona-opacity-0")),Me?Me.element.style.display=c?"none":"":Ge&&(Ge.style.display=c?"none":""))},Rt=(c,g="user")=>{var D,N;if(!$()||W===c)return;let y=W;W=c,Kr();let b=(()=>{var Ne,et,Xe,st,at,Le,ke,qe,E,Se;let q=(et=(Ne=r.launcher)==null?void 0:Ne.sidebarMode)!=null?et:!1,I=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,be=(at=(st=r.launcher)==null?void 0:st.mobileFullscreen)!=null?at:!0,le=(ke=(Le=r.launcher)==null?void 0:Le.mobileBreakpoint)!=null?ke:640,ee=I.innerWidth<=le,me=on(r)&&be&&ee,Ce=F()&&((Se=(E=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:E.expandedSize)!=null?Se:"fullscreen")==="fullscreen";return q||be&&ee&&A||me||Ce})();if(W&&b){if(!Kt){let q=e.getRootNode(),I=q instanceof ShadowRoot?q.host:e.closest(".persona-host");I&&(Kt=Wi(I,(N=(D=r.launcher)==null?void 0:D.zIndex)!=null?N:gn))}Jt||(Jt=Ri(e.ownerDocument))}else W||(Kt==null||Kt(),Kt=null,Jt==null||Jt(),Jt=null);W&&(Lt(),Ur(!0));let T={open:W,source:g,timestamp:Date.now()};W&&!y?o.emit("widget:opened",T):!W&&y&&o.emit("widget:closed",T),o.emit("widget:state",{open:W,launcherEnabled:A,voiceActive:mt.active,streaming:_.isStreaming()})},Io=c=>{jt(c?"stop":"send"),P&&(P.disabled=c),er.buttons.forEach(g=>{g.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Wo=()=>{mt.active||ie&&ie.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Wo(),200)});let ds=()=>{var y,b,T,D,N,q,I,be,le,ee,me;vr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",dr.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",ie.placeholder=(q=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=Te.querySelector("[data-persona-intro-card]");if(c){let Ce=((I=r.copy)==null?void 0:I.showWelcomeCard)!==!1;c.style.display=Ce?"":"none",Ce?(Te.classList.remove("persona-gap-3"),Te.classList.add("persona-gap-6")):(Te.classList.remove("persona-gap-6"),Te.classList.add("persona-gap-3"))}!((le=(be=r.sendButton)==null?void 0:be.useIcon)!=null&&le)&&!(_!=null&&_.isStreaming())&&(re.textContent=(me=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?me:"Send"),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let hr=null,sa=()=>{hr==null&&(hr=setInterval(()=>{let c=ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(hr),hr=null;return}let g=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=va(g-b))})},100))};if(_=new ks(r,{onMessagesChanged(c){uo(ve,c,Ie),sa(),_&&(c.some(T=>T.role==="user")?er.render([],_,ie,c):er.render(r.suggestionChips,_,ie,c,r.suggestionChipsConfig)),Ur(!de),ea(c);let g=[...c].reverse().find(b=>b.role==="user"),y=mt.lastUserMessageId;g&&g.id!==y&&(mt.lastUserMessageId=g.id,o.emit("user:message",g)),mt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Po(c),Lr()},onStatusChanged(c){var b;let g=(b=r.statusIndicator)!=null?b:{};Oe(zt,(T=>{var D,N,q,I;return T==="idle"?(D=g.idleText)!=null?D:mn.idle:T==="connecting"?(N=g.connectingText)!=null?N:mn.connecting:T==="connected"?(q=g.connectedText)!=null?q:mn.connected:T==="error"?(I=g.errorText)!=null?I:mn.error:mn[T]})(c),g,c)},onStreamingChanged(c){de=c,Io(c),_&&uo(ve,_.getMessages(),Ie),c||Ur(!0),Lr()},onVoiceStatusChanged(c){var g,y;if(((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":X(),M();break;case"speaking":X(),Z();break;default:c==="idle"&&_.isBargeInActive()?(X(),j(),P==null||P.setAttribute("aria-label","End voice session")):(mt.active=!1,X(),Vn("system"),En());break}},onArtifactsState(c){In=c,Hn(),Po()}}),kt.current=_,((lc=(ic=r.voiceRecognition)==null?void 0:ic.provider)==null?void 0:lc.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(G||r.onSSEEvent)&&_.setSSEEventCallback((c,g)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,g),G==null||G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,y,b;c&&(c.metadata&&(d=sl(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length&&_.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&_.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ps=()=>{var g,y,b;!F()||W||!((b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Rt(!0,"auto")},us=c=>{var T;if(c.preventDefault(),_.isStreaming()){_.cancel();return}let g=ie.value.trim(),y=(T=vt==null?void 0:vt.hasAttachments())!=null?T:!1;if(!g&&!y)return;ps();let b;y&&(b=[],b.push(...vt.getContentParts()),g&&b.push(Ta(g))),ie.value="",ie.style.height="auto",mo(),_.sendMessage(g,{contentParts:b}),y&&vt.clearAttachments()},aa=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Ro={...Ha},Ho=!1,mo=()=>{Ro={...Ha}},ia=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),la=c=>{if(!ie)return;Ho=!0,ie.value=c,ie.dispatchEvent(new Event("input",{bubbles:!0})),Ho=!1;let g=ie.value.length;ie.setSelectionRange(g,g)},ms=()=>{Ho||mo()},gs=c=>{if(ie){if(aa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ie.selectionStart===0&&ie.selectionEnd===0,y=Fp({direction:c.key==="ArrowUp"?"up":"down",history:ia(),currentValue:ie.value,atStart:g,state:Ro});if(Ro=y.state,y.handled){c.preventDefault(),y.value!==void 0&&la(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}mo(),c.preventDefault(),re.click()}}},fs=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(ne)&&(_.cancel(),mo(),c.preventDefault(),c.stopImmediatePropagation())},hs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!vt)return;let g=eb(c.clipboardData);g.length!==0&&(c.preventDefault(),await vt.handleFiles(g))},yn=null,On=!1,Pr=null,rt=null,ys=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,go=(c="user")=>{var D,N,q,I,be,le,ee;if(On||_.isStreaming())return;let g=ys();if(!g)return;yn=new g;let b=(N=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?N:2e3;yn.continuous=!0,yn.interimResults=!0,yn.lang="en-US";let T=ie.value;yn.onresult=me=>{let Ce="",Ne="";for(let Xe=0;Xe<me.results.length;Xe++){let st=me.results[Xe],at=st[0].transcript;st.isFinal?Ce+=at+" ":Ne=at}let et=T+Ce+Ne;ie.value=et,Pr&&clearTimeout(Pr),(Ce||Ne)&&(Pr=window.setTimeout(()=>{let Xe=ie.value.trim();Xe&&yn&&On&&(sr(),ie.value="",ie.style.height="auto",_.sendMessage(Xe,{viaVoice:!0}))},b))},yn.onerror=me=>{me.error!=="no-speech"&&sr()},yn.onend=()=>{if(On){let me=ie.value.trim();me&&me!==T.trim()&&(ie.value="",ie.style.height="auto",_.sendMessage(me,{viaVoice:!0})),sr()}};try{if(yn.start(),On=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),Vn(c),En(),P){let me=(q=r.voiceRecognition)!=null?q:{};rt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(I=me.iconName)!=null?I:"mic",iconSize:parseFloat((ee=(le=me.iconSize)!=null?le:(be=r.sendButton)==null?void 0:be.size)!=null?ee:"40")||24};let Ce=me.recordingBackgroundColor,Ne=me.recordingIconColor,et=me.recordingBorderColor;if(P.classList.add("persona-voice-recording"),P.style.backgroundColor=Ce!=null?Ce:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let Xe=P.querySelector("svg");Xe&&Xe.setAttribute("stroke",Ne)}et&&(P.style.borderColor=et),P.setAttribute("aria-label","Stop voice recognition")}}catch{sr("system")}},sr=(c="user")=>{if(On){if(On=!1,Pr&&(clearTimeout(Pr),Pr=null),yn){try{yn.stop()}catch{}yn=null}if(mt.active=!1,Vn(c),En(),P){if(P.classList.remove("persona-voice-recording"),rt){P.style.backgroundColor=rt.backgroundColor,P.style.color=rt.color,P.style.borderColor=rt.borderColor;let g=P.querySelector("svg");g&&g.setAttribute("stroke",rt.color||"currentColor"),rt=null}P.setAttribute("aria-label","Start voice recognition")}}},ca=(c,g)=>{var st,at,Le,ke,qe,E,Se,We;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((st=c==null?void 0:c.provider)==null?void 0:st.type)==="runtype";if(!(y||b))return null;let D=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(at=c==null?void 0:c.iconName)!=null?at:"mic",I=(Le=g==null?void 0:g.size)!=null?Le:"40px",be=(ke=c==null?void 0:c.iconSize)!=null?ke:I,le=parseFloat(be)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,me=(E=c==null?void 0:c.iconColor)!=null?E:g==null?void 0:g.textColor;N.style.width=be,N.style.height=be,N.style.minWidth=be,N.style.minHeight=be,N.style.fontSize="18px",N.style.lineHeight="1",me?N.style.color=me:N.style.color="var(--persona-text, #111827)";let Ne=fe(q,le,me||"currentColor",1.5);Ne?N.appendChild(Ne):N.textContent="\u{1F3A4}",ee?N.style.backgroundColor=ee:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),D.appendChild(N);let et=(Se=c==null?void 0:c.tooltipText)!=null?Se:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&et){let Je=h("div","persona-send-button-tooltip");Je.textContent=et,D.appendChild(Je)}return{micButton:N,micButtonWrapper:D}},Jr=()=>{var g,y,b,T,D;if(!P||rt)return;let c=(g=r.voiceRecognition)!=null?g:{};rt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((D=(T=c.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},Ve=(c,g)=>{var D,N,q,I,be;if(!P)return;let y=P.querySelector("svg");y&&y.remove();let b=(be=rt==null?void 0:rt.iconSize)!=null?be:parseFloat((I=(q=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(N=r.sendButton)==null?void 0:N.size)!=null?I:"40")||24,T=fe(c,b,g,1.5);T&&P.appendChild(T)},C=()=>{P&&P.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},j=()=>{var T;if(!P)return;Jr();let c=(T=r.voiceRecognition)!=null?T:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(C(),P.classList.add("persona-voice-recording"),P.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let D=P.querySelector("svg");D&&D.setAttribute("stroke",y)}b&&(P.style.borderColor=b),P.setAttribute("aria-label","Stop voice recognition")},M=()=>{var q,I,be,le,ee,me,Ce,Ne;if(!P)return;Jr();let c=(q=r.voiceRecognition)!=null?q:{},g=_.getVoiceInterruptionMode(),y=(I=c.processingIconName)!=null?I:"loader",b=(le=(be=c.processingIconColor)!=null?be:rt==null?void 0:rt.color)!=null?le:"",T=(me=(ee=c.processingBackgroundColor)!=null?ee:rt==null?void 0:rt.backgroundColor)!=null?me:"",D=(Ne=(Ce=c.processingBorderColor)!=null?Ce:rt==null?void 0:rt.borderColor)!=null?Ne:"";C(),P.classList.add("persona-voice-processing"),P.style.backgroundColor=T,P.style.borderColor=D;let N=b||"currentColor";P.style.color=N,Ve(y,N),P.setAttribute("aria-label","Processing voice input"),g==="none"&&(P.style.cursor="default")},Z=()=>{var be,le,ee,me,Ce,Ne,et,Xe,st,at,Le,ke;if(!P)return;Jr();let c=(be=r.voiceRecognition)!=null?be:{},g=_.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:y,T=(Ne=c.speakingIconColor)!=null?Ne:g==="barge-in"?(me=(ee=c.recordingIconColor)!=null?ee:rt==null?void 0:rt.color)!=null?me:"":(Ce=rt==null?void 0:rt.color)!=null?Ce:"",D=(st=c.speakingBackgroundColor)!=null?st:g==="barge-in"?(et=c.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Xe=rt==null?void 0:rt.backgroundColor)!=null?Xe:"",N=(ke=c.speakingBorderColor)!=null?ke:g==="barge-in"?(at=c.recordingBorderColor)!=null?at:"":(Le=rt==null?void 0:rt.borderColor)!=null?Le:"";C(),P.classList.add("persona-voice-speaking"),P.style.backgroundColor=D,P.style.borderColor=N;let q=T||"currentColor";P.style.color=q,Ve(b,q);let I=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";P.setAttribute("aria-label",I),g==="none"&&(P.style.cursor="default"),g==="barge-in"&&P.classList.add("persona-voice-recording")},X=()=>{var c,g,y;P&&(C(),rt&&(P.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",P.style.color=(g=rt.color)!=null?g:"",P.style.borderColor=(y=rt.borderColor)!=null?y:"",Ve(rt.iconName,rt.color||"currentColor"),rt=null),P.style.cursor="",P.setAttribute("aria-label","Start voice recognition"))},Y=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let y=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,En(),Vn("user"),X()});return}_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),mt.manuallyDeactivated=!_.isVoiceActive(),En(),Vn("user"),_.isVoiceActive()?j():X()});return}if(On){let y=ie.value.trim();mt.manuallyDeactivated=!0,En(),sr("user"),y&&(ie.value="",ie.style.height="auto",_.sendMessage(y))}else mt.manuallyDeactivated=!1,En(),go("user")};pr=Y,P&&(P.addEventListener("click",Y),ft.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),X()):sr("system"),P&&P.removeEventListener("click",Y)}));let Ye=o.on("assistant:complete",()=>{os&&(mt.active||mt.manuallyDeactivated||os==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!mt.active&&!mt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),Vn("auto"),_.isVoiceActive()&&j()}):go("auto"))},600))});ft.push(Ye);let Fe=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ft.push(Fe);let Ze=()=>{Rt(!W,"user")},Me=null,Ge=null;if(A&&!F()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>$s(r,Ze).element,onToggle:Ze});g&&(Ge=g)}Ge||(Me=$s(r,Ze))}Me?e.appendChild(Me.element):Ge&&e.appendChild(Ge),Kr(),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),ds(),Io(_.isStreaming()),Ur(!0),Xs(),R&&(!A||F()?setTimeout(()=>Wo(),0):W&&setTimeout(()=>Wo(),200));let Lt=()=>{var I,be,le,ee,me,Ce,Ne,et,Xe,st,at,Le,ke,qe,E,Se,We,Je,ye,Tt,ot,Xt;if(F()){_n(),Kr();return}let c=on(r),g=(be=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?be:!1,y=c||g||((ee=(le=r.launcher)==null?void 0:le.fullHeight)!=null?ee:!1),b=(me=e.ownerDocument.defaultView)!=null?me:window,T=(Ne=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Ne:!0,D=(Xe=(et=r.launcher)==null?void 0:et.mobileBreakpoint)!=null?Xe:640,N=b.innerWidth<=D,q=T&&N&&A;try{if(q){Zn(),So(e,r);return}if(B&&(B=!1,Zn(),So(e,r)),!A&&!c){z.style.height="",z.style.width="";return}if(!g&&!c){let ln=(at=(st=r==null?void 0:r.launcher)==null?void 0:st.width)!=null?at:r==null?void 0:r.launcherWidth,Pt=ln!=null?ln:Gn;z.style.width=Pt,z.style.maxWidth=Pt}if(gr(),!y){let ln=b.innerHeight,Pt=64,xn=(ke=(Le=r.launcher)==null?void 0:Le.heightOffset)!=null?ke:0,cn=Math.max(200,ln-Pt),Qe=Math.min(640,cn),it=Math.max(200,Qe-xn);z.style.height=`${it}px`}}finally{if(_n(),Kr(),W&&A){let Pt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Se=(E=r.launcher)==null?void 0:E.mobileBreakpoint)!=null?Se:640),xn=(Je=(We=r.launcher)==null?void 0:We.sidebarMode)!=null?Je:!1,cn=(Tt=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Tt:!0,Qe=on(r)&&cn&&Pt,it=xn||cn&&Pt&&A||Qe;if(it&&!Jt){let vn=e.getRootNode(),pn=vn instanceof ShadowRoot?vn.host:e.closest(".persona-host");pn&&!Kt&&(Kt=Wi(pn,(Xt=(ot=r.launcher)==null?void 0:ot.zIndex)!=null?Xt:gn)),Jt=Ri(e.ownerDocument)}else it||(Kt==null||Kt(),Kt=null,Jt==null||Jt(),Jt=null)}}};Lt();let en=(cc=e.ownerDocument.defaultView)!=null?cc:window;if(en.addEventListener("resize",Lt),ft.push(()=>en.removeEventListener("resize",Lt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{_n()});c.observe(_e),ft.push(()=>c.disconnect())}rr=Te.scrollTop;let wt=Te.scrollHeight,Et=()=>{let c=Te.scrollTop,g=Te.scrollHeight,y=g<wt;wt=g;let{action:b,nextLastScrollTop:T}=Da({following:nr.isFollowing(),currentScrollTop:c,lastScrollTop:rr,nearBottom:Rs(Te,rs),userScrollThreshold:Js,isAutoScrolling:Tr||co||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rr=T,b==="resume"){jr();return}b==="pause"&&as()};Te.addEventListener("scroll",Et,{passive:!0}),ft.push(()=>Te.removeEventListener("scroll",Et));let tn=c=>{let g=Na({following:nr.isFollowing(),deltaY:c.deltaY,nearBottom:Rs(Te,rs),resumeWhenNearBottom:!0});g==="pause"?as():g==="resume"&&jr()};Te.addEventListener("wheel",tn,{passive:!0}),ft.push(()=>Te.removeEventListener("wheel",tn)),ut.addEventListener("click",()=>{Te.scrollTop=Te.scrollHeight,rr=Te.scrollTop,jr(),Ur(!0)}),ft.push(()=>ut.remove()),ft.push(()=>{ss()});let dn=()=>{Ue&&(Dn&&(Ue.removeEventListener("click",Dn),Dn=null),$()?(Ue.style.display="",Dn=()=>{Rt(!1,"user")},Ue.addEventListener("click",Dn)):Ue.style.display="none")};dn(),(()=>{let{clearChatButton:c}=$e;c&&c.addEventListener("click",()=>{_.clearMessages(),Nn.clear(),jr(),Mo($e.composerOverlay);try{localStorage.removeItem(es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},S.syncFromMetadata(),G==null||G.clear(),ae==null||ae.update()})})(),Nt&&Nt.addEventListener("submit",us),ie==null||ie.addEventListener("keydown",gs),ie==null||ie.addEventListener("input",ms),ie==null||ie.addEventListener("paste",hs);let Gt=(dc=e.ownerDocument)!=null?dc:document;Gt.addEventListener("keydown",fs,!0);let Kn="persona-attachment-drop-active",bs=0,hi=()=>{bs=0,ne.classList.remove(Kn)},Bo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&vt!==null},yl=c=>{!ai(c.dataTransfer)||!Bo()||(bs++,bs===1&&ne.classList.add(Kn))},bl=c=>{!ai(c.dataTransfer)||!Bo()||(bs--,bs<=0&&hi())},xl=c=>{!ai(c.dataTransfer)||!Bo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},vl=c=>{var y;if(!ai(c.dataTransfer)||!Bo())return;c.preventDefault(),c.stopPropagation(),hi();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&vt.handleFiles(g)},Gr=!0;ne.addEventListener("dragenter",yl,Gr),ne.addEventListener("dragleave",bl,Gr),e.addEventListener("dragover",xl,Gr),e.addEventListener("drop",vl,Gr);let da=e.ownerDocument,wl=c=>{Bo()&&c.preventDefault()},Cl=c=>{Bo()&&c.preventDefault()};da.addEventListener("dragover",wl),da.addEventListener("drop",Cl),ft.push(()=>{Nt&&Nt.removeEventListener("submit",us),ie==null||ie.removeEventListener("keydown",gs),ie==null||ie.removeEventListener("input",ms),ie==null||ie.removeEventListener("paste",hs),Gt.removeEventListener("keydown",fs,!0)}),ft.push(()=>{ne.removeEventListener("dragenter",yl,Gr),ne.removeEventListener("dragleave",bl,Gr),e.removeEventListener("dragover",xl,Gr),e.removeEventListener("drop",vl,Gr),da.removeEventListener("dragover",wl),da.removeEventListener("drop",Cl),hi()}),ft.push(()=>{_.cancel()}),Me?ft.push(()=>{Me==null||Me.destroy()}):Ge&&ft.push(()=>{Ge==null||Ge.remove()});let Qt={update(c){var Zt,yr,Wr,pa,ua,ma,xo,ga,xs,yc,bc,xc,vc,wc,Cc,Ac,Sc,Ec,Tc,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Yc,Qc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,$d,_d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Yd,Qd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up;let g=r.toolCall,y=r.messageActions,b=(Zt=r.layout)==null?void 0:Zt.messages,T=r.colorScheme,D=r.loadingIndicator,N=r.iterationDisplay,q=(yr=r.features)==null?void 0:yr.showReasoning,I=(Wr=r.features)==null?void 0:Wr.showToolCalls,be=(pa=r.features)==null?void 0:pa.toolCallDisplay,le=(ua=r.features)==null?void 0:ua.reasoningDisplay;r={...r,...c},Zn(),So(e,r),ti(e,r),ni(e,r),Hn(),r.colorScheme!==T&&_r();let ee=ri.getForInstance(r.plugins);s.length=0,s.push(...ee),A=(xo=(ma=r.launcher)==null?void 0:ma.enabled)!=null?xo:!0,k=(xs=(ga=r.launcher)==null?void 0:ga.autoExpand)!=null?xs:!1,Pe=(bc=(yc=r.features)==null?void 0:yc.showReasoning)!=null?bc:!0,ze=(vc=(xc=r.features)==null?void 0:xc.showToolCalls)!=null?vc:!0,ce=(Cc=(wc=r.features)==null?void 0:wc.scrollToBottom)!=null?Cc:{},Br(),kr();let me=pe;if(pe=(Sc=(Ac=r.features)==null?void 0:Ac.showEventStreamToggle)!=null?Sc:!1,pe&&!me){if(G||(te=new Ks(je),G=new Vs(xe,te),te.open().then(()=>G==null?void 0:G.restore()).catch(()=>{}),_.setSSEEventCallback((Q,xt)=>{var Ot;(Ot=r.onSSEEvent)==null||Ot.call(r,Q,xt),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!gt&&De){let Q=(Tc=(Ec=r.features)==null?void 0:Ec.eventStream)==null?void 0:Tc.classNames,xt="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"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");gt=h("button",xt),gt.style.width="28px",gt.style.height="28px",gt.style.color=An.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let Ot=fe("activity","18px","currentColor",1.5);Ot&&gt.appendChild(Ot);let lt=$e.clearChatButtonWrapper,St=$e.closeButtonWrapper,nn=lt||St;nn&&nn.parentNode===De?De.insertBefore(gt,nn):De.appendChild(gt),gt.addEventListener("click",()=>{He?Qn():Cr()})}}else!pe&&me&&(Qn(),gt&&(gt.remove(),gt=null),G==null||G.clear(),te==null||te.destroy(),G=null,te=null);if(((Mc=r.launcher)==null?void 0:Mc.enabled)===!1&&Me&&(Me.destroy(),Me=null),((kc=r.launcher)==null?void 0:kc.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((Lc=r.launcher)==null?void 0:Lc.enabled)!==!1&&!Me&&!Ge){let Q=s.find(xt=>xt.renderLauncher);if(Q!=null&&Q.renderLauncher){let xt=Q.renderLauncher({config:r,defaultRenderer:()=>$s(r,Ze).element,onToggle:Ze});xt&&(Ge=xt,e.appendChild(Ge))}Ge||(Me=$s(r,Ze),e.appendChild(Me.element))}Me&&Me.update(r),Ae&&((Pc=r.launcher)==null?void 0:Pc.title)!==void 0&&(Ae.textContent=r.launcher.title),Be&&((Ic=r.launcher)==null?void 0:Ic.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Ce=(Wc=r.layout)==null?void 0:Wc.header;if((Ce==null?void 0:Ce.layout)!==w&&De){let Q=Ce?_s(r,Ce,{showClose:$(),onClose:()=>Rt(!1,"user")}):eo({config:r,showClose:$(),onClose:()=>Rt(!1,"user")});De.replaceWith(Q.header),De=Q.header,U=Q.iconHolder,Ae=Q.headerTitle,Be=Q.headerSubtitle,Ue=Q.closeButton,w=Ce==null?void 0:Ce.layout}else if(Ce&&(U&&(U.style.display=Ce.showIcon===!1?"none":""),Ae&&(Ae.style.display=Ce.showTitle===!1?"none":""),Be&&(Be.style.display=Ce.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=Ce.showCloseButton===!1?"none":""),$e.clearChatButtonWrapper)){let Q=Ce.showClearChat;if(Q!==void 0){$e.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:xt}=$e;xt&&!xt.classList.contains("persona-absolute")&&(Q?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let et=((Rc=r.layout)==null?void 0:Rc.showHeader)!==!1;De&&(De.style.display=et?"":"none");let Xe=((Hc=r.layout)==null?void 0:Hc.showFooter)!==!1;_e&&(_e.style.display=Xe?"":"none"),_n(),kr(),A!==L?A?Rt(k,"auto"):(W=!0,Kr()):k!==H&&Rt(k,"auto"),H=k,L=A,Lt(),dn();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(g),ke=JSON.stringify(r.messageActions)!==JSON.stringify(y),qe=JSON.stringify((Bc=r.layout)==null?void 0:Bc.messages)!==JSON.stringify(b),E=((Dc=r.loadingIndicator)==null?void 0:Dc.render)!==(D==null?void 0:D.render)||((Nc=r.loadingIndicator)==null?void 0:Nc.renderIdle)!==(D==null?void 0:D.renderIdle)||((Oc=r.loadingIndicator)==null?void 0:Oc.showBubble)!==(D==null?void 0:D.showBubble),Se=r.iterationDisplay!==N,We=(($c=(Fc=r.features)==null?void 0:Fc.showReasoning)!=null?$c:!0)!==(q!=null?q:!0)||((jc=(_c=r.features)==null?void 0:_c.showToolCalls)!=null?jc:!0)!==(I!=null?I:!0)||JSON.stringify((Uc=r.features)==null?void 0:Uc.toolCallDisplay)!==JSON.stringify(be)||JSON.stringify((qc=r.features)==null?void 0:qc.reasoningDisplay)!==JSON.stringify(le);(Le||ke||qe||E||Se||We)&&_&&(ns++,uo(ve,_.getMessages(),Ie));let ye=(zc=r.launcher)!=null?zc:{},Tt=(Vc=ye.headerIconHidden)!=null?Vc:!1,ot=(Jc=(Kc=r.layout)==null?void 0:Kc.header)==null?void 0:Jc.showIcon,Xt=Tt||ot===!1,ln=ye.headerIconName,Pt=(Gc=ye.headerIconSize)!=null?Gc:"48px";if(U){let Q=ne.querySelector(".persona-border-b-persona-divider"),xt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Xt)U.style.display="none",Q&&xt&&!Q.contains(xt)&&Q.insertBefore(xt,Q.firstChild);else{if(U.style.display="",U.style.height=Pt,U.style.width=Pt,Q&&xt&&(Q.contains(U)?U.nextSibling!==xt&&(U.remove(),Q.insertBefore(U,xt)):Q.insertBefore(U,xt)),ln){let lt=parseFloat(Pt)||24,St=fe(ln,lt*.6,"#ffffff",2);St?U.replaceChildren(St):U.textContent=(Xc=ye.agentIconText)!=null?Xc:"\u{1F4AC}"}else if(ye.iconUrl){let lt=U.querySelector("img");if(lt)lt.src=ye.iconUrl,lt.style.height=Pt,lt.style.width=Pt;else{let St=document.createElement("img");St.src=ye.iconUrl,St.alt="",St.className="persona-rounded-xl persona-object-cover",St.style.height=Pt,St.style.width=Pt,U.replaceChildren(St)}}else{let lt=U.querySelector("svg"),St=U.querySelector("img");(lt||St)&&U.replaceChildren(),U.textContent=(Yc=ye.agentIconText)!=null?Yc:"\u{1F4AC}"}let Ot=U.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let xn=(Zc=(Qc=r.layout)==null?void 0:Qc.header)==null?void 0:Zc.showTitle,cn=(td=(ed=r.layout)==null?void 0:ed.header)==null?void 0:td.showSubtitle;if(Ae&&(Ae.style.display=xn===!1?"none":""),Be&&(Be.style.display=cn===!1?"none":""),Ue){((rd=(nd=r.layout)==null?void 0:nd.header)==null?void 0:rd.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let xt=(od=ye.closeButtonSize)!=null?od:"32px",Ot=(sd=ye.closeButtonPlacement)!=null?sd:"inline";Ue.style.height=xt,Ue.style.width=xt;let{closeButtonWrapper:lt}=$e,St=Ot==="top-right",nn=lt==null?void 0:lt.classList.contains("persona-absolute");if(lt&&St!==nn)if(lt.remove(),St)lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(lt);else{let pt=(id=(ad=ye.clearChat)==null?void 0:ad.placement)!=null?id:"inline",rn=(cd=(ld=ye.clearChat)==null?void 0:ld.enabled)!=null?cd:!0;lt.className=rn&&pt==="inline"?"":"persona-ml-auto";let Ln=ne.querySelector(".persona-border-b-persona-divider");Ln&&Ln.appendChild(lt)}if(Ue.style.color=ye.closeButtonColor||An.actionIconColor,ye.closeButtonBackgroundColor?(Ue.style.backgroundColor=ye.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let pt=ye.closeButtonBorderWidth||"0px",rn=ye.closeButtonBorderColor||"transparent";Ue.style.border=`${pt} solid ${rn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");ye.closeButtonBorderRadius?(Ue.style.borderRadius=ye.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(Ue.style.paddingLeft=ye.closeButtonPaddingX,Ue.style.paddingRight=ye.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),ye.closeButtonPaddingY?(Ue.style.paddingTop=ye.closeButtonPaddingY,Ue.style.paddingBottom=ye.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let un=(dd=ye.closeButtonIconName)!=null?dd:"x",ar=(pd=ye.closeButtonIconText)!=null?pd:"\xD7";Ue.innerHTML="";let Cn=fe(un,"28px","currentColor",1);Cn?Ue.appendChild(Cn):Ue.textContent=ar;let Yt=(ud=ye.closeButtonTooltipText)!=null?ud:"Close chat",$n=(md=ye.closeButtonShowTooltip)!=null?md:!0;if(Ue.setAttribute("aria-label",Yt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),$n&&Yt)){let pt=null,rn=()=>{if(pt||!Ue)return;let vo=Ue.ownerDocument,vs=vo.body;if(!vs)return;pt=br(vo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let ws=br(vo,"div");ws.className="persona-clear-chat-tooltip-arrow",pt.appendChild(ws);let wo=Ue.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Yr),pt.style.left=`${wo.left+wo.width/2}px`,pt.style.top=`${wo.top-8}px`,pt.style.transform="translate(-50%, -100%)",vs.appendChild(pt)},Ln=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",rn),lt.addEventListener("mouseleave",Ln),Ue.addEventListener("focus",rn),Ue.addEventListener("blur",Ln),lt._cleanupTooltip=()=>{Ln(),lt&&(lt.removeEventListener("mouseenter",rn),lt.removeEventListener("mouseleave",Ln)),Ue&&(Ue.removeEventListener("focus",rn),Ue.removeEventListener("blur",Ln))}}}let{clearChatButton:Qe,clearChatButtonWrapper:it}=$e;if(Qe){let Q=(gd=ye.clearChat)!=null?gd:{},xt=(fd=Q.enabled)!=null?fd:!0,Ot=(yd=(hd=r.layout)==null?void 0:hd.header)==null?void 0:yd.showClearChat,lt=Ot!==void 0?Ot:xt,St=(bd=Q.placement)!=null?bd:"inline";if(it){it.style.display=lt?"":"none";let{closeButtonWrapper:nn}=$e;!F()&&nn&&!nn.classList.contains("persona-absolute")&&(lt?nn.classList.remove("persona-ml-auto"):nn.classList.add("persona-ml-auto"));let un=St==="top-right",ar=it.classList.contains("persona-absolute");if(!F()&&un!==ar&&lt){if(it.remove(),un)it.className="persona-absolute persona-top-4 persona-z-50",it.style.right="48px",ne.style.position="relative",ne.appendChild(it);else{it.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",it.style.right="";let Yt=ne.querySelector(".persona-border-b-persona-divider"),$n=$e.closeButtonWrapper;Yt&&$n&&$n.parentElement===Yt?Yt.insertBefore(it,$n):Yt&&Yt.appendChild(it)}let Cn=$e.closeButtonWrapper;Cn&&!Cn.classList.contains("persona-absolute")&&(un?Cn.classList.add("persona-ml-auto"):Cn.classList.remove("persona-ml-auto"))}}if(lt){if(!F()){let pt=(xd=Q.size)!=null?xd:"32px";Qe.style.height=pt,Qe.style.width=pt}let nn=(vd=Q.iconName)!=null?vd:"refresh-cw",un=(wd=Q.iconColor)!=null?wd:"";Qe.style.color=un||An.actionIconColor,Qe.innerHTML="";let ar=F()?"14px":"20px",Cn=fe(nn,ar,"currentColor",2);if(Cn&&Qe.appendChild(Cn),Q.backgroundColor?(Qe.style.backgroundColor=Q.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let pt=Q.borderWidth||"0px",rn=Q.borderColor||"transparent";Qe.style.border=`${pt} solid ${rn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");Q.borderRadius?(Qe.style.borderRadius=Q.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),Q.paddingX?(Qe.style.paddingLeft=Q.paddingX,Qe.style.paddingRight=Q.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),Q.paddingY?(Qe.style.paddingTop=Q.paddingY,Qe.style.paddingBottom=Q.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Yt=(Cd=Q.tooltipText)!=null?Cd:"Clear chat",$n=(Ad=Q.showTooltip)!=null?Ad:!0;if(Qe.setAttribute("aria-label",Yt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),$n&&Yt)){let pt=null,rn=()=>{if(pt||!Qe)return;let vo=Qe.ownerDocument,vs=vo.body;if(!vs)return;pt=br(vo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let ws=br(vo,"div");ws.className="persona-clear-chat-tooltip-arrow",pt.appendChild(ws);let wo=Qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Yr),pt.style.left=`${wo.left+wo.width/2}px`,pt.style.top=`${wo.top-8}px`,pt.style.transform="translate(-50%, -100%)",vs.appendChild(pt)},Ln=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",rn),it.addEventListener("mouseleave",Ln),Qe.addEventListener("focus",rn),Qe.addEventListener("blur",Ln),it._cleanupTooltip=()=>{Ln(),it&&(it.removeEventListener("mouseenter",rn),it.removeEventListener("mouseleave",Ln)),Qe&&(Qe.removeEventListener("focus",rn),Qe.removeEventListener("blur",Ln))}}}}let vn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[oi],pn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Zo.message,Zo.messageAndClick];S=si({parsers:vn,handlers:pn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Bu(r,S,oe),_.updateConfig(r),uo(ve,_.getMessages(),Ie),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),ds(),Io(_.isStreaming());let fo=((Sd=r.voiceRecognition)==null?void 0:Sd.enabled)===!0,ho=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),yo=((Td=(Ed=r.voiceRecognition)==null?void 0:Ed.provider)==null?void 0:Td.type)==="runtype";if(fo&&(ho||yo))if(!P||!he){let Q=ca(r.voiceRecognition,r.sendButton);Q&&(P=Q.micButton,he=Q.micButtonWrapper,Ct.insertBefore(he,sn),P.addEventListener("click",Y),P.disabled=_.isStreaming())}else{let Q=(Md=r.voiceRecognition)!=null?Md:{},xt=(kd=r.sendButton)!=null?kd:{},Ot=(Ld=Q.iconName)!=null?Ld:"mic",lt=(Pd=xt.size)!=null?Pd:"40px",St=(Id=Q.iconSize)!=null?Id:lt,nn=parseFloat(St)||24;P.style.width=St,P.style.height=St,P.style.minWidth=St,P.style.minHeight=St;let un=(Rd=(Wd=Q.iconColor)!=null?Wd:xt.textColor)!=null?Rd:"currentColor";P.innerHTML="";let ar=fe(Ot,nn,un,2);ar?P.appendChild(ar):P.textContent="\u{1F3A4}";let Cn=(Hd=Q.backgroundColor)!=null?Hd:xt.backgroundColor;Cn?P.style.backgroundColor=Cn:P.style.backgroundColor="",un?P.style.color=un:P.style.color="var(--persona-text, #111827)",Q.borderWidth?(P.style.borderWidth=Q.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),Q.borderColor?P.style.borderColor=Q.borderColor:P.style.borderColor="",Q.paddingX?(P.style.paddingLeft=Q.paddingX,P.style.paddingRight=Q.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),Q.paddingY?(P.style.paddingTop=Q.paddingY,P.style.paddingBottom=Q.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),$n=(Bd=Q.tooltipText)!=null?Bd:"Start voice recognition";if(((Dd=Q.showTooltip)!=null?Dd:!1)&&$n)if(Yt)Yt.textContent=$n,Yt.style.display="";else{let rn=document.createElement("div");rn.className="persona-send-button-tooltip",rn.textContent=$n,he==null||he.insertBefore(rn,P)}else Yt&&(Yt.style.display="none");he.style.display="",P.disabled=_.isStreaming()}else P&&he&&(he.style.display="none",((Od=(Nd=r.voiceRecognition)==null?void 0:Nd.provider)==null?void 0:Od.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():On&&sr());if(((Fd=r.attachments)==null?void 0:Fd.enabled)===!0)if(!dt||!ge){let Q=($d=r.attachments)!=null?$d:{},Ot=(jd=((_d=r.sendButton)!=null?_d:{}).size)!=null?jd:"40px";It||(It=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),It.style.display="none",Nt.insertBefore(It,ie)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((Ud=Q.allowedTypes)!=null?Ud:Rr).join(","),Ke.multiple=((qd=Q.maxFiles)!=null?qd:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Nt.insertBefore(Ke,ie)),dt=h("div","persona-send-button-wrapper"),ge=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ge.type="button",ge.setAttribute("aria-label",(zd=Q.buttonTooltipText)!=null?zd:"Attach file");let lt=(Vd=Q.buttonIconName)!=null?Vd:"paperclip",St=Ot,nn=parseFloat(St)||40,un=Math.round(nn*.6);ge.style.width=St,ge.style.height=St,ge.style.minWidth=St,ge.style.minHeight=St,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.style.backgroundColor="transparent",ge.style.color="var(--persona-primary, #111827)",ge.style.border="none",ge.style.borderRadius="6px",ge.style.transition="background-color 0.15s ease",ge.addEventListener("mouseenter",()=>{ge.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ge.addEventListener("mouseleave",()=>{ge.style.backgroundColor="transparent"});let ar=fe(lt,un,"currentColor",1.5);ar?ge.appendChild(ar):ge.textContent="\u{1F4CE}",ge.addEventListener("click",$n=>{$n.preventDefault(),Ke==null||Ke.click()}),dt.appendChild(ge);let Cn=(Kd=Q.buttonTooltipText)!=null?Kd:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=Cn,dt.appendChild(Yt),nt.append(dt),!vt&&Ke&&It&&(vt=qo.fromConfig(Q),vt.setPreviewsContainer(It),Ke.addEventListener("change",async()=>{vt&&(Ke!=null&&Ke.files)&&(await vt.handleFileSelect(Ke.files),Ke.value="")})),ne.querySelector(".persona-attachment-drop-overlay")||ne.appendChild(Du(Q.dropOverlay))}else{dt.style.display="";let Q=(Jd=r.attachments)!=null?Jd:{};Ke&&(Ke.accept=((Gd=Q.allowedTypes)!=null?Gd:Rr).join(","),Ke.multiple=((Xd=Q.maxFiles)!=null?Xd:4)>1),vt&&vt.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else dt&&(dt.style.display="none"),vt&&vt.clearAttachments(),(Yd=ne.querySelector(".persona-attachment-drop-overlay"))==null||Yd.remove();let Ut=(Qd=r.sendButton)!=null?Qd:{},bo=(Zd=Ut.useIcon)!=null?Zd:!1,Xr=(ep=Ut.iconText)!=null?ep:"\u2191",ht=Ut.iconName,Tn=(tp=Ut.tooltipText)!=null?tp:"Send message",Ir=(np=Ut.showTooltip)!=null?np:!1,wn=(rp=Ut.size)!=null?rp:"40px",Mn=Ut.backgroundColor,Bt=Ut.textColor;if(bo){if(re.style.width=wn,re.style.height=wn,re.style.minWidth=wn,re.style.minHeight=wn,re.style.fontSize="18px",re.style.lineHeight="1",re.innerHTML="",Bt?re.style.color=Bt:re.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let Q=parseFloat(wn)||24,xt=(Bt==null?void 0:Bt.trim())||"currentColor",Ot=fe(ht,Q,xt,2);Ot?re.appendChild(Ot):re.textContent=Xr}else re.textContent=Xr;re.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Mn?(re.style.backgroundColor=Mn,re.classList.remove("persona-bg-persona-primary")):(re.style.backgroundColor="",re.classList.add("persona-bg-persona-primary"))}else re.textContent=(sp=(op=r.copy)==null?void 0:op.sendButtonLabel)!=null?sp:"Send",re.style.width="",re.style.height="",re.style.minWidth="",re.style.minHeight="",re.style.fontSize="",re.style.lineHeight="",re.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",Mn?(re.style.backgroundColor=Mn,re.classList.remove("persona-bg-persona-accent")):re.classList.add("persona-bg-persona-accent"),Bt?re.style.color=Bt:re.classList.add("persona-text-white");Ut.borderWidth?(re.style.borderWidth=Ut.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),Ut.borderColor?re.style.borderColor=Ut.borderColor:re.style.borderColor="",Ut.paddingX?(re.style.paddingLeft=Ut.paddingX,re.style.paddingRight=Ut.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),Ut.paddingY?(re.style.paddingTop=Ut.paddingY,re.style.paddingBottom=Ut.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let $t=sn==null?void 0:sn.querySelector(".persona-send-button-tooltip");if(Ir&&Tn)if($t)$t.textContent=Tn,$t.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Tn,sn==null||sn.insertBefore(Q,re)}else $t&&($t.style.display="none");let Dt=(dp=(ap=r.layout)==null?void 0:ap.contentMaxWidth)!=null?dp:F()?(cp=(lp=(ip=r.launcher)==null?void 0:ip.composerBar)==null?void 0:lp.contentMaxWidth)!=null?cp:"720px":void 0;Dt?(ve.style.maxWidth=Dt,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Ht&&(Ht.style.maxWidth=Dt,Ht.style.marginLeft="auto",Ht.style.marginRight="auto")):(ve.style.maxWidth="",ve.style.marginLeft="",ve.style.marginRight="",ve.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""));let qt=(pp=r.statusIndicator)!=null?pp:{},kn=(up=qt.visible)!=null?up:!0;if(zt.style.display=kn?"":"none",_){let Q=_.getStatus();Oe(zt,(Ot=>{var lt,St,nn,un;return Ot==="idle"?(lt=qt.idleText)!=null?lt:mn.idle:Ot==="connecting"?(St=qt.connectingText)!=null?St:mn.connecting:Ot==="connected"?(nn=qt.connectedText)!=null?nn:mn.connected:Ot==="error"?(un=qt.errorText)!=null?un:mn.error:mn[Ot]})(Q),qt,Q)}zt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Fn=qt.align==="left"?"persona-text-left":qt.align==="center"?"persona-text-center":"persona-text-right";zt.classList.add(Fn)},open(){$()&&Rt(!0,"api")},close(){$()&&Rt(!1,"api")},toggle(){$()&&Rt(!W,"api")},clearChat(){fn=!1,_.clearMessages(),Nn.clear(),jr();try{localStorage.removeItem(es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},S.syncFromMetadata(),G==null||G.clear(),ae==null||ae.update()},setMessage(c){return!ie||_.isStreaming()?!1:(!W&&$()&&Rt(!0,"system"),ie.value=c,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ie.value.trim();return g?(!W&&$()&&Rt(!0,"system"),ie.value="",ie.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return _.isStreaming()?!1:((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(_.isVoiceActive()||(!W&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,En(),_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),Vn("user"),_.isVoiceActive()&&j()})),!0):On?!0:ys()?(!W&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,En(),go("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,En(),Vn("user"),X()}),!0):!1:On?(mt.manuallyDeactivated=!0,En(),sr("user"),!0):!1},injectMessage(c){return!W&&$()&&Rt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!W&&$()&&Rt(!0,"system");let g=_.injectAssistantMessage(c);return O&&(O=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(c){return!W&&$()&&Rt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!W&&$()&&Rt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!W&&$()&&Rt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!W&&$()&&Rt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!W&&$()&&Rt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,g){return _.connectStream(c,g)},__pushEventStreamEvent(c){G&&G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!pe||!G||Cr()},hideEventStream(){He&&Qn()},isEventStreamVisible(){return He},showArtifacts(){Yn(r)&&(fn=!1,Hn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){Yn(r)&&(fn=!0,Hn())},upsertArtifact(c){return Yn(r)?(fn=!1,_.upsertArtifact(c)):null},selectArtifact(c){Yn(r)&&_.selectArtifact(c)},clearArtifacts(){Yn(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return A&&!W&&!F()||!ie?!1:(ie.focus(),!0)},async resolveApproval(c,g){let b=_.getMessages().find(T=>{var D;return T.variant==="approval"&&((D=T.approval)==null?void 0:D.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){_.resolveWebMcpApproval(b.id,g);return}return _.resolveApproval(b.approval,g)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return $()&&W},isVoiceActive(){return mt.active},getState(){return{open:$()&&W,launcherEnabled:A,voiceActive:mt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!W&&$()&&Rt(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let y=rl({onSubmit:async(b,T)=>{var D;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});ve.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!W&&$()&&Rt(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let y=ol({onSubmit:async(b,T)=>{var D;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});ve.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return _.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return _.submitNPSFeedback(c,g)},destroy(){hr!=null&&(clearInterval(hr),hr=null),ft.forEach(c=>c()),J.remove(),we==null||we.remove(),Me==null||Me.destroy(),Ge==null||Ge.remove(),Dn&&Ue.removeEventListener("click",Dn)}};if((((pc=t==null?void 0:t.debugTools)!=null?pc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Qt,getMessages:Qt.getMessages,getStatus:Qt.getStatus,getMetadata:Qt.getPersistentMetadata,updateMetadata:Qt.updatePersistentMetadata,clearHistory:()=>Qt.clearChat(),setVoiceActive:y=>y?Qt.startVoiceRecognition():Qt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ft.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.focusInput()};if(window.addEventListener("persona:focusInput",g),ft.push(()=>{window.removeEventListener("persona:focusInput",g)}),pe){let q=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Qt.showEventStream()},I=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Qt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",I),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",I)})}let y=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.showArtifacts()},b=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.hideArtifacts()},T=q=>{let I=q.detail;I!=null&&I.instanceId&&I.instanceId!==c||I!=null&&I.artifact&&Qt.upsertArtifact(I.artifact)},D=q=>{let I=q.detail;I!=null&&I.instanceId&&I.instanceId!==c||typeof(I==null?void 0:I.id)=="string"&&Qt.selectArtifact(I.id)},N=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",N),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",N)})}let Jn=tb(r.persistState);if(Jn&&$()){let c=nb(Jn.storage),g=`${Jn.keyPrefix}widget-open`,y=`${Jn.keyPrefix}widget-voice`,b=`${Jn.keyPrefix}widget-voice-mode`;if(c){let T=((uc=Jn.persist)==null?void 0:uc.openState)&&c.getItem(g)==="true",D=((mc=Jn.persist)==null?void 0:mc.voiceState)&&c.getItem(y)==="true",N=((gc=Jn.persist)==null?void 0:gc.voiceState)&&c.getItem(b)==="true";if(T&&setTimeout(()=>{Qt.open(),setTimeout(()=>{var q;if(D||N)Qt.startVoiceRecognition();else if((q=Jn.persist)!=null&&q.focusInput){let I=e.querySelector("textarea");I&&I.focus()}},100)},0),(fc=Jn.persist)!=null&&fc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(hc=Jn.persist)!=null&&hc.voiceState&&(o.on("voice:state",q=>{c.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{c.setItem(b,q.viaVoice?"true":"false")})),Jn.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(b)},I=()=>q();window.addEventListener("persona:clear-chat",I),ft.push(()=>{window.removeEventListener("persona:clear-chat",I)})}}}return u&&$()&&setTimeout(()=>{Qt.open()},0),Lr(),Qt};var rb=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},Nu=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},dl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Ou=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",dl(e)},il=e=>{e.style.transition=""},ll=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},cl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ii=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},ob=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},sb=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Fu=(e,n,t,r,s,o,a)=>{var v,x,S,A,k,R;let i=lr(o),d=i.reveal==="push";ob(e,n,t,r,d),sb(e,n,t,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,p=(A=(S=o==null?void 0:o.launcher)==null?void 0:S.mobileBreakpoint)!=null?A:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ll(n),il(r),Ou(r),cl(t),ii(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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((R=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?R:gn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ou(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ll(n),il(r),cl(t),ii(s,r);let H=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":L;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=H,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",il(r),dl(r),ii(s,r);let H=rb(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",B=i.side==="right"?a?`translateX(-${H}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${H}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${L+H}px`,n.style.transition=w,n.style.transform=B,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ll(n),dl(r),cl(t),ii(s,r);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",B=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",r.style.position="relative",r.style.overflow=H||B?"hidden":"visible",r.style.transition=w,H&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},ab=(e,n)=>{let t=e.ownerDocument.createElement("div");return Nu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Nu(t,r)},destroy(){t.remove()}}},ib=(e,n)=>{var k,R,H,L;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(R=(k=n==null?void 0:n.launcher)==null?void 0:k.enabled)==null||R?(L=(H=n==null?void 0:n.launcher)==null?void 0:H.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),r.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),lr(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Fu(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{Fu(a,i,d,l,u,n,p),v()},S=a.ownerDocument.defaultView,A=()=>{x()};return S==null||S.addEventListener("resize",A),lr(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(w){let B=w.launcherEnabled?w.open:!0;p!==B&&(p=B,x())},updateConfig(w){var B,F;n=w,((F=(B=n==null?void 0:n.launcher)==null?void 0:B.enabled)!=null?F:!0)===!1&&(p=!0),x()},destroy(){S==null||S.removeEventListener("resize",A),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},li=(e,n)=>on(n)?ib(e,n):ab(e,n);var pl={},lb=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},cb=()=>{try{if(typeof pl!="undefined"&&pl.url)return new URL("../widget.css",pl.url).href}catch{}return null},$u=(e,n)=>{let t=cb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},_u=e=>{var S;let n=lb(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=li(n,s),a,i=[],d=(A,k)=>{var w,B;let H=!((B=(w=k==null?void 0:k.launcher)==null?void 0:w.enabled)!=null?B:!0)||on(k),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),H&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let F=A.attachShadow({mode:"open"});F.appendChild(L),$u(F,r)}else A.appendChild(L),$u(A,r);return n.id&&L.setAttribute("data-persona-instance",n.id),L},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let A=d(o.host,s);a=al(A,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(A=>A()),i=[],a.destroy()};p(),(S=e.onReady)==null||S.call(e);let m=A=>{f(),o.destroy(),o=li(n,A),s=A,p()},v={update(A){var B,F,$,W,O,V;let k={...s,...A,launcher:{...(B=s==null?void 0:s.launcher)!=null?B:{},...(F=A==null?void 0:A.launcher)!=null?F:{},dock:{...(W=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?W:{},...(V=(O=A==null?void 0:A.launcher)==null?void 0:O.dock)!=null?V:{}}}},R=on(s),H=on(k),L=Zr(s),w=Zr(k);if(R!==H||L!==w){m(k);return}s=k,o.updateConfig(s),a.update(A),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(A,k,R){if(k==="host")return o.host;if(k in A)return Reflect.get(A,k,R);let H=a[k];return typeof H=="function"?H.bind(a):H}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Vu=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),db=new Set(["button","a","input","select","textarea","details","summary"]),pb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ul=/\b(product|card|item|listing|result)\b/i,gl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ub=3e3,mb=100;function Ku(e){let n=typeof e.className=="string"?e.className:"";if(ul.test(n)||e.id&&ul.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&ul.test(r.value))return!0}return!1}function Ju(e){var n;return gl.test(((n=e.textContent)!=null?n:"").trim())}function Gu(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function gb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ju(e){let n=e.match(gl);return n?n[0]:null}function Uu(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function fb(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var hb="commerce-card",yb="result-card";function qu(e){return!Ku(e)||!Ju(e)||!Gu(e)&&!gb(e)?0:5200}function zu(e){var r;return!Ku(e)||Ju(e)||!Gu(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Xu=[{id:hb,scoreElement(e){return qu(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||gl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(qu(e)===0)return null;let{title:t,href:r}=Uu(e),s=(u=(l=ju(((d=e.textContent)!=null?d:"").trim()))!=null?l:ju(n.text))!=null?u:"",o=fb(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
- `)}},{id:yb,scoreElement(e){return zu(e)},formatSummary(e,n){if(zu(e)===0)return null;let{title:t,href:r}=Uu(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
109
- `)}}];function bb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function xb(e){var u,p,f,m,v,x,S,A,k,R,H,L,w;let n=(u=e.options)!=null?u:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(v=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(S=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?S:200,o=(k=(A=n.visibleOnly)!=null?A:e.visibleOnly)!=null?k:!0,a=(R=n.root)!=null?R:e.root,i=(H=n.mode)!=null?H:"structured",d=(L=n.maxCandidates)!=null?L:Math.max(500,t*10),l=(w=e.rules)!=null?w:Xu;return i==="simple"&&e.rules&&e.rules.length>0?(bb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function ml(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var vb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function wb(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||db.has(n)||t&&pb.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Yu(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Cb(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(n[u.name]=u.value)}return n}function Qu(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${ml(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of vb){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${ml(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>ml(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function Ab(e){return e==="static"?mb:ub}function Zu(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:Qu(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:wb(e),attributes:Cb(e)}}function Sb(e,n,t,r){let s=Ab(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Eb(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function Tb(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Vu.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Yu(l)){i=a.nextNode();continue}let p=Zu(l,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(S=>S==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:v,formattingRule:x}=Sb(l,p,e.rules,t);s.push({el:l,domIndex:o,enriched:p,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;Eb(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,t);m&&(u=m)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function Mb(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(Vu.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Yu(d)){o=s.nextNode();continue}let u=Zu(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function kb(e={}){var r;let n=xb(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?Mb(n,t):Tb(n,t):[]}var ci=100;function Lb(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
107
+ `}if(!b&&!c){let Bt="max-height: -moz-available !important; max-height: stretch !important;",Vt=g?"":"padding-top: 1.25em !important;",Wn=g?"":`z-index: ${($t=(Ht=r.launcher)==null?void 0:Ht.zIndex)!=null?$t:hn} !important;`;ie.style.cssText+=Bt+Vt+Wn}T()};lr(),Eo(e,r),si(e,r),ai(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",$r)});let Jt=null,Gt=null;ft.push(()=>{Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null}),On&&ft.push(()=>{On==null||On.disconnect(),On=null}),ft.push(()=>{vn==null||vn(),vn=null,kr(),Wt&&(Wt.remove(),Wt=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),ce&&ft.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),fe==null||fe.destroy(),fe=null,V==null||V.destroy(),V=null,ne=null});let Un=null,qr=()=>{Un&&(Un(),Un=null),r.colorScheme==="auto"&&(Un=Wi(()=>{Eo(e,r)}))};qr(),ft.push(()=>{Un&&(Un(),Un=null)});let tr=(dc=r.features)==null?void 0:dc.streamAnimation;if(tr!=null&&tr.type&&tr.type!=="none"){let c=Fs(tr.type,tr.plugins);c&&(Bi(c,e),ft.push(()=>Zp(e)))}let cr=Tu(Ct),qn=null,S,zn=!1,dr=Kp(),Lr=new Map,wr=new Map,ss=0,pr=Oa(),ur=0,mr=null,Pr=!1,po=!1,Ys=4,as=24,Zs=80,Io=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=(uc=(pc=r.voiceRecognition)==null?void 0:pc.autoResume)!=null?uc:!1,nr=c=>{o.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},Ln=()=>{m(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},ea=()=>{var b,k;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=dl(d.voiceState),g=!!c.active,y=Number((k=c.timestamp)!=null?k:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<xb&&setTimeout(()=>{var D,O;mt.active||(mt.manuallyDeactivated=!1,((O=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:O.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("restore"),S.isVoiceActive()&&M()}):fo("restore"))},1e3)},ta=()=>S?Uu(S.getMessages()).filter(c=>!c.__skipPersist):[];function Wo(c){if(!(i!=null&&i.save))return;let y={messages:c?Uu(c):S?ta():[],metadata:d,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Ir=null,na=()=>ie.querySelector("#persona-scroll-container")||X,uo=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),Pr=!1},ls=()=>{mr!==null&&(cancelAnimationFrame(mr),mr=null),po=!1,uo()},Wr=()=>{if(!yn()||me){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==de&&de.appendChild(Tt),bt();let c=Bs(X)>0;Tt.style.display=pr.isFollowing()||!c?"none":""},cs=()=>{pr.pause()&&(ls(),Wr())},zr=()=>{pr.resume(),Wr()},Vr=(c=!1)=>{pr.isFollowing()&&(!c&&!zn||(mr!==null&&(cancelAnimationFrame(mr),mr=null),po=!0,mr=requestAnimationFrame(()=>{mr=null,po=!1,pr.isFollowing()&&ra(na(),c?220:140)})))},ra=(c,g=500)=>{let y=c.scrollTop,b=Bs(c),k=b-y;if(Math.abs(k)<1){ur=c.scrollTop;return}if(Math.abs(k)>=Zs){uo(),Pr=!0,c.scrollTop=b,ur=c.scrollTop,Pr=!1;return}uo();let D=performance.now();Pr=!0;let O=R=>1-Math.pow(1-R,3),U=R=>{if(!pr.isFollowing()){uo();return}let we=Bs(c);we!==b&&(b=we,k=b-y);let le=R-D,ee=Math.min(le/g,1),he=O(ee),Ae=y+k*he;c.scrollTop=Ae,ur=c.scrollTop,ee<1?Ir=requestAnimationFrame(U):(c.scrollTop=b,ur=c.scrollTop,Ir=null,Pr=!1)};Ir=requestAnimationFrame(U)},oa=c=>{let g=new Map;c.forEach(y=>{let b=Io.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Io.clear(),g.forEach((y,b)=>{Io.set(b,y)})},mo=(c,g,y)=>{var Je,it,lt,Te,Ee,je;let b=document.createElement("div"),D=(()=>{var Se;let T=s.find(Pe=>Pe.renderLoadingIndicator);if(T!=null&&T.renderLoadingIndicator)return T.renderLoadingIndicator;if((Se=r.loadingIndicator)!=null&&Se.render)return r.loadingIndicator.render})(),O=(T,Se)=>Se==null?!1:typeof Se=="string"?(T.textContent=Se,!0):(T.appendChild(Se),!0),U=new Set,R=new Set,we=s.some(T=>T.renderAskUserQuestion),le=[],ee=[],he=r.enableComponentStreaming!==!1;if(g.forEach(T=>{var Cn,pn,Ze,ct,An,mn,ho,yo,bo,Fo,_o,zt,xo,Yr;U.add(T.id);let Se=we&&ro(T),Pe=!Se&&T.role==="assistant"&&!T.variant&&he&&al(T);if(!Pe&&wr.has(T.id)){let yt=c.querySelector(`#wrapper-${T.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),wr.delete(T.id)}let ze=ro(T)?`:${(Cn=T.agentMetadata)!=null&&Cn.askUserQuestionAnswered?"a":"u"}:${(pn=T.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(T.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Vp(T,ss)+ze,Lt=Se||Pe?null:Jp(dr,T.id,xe);if(Lt){b.appendChild(Lt.cloneNode(!0)),ro(T)&&((Ze=T.toolCall)!=null&&Ze.id)&&((ct=T.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((An=T.agentMetadata)!=null&&An.askUserQuestionAnswered)&&(R.add(T.toolCall.id),Js(T,r,Ce.composerOverlay));return}let st=null,Qt=s.find(yt=>!!(T.variant==="reasoning"&&yt.renderReasoning||T.variant==="tool"&&yt.renderToolCall||T.variant==="approval"&&yt.renderApproval||!T.variant&&yt.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if(ro(T)&&((ho=T.agentMetadata)==null?void 0:ho.askUserQuestionAnswered)===!0){Lr.delete(T.id);let yt=c.querySelector(`#wrapper-${T.id}`);yt==null||yt.removeAttribute("data-preserve-runtime");return}if(ro(T)&&((bo=(yo=r.features)==null?void 0:yo.askUserQuestion)==null?void 0:bo.enabled)!==!1){let yt=s.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(yt&&Pt.current){let Pn=Lr.get(T.id),Br=Pn!==xe,Sn=null;if(Br){let{payload:$t,complete:Bt}=oo(T),Vt=T.id,Wn=()=>{var Kn;return(Kn=Pt.current)==null?void 0:Kn.getMessages().find(nn=>nn.id===Vt)};Sn=yt.renderAskUserQuestion({message:T,payload:$t,complete:Bt,resolve:Kn=>{var Ar;let nn=Wn();nn&&((Ar=Pt.current)==null||Ar.resolveAskUserQuestion(nn,Kn))},dismiss:()=>{var nn,Ar,Dr;let Kn=Wn();(nn=Kn==null?void 0:Kn.agentMetadata)!=null&&nn.awaitingLocalTool&&((Ar=Pt.current)==null||Ar.markAskUserQuestionResolved(Kn),(Dr=Pt.current)==null||Dr.resolveAskUserQuestion(Kn,"(dismissed)"))},config:r})}let In=Pn!=null;if(Br&&Sn===null&&!In){((Fo=T.agentMetadata)==null?void 0:Fo.awaitingLocalTool)===!0&&!((_o=T.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(R.add(T.toolCall.id),Js(T,r,Ce.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${T.id}`,Ht.setAttribute("data-wrapper-id",T.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),b.appendChild(Ht),le.push({messageId:T.id,fingerprint:xe,bubble:Sn});return}else{((zt=T.agentMetadata)==null?void 0:zt.awaitingLocalTool)===!0&&!((xo=T.agentMetadata)!=null&&xo.askUserQuestionAnswered)&&(R.add(T.toolCall.id),Js(T,r,Ce.composerOverlay));return}}else if(Qt)if(T.variant==="reasoning"&&T.reasoning&&Qt.renderReasoning){if(!Re)return;st=Qt.renderReasoning({message:T,defaultRenderer:()=>ji(T,r),config:r})}else if(T.variant==="tool"&&T.toolCall&&Qt.renderToolCall){if(!Ne)return;st=Qt.renderToolCall({message:T,defaultRenderer:()=>Ui(T,r),config:r})}else if(T.variant==="approval"&&T.approval&&Qt.renderApproval){if(r.approval===!1)return;st=Qt.renderApproval({message:T,defaultRenderer:()=>Xi(T,r),config:r})}else Qt.renderMessage&&(st=Qt.renderMessage({message:T,defaultRenderer:()=>{let yt=Vs(T,y,dn,r.messageActions,z,{loadingIndicatorRenderer:D,widgetConfig:r});return T.role!=="user"&&el(yt,T,r,S),yt},config:r}));if(!st&&Pe){let yt=il(T);if(yt){let Pn=wr.get(T.id),Br=Pn!==xe,Sn=r.wrapComponentDirectiveInBubble!==!1,In=null;if(Br){let Ht=sl(yt,{config:r,message:T,transform:y});if(Ht)if(Sn){let $t=document.createElement("div");if($t.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$t.id=`bubble-${T.id}`,$t.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let Bt=document.createElement("div");Bt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Bt.innerHTML=y({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),$t.appendChild(Bt)}$t.appendChild(Ht),In=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${T.id}`,$t.setAttribute("data-message-id",T.id),$t.setAttribute("data-persona-component-directive","true"),T.content&&T.content.trim()){let Bt=document.createElement("div");Bt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Bt.innerHTML=y({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),$t.appendChild(Bt)}$t.appendChild(Ht),In=$t}}if(In||Pn!=null){let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${T.id}`,Ht.setAttribute("data-wrapper-id",T.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),Sn||Ht.classList.add("persona-w-full"),b.appendChild(Ht),ee.push({messageId:T.id,fingerprint:xe,bubble:In});return}}}if(!st)if(T.variant==="reasoning"&&T.reasoning){if(!Re)return;st=ji(T,r)}else if(T.variant==="tool"&&T.toolCall){if(!Ne)return;st=Ui(T,r)}else if(T.variant==="approval"&&T.approval){if(r.approval===!1)return;st=Xi(T,r)}else{let yt=(Yr=r.layout)==null?void 0:Yr.messages;yt!=null&&yt.renderUserMessage&&T.role==="user"?st=yt.renderUserMessage({message:T,config:r,streaming:!!T.streaming}):yt!=null&&yt.renderAssistantMessage&&T.role==="assistant"?st=yt.renderAssistantMessage({message:T,config:r,streaming:!!T.streaming}):st=Vs(T,y,yt,r.messageActions,z,{loadingIndicatorRenderer:D,widgetConfig:r}),T.role!=="user"&&st&&el(st,T,r,S)}let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-${T.id}`,It.setAttribute("data-wrapper-id",T.id),T.role==="user"&&It.classList.add("persona-justify-end"),(st==null?void 0:st.getAttribute("data-persona-component-directive"))==="true"&&It.classList.add("persona-w-full"),It.appendChild(st),Gp(dr,T.id,xe,It),b.appendChild(It)}),Ce.composerOverlay&&Ce.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Se=>{let Pe=Se.getAttribute("data-persona-ask-sheet-for");Pe&&!R.has(Pe)&&ko(Ce.composerOverlay,Pe)}),(it=(Je=r.features)==null?void 0:Je.toolCallDisplay)!=null&&it.grouped){let T=[],Se=[];g.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ne){Se.push(Pe);return}Se.length>1&&T.push(Se),Se=[]}),Se.length>1&&T.push(Se),T.forEach((Pe,ze)=>{var pn,Ze;let xe=Pe.map(ct=>Array.from(b.children).find(An=>An instanceof HTMLElement&&An.getAttribute("data-wrapper-id")===ct.id)).filter(ct=>!!ct);if(xe.length<2)return;let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-tool-group-${ze}-${Pe[0].id}`,Lt.setAttribute("data-wrapper-id",`tool-group-${ze}-${Pe[0].id}`);let st=document.createElement("div");st.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",st.setAttribute("data-persona-tool-group","true");let Qt=document.createElement("div");Qt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let dn=`Called ${Pe.length} tools`,It=(Ze=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:Ze.call(pn,{messages:Pe,toolCalls:Pe.map(ct=>ct.toolCall).filter(ct=>!!ct),defaultSummary:dn,config:r});O(Qt,It)||(Qt.textContent=dn);let Cn=document.createElement("div");Cn.className="persona-tool-group-stack persona-flex persona-flex-col",st.append(Qt,Cn),Lt.appendChild(st),xe[0].before(Lt),xe.forEach((ct,An)=>{let mn=document.createElement("div");mn.className="persona-tool-group-item persona-relative",mn.setAttribute("data-persona-tool-group-item","true"),An<xe.length-1&&mn.setAttribute("data-persona-tool-group-connector","true"),mn.appendChild(ct),Cn.appendChild(mn)})})}Xp(dr,U);let Ae=g.some(T=>T.role==="assistant"&&T.streaming),He=g[g.length-1],tt=(He==null?void 0:He.role)==="assistant"&&!He.streaming&&He.variant!=="approval";if(zn&&g.some(T=>T.role==="user")&&!Ae&&!tt){let T={config:r,streaming:!0,location:"standalone",defaultRenderer:Xo},Se=s.find(ze=>ze.renderLoadingIndicator),Pe=null;if(Se!=null&&Se.renderLoadingIndicator&&(Pe=Se.renderLoadingIndicator(T)),Pe===null&&((lt=r.loadingIndicator)!=null&&lt.render)&&(Pe=r.loadingIndicator.render(T)),Pe===null&&(Pe=Xo()),Pe){let ze=document.createElement("div"),xe=((Te=r.loadingIndicator)==null?void 0:Te.showBubble)!==!1;ze.className=xe?["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(" "),ze.setAttribute("data-typing-indicator","true"),ze.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ze.appendChild(Pe);let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id="wrapper-typing-indicator",Lt.setAttribute("data-wrapper-id","typing-indicator"),Lt.appendChild(ze),b.appendChild(Lt)}}if(!zn&&g.length>0){let T=g[g.length-1],Se={config:r,lastMessage:T,messageCount:g.length},Pe=s.find(xe=>xe.renderIdleIndicator),ze=null;if(Pe!=null&&Pe.renderIdleIndicator&&(ze=Pe.renderIdleIndicator(Se)),ze===null&&((Ee=r.loadingIndicator)!=null&&Ee.renderIdle)&&(ze=r.loadingIndicator.renderIdle(Se)),ze){let xe=document.createElement("div"),Lt=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;xe.className=Lt?["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(" "),xe.setAttribute("data-idle-indicator","true"),xe.appendChild(ze);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-idle-indicator",st.setAttribute("data-wrapper-id","idle-indicator"),st.appendChild(xe),b.appendChild(st)}}if(Da(c,b),le.length>0)for(let{messageId:T,fingerprint:Se,bubble:Pe}of le){let ze=c.querySelector(`#wrapper-${T}`);ze&&Pe!==null&&(ze.replaceChildren(Pe),ze.setAttribute("data-bubble-fp",Se),Lr.set(T,Se))}if(Lr.size>0)for(let T of Lr.keys())U.has(T)||Lr.delete(T);if(ee.length>0)for(let{messageId:T,fingerprint:Se,bubble:Pe}of ee){let ze=c.querySelector(`#wrapper-${T}`);ze&&Pe!==null&&(ze.replaceChildren(Pe),ze.setAttribute("data-bubble-fp",Se),wr.set(T,Se))}if(wr.size>0)for(let T of wr.keys())U.has(T)||wr.delete(T)},Kr=null,sa=()=>{var y;if(Kr)return;let c=b=>{let k=b.composedPath();k.includes(ie)||Qe&&k.includes(Qe)||Rt(!1,"user")};Kr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},ds=()=>{var g;if(!Kr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",Kr,!0),Kr=null};ft.push(()=>ds());let Jr=null,aa=()=>{var y;if(Jr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Rt(!1,"user"))};Jr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},ps=()=>{var g;if(!Jr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",Jr,!0),Jr=null};ft.push(()=>ps());let Gr=!1,us=new Set,ia=()=>{var g,y,b,k;let c=(b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((k=r.features)==null?void 0:k.streamAnimation)},Rr=()=>{var it,lt,Te,Ee;if(!F())return;let c=Ce.peekBanner,g=Ce.peekTextNode;if(!c||!g)return;if(B){c.classList.remove("persona-pill-peek--visible");return}let y=(it=S==null?void 0:S.getMessages())!=null?it:[],b;for(let je=y.length-1;je>=0;je--){let T=y[je];if(T.role==="assistant"&&T.content){b=T;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let k=b.content,D=!!b.streaming,O=ia(),U=$a(O),R=U.type!=="none"?Fs(U.type,O==null?void 0:O.plugins):null,we=((lt=R==null?void 0:R.isAnimating)==null?void 0:lt.call(R,b))===!0,le=R!==null&&(D||we);le&&R&&!us.has(R.name)&&(Bi(R,e),us.add(R.name));let ee=le&&(R!=null&&R.containerClass)?R.containerClass:null,he=(Te=g.dataset.personaPeekStreamClass)!=null?Te:null;he&&he!==ee&&(g.classList.remove(he),delete g.dataset.personaPeekStreamClass),ee&&he!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),le?(g.style.setProperty("--persona-stream-step",`${U.speed}ms`),g.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ae=le?ja(k,U.buffer,R,b,D):k;if(le&&U.placeholder==="skeleton"&&D&&(!Ae||!Ae.trim())){let je=document.createElement("div"),T=$s();T.classList.add("persona-pill-peek__skeleton"),je.appendChild(T),Da(g,je)}else{let je=Math.max(0,Ae.length-100),T=Ae.length>100?Ae.slice(-100):Ae,Se=jo(T);if(!le||!R){let Pe=Ae.length>100?`\u2026${T}`:T;g.textContent!==Pe&&(g.textContent=Pe)}else{let Pe=Se;(R.wrap==="char"||R.wrap==="word")&&(Pe=_s(Se,R.wrap,`peek-${b.id}`,{skipTags:R.skipTags,startIndex:je}));let ze=document.createElement("div");if(ze.innerHTML=Pe,R.useCaret&&T.length>0){let xe=Ua(),Lt=ze.querySelectorAll(".persona-stream-char, .persona-stream-word"),st=Lt[Lt.length-1];st!=null&&st.parentNode?st.parentNode.insertBefore(xe,st.nextSibling):ze.appendChild(xe)}Da(g,ze),(Ee=R.onAfterRender)==null||Ee.call(R,{container:g,bubble:c,messageId:b.id,message:b,speed:U.speed,duration:U.duration})}}let Je=zn||Gr;c.classList.toggle("persona-pill-peek--visible",Je)};if(F()){let c=Ce.peekBanner;if(c){let b=k=>{k.preventDefault(),k.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let g=()=>{Gr||(Gr=!0,Rr())},y=()=>{Gr&&(Gr=!1,Rr())};ae.addEventListener("pointerenter",g),ae.addEventListener("pointerleave",y),ft.push(()=>{ae.removeEventListener("pointerenter",g),ae.removeEventListener("pointerleave",y)}),Qe&&(Qe.addEventListener("pointerenter",g),Qe.addEventListener("pointerleave",y),ft.push(()=>{Qe.removeEventListener("pointerenter",g),Qe.removeEventListener("pointerleave",y)}))}let la=c=>{var he,Ae,He,tt,Je,it,lt,Te;let g=(Ae=(he=r.launcher)==null?void 0:he.composerBar)!=null?Ae:{},y=(He=g.expandedSize)!=null?He:"anchored",b=(tt=g.bottomOffset)!=null?tt:"16px",k=g.collapsedMaxWidth,D=(Je=g.expandedMaxWidth)!=null?Je:"880px",O=(it=g.expandedTopOffset)!=null?it:"5vh",U=(lt=g.modalMaxWidth)!=null?lt:"880px",R=(Te=g.modalMaxHeight)!=null?Te:"min(90vh, 800px)",we="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",ee=ie.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Qe){let Ee=Qe.style;Ee.bottom=b,Ee.width=k!=null?k:""}if(c&&y!=="fullscreen"){if(y==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=U,ee.maxWidth=we,ee.maxHeight=R,ee.height=R;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${b} + ${le})`,ee.top=O,ee.width=D,ee.maxWidth=we}},Xr=()=>{var R,we,le,ee,he,Ae,He,tt;if(!_())return;if(F()){let it=(le=((we=(R=r.launcher)==null?void 0:R.composerBar)!=null?we:{}).expandedSize)!=null?le:"anchored",lt=B?"expanded":"collapsed";ie.dataset.state=lt,ie.dataset.expandedSize=it,Qe&&(Qe.dataset.state=lt,Qe.dataset.expandedSize=it),ie.style.removeProperty("display"),ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),la(B),de.style.display=B?"flex":"none",lr(),B?(sa(),aa()):(ds(),ps()),Rr();return}let c=an(r),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,y=(Ae=(he=r.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ae:640,b=(tt=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?tt:!0,k=g.innerWidth<=y,D=b&&k&&A,O=yr(r).reveal;B?(ie.style.removeProperty("display"),ie.style.display=c?"flex":"",ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-95","persona-opacity-0"),ae.classList.add("persona-scale-100","persona-opacity-100"),Ke?Ke.element.style.display="none":Ye&&(Ye.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!D?(ie.style.removeProperty("display"),ie.style.display="flex",ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ie.style.setProperty("display","none","important"),ie.classList.remove("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ie.style.display="",ie.classList.add("persona-pointer-events-none","persona-opacity-0"),ae.classList.remove("persona-scale-100","persona-opacity-100"),ae.classList.add("persona-scale-95","persona-opacity-0")),Ke?Ke.element.style.display=c?"none":"":Ye&&(Ye.style.display=c?"none":""))},Rt=(c,g="user")=>{var D,O;if(!_()||B===c)return;let y=B;B=c,Xr();let b=(()=>{var He,tt,Je,it,lt,Te,Ee,je,T,Se;let U=(tt=(He=r.launcher)==null?void 0:He.sidebarMode)!=null?tt:!1,R=(Je=e.ownerDocument.defaultView)!=null?Je:window,we=(lt=(it=r.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,le=(Ee=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?Ee:640,ee=R.innerWidth<=le,he=an(r)&&we&&ee,Ae=F()&&((Se=(T=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:T.expandedSize)!=null?Se:"fullscreen")==="fullscreen";return U||we&&ee&&A||he||Ae})();if(B&&b){if(!Jt){let U=e.getRootNode(),R=U instanceof ShadowRoot?U.host:e.closest(".persona-host");R&&(Jt=Di(R,(O=(D=r.launcher)==null?void 0:D.zIndex)!=null?O:hn))}Gt||(Gt=Ni(e.ownerDocument))}else B||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null);B&&(Xt(),Vr(!0));let k={open:B,source:g,timestamp:Date.now()};B&&!y?o.emit("widget:opened",k):!B&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:B,launcherEnabled:A,voiceActive:mt.active,streaming:S.isStreaming()})},Ro=c=>{Kt(c?"stop":"send"),K&&(K.disabled=c),cr.buttons.forEach(g=>{g.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Ho=()=>{mt.active||G&&G.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Ho(),200)});let ms=()=>{var y,b,k,D,O,U,R,we,le,ee,he;Hn.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",Xn.textContent=(D=(k=r.copy)==null?void 0:k.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",G.placeholder=(U=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?U:"How can I help...";let c=X.querySelector("[data-persona-intro-card]");if(c){let Ae=((R=r.copy)==null?void 0:R.showWelcomeCard)!==!1;c.style.display=Ae?"":"none",Ae?(X.classList.remove("persona-gap-3"),X.classList.add("persona-gap-6")):(X.classList.remove("persona-gap-6"),X.classList.add("persona-gap-3"))}!((le=(we=r.sendButton)==null?void 0:we.useIcon)!=null&&le)&&!(S!=null&&S.isStreaming())&&(Oe.textContent=(he=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?he:"Send"),G.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',G.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let Cr=null,ca=()=>{Cr==null&&(Cr=setInterval(()=>{let c=$e.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Cr),Cr=null;return}let g=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=Aa(g-b))})},100))};if(S=new Is(r,{onMessagesChanged(c){mo($e,c,Ie),ca(),S&&(c.some(k=>k.role==="user")?cr.render([],S,G,c):cr.render(r.suggestionChips,S,G,c,r.suggestionChipsConfig)),Vr(!zn),oa(c);let g=[...c].reverse().find(b=>b.role==="user"),y=mt.lastUserMessageId;g&&g.id!==y&&(mt.lastUserMessageId=g.id,o.emit("user:message",g)),mt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wo(c),Rr()},onStatusChanged(c){var b;let g=(b=r.statusIndicator)!=null?b:{};ge(ln,(k=>{var D,O,U,R;return k==="idle"?(D=g.idleText)!=null?D:fn.idle:k==="connecting"?(O=g.connectingText)!=null?O:fn.connecting:k==="connected"?(U=g.connectedText)!=null?U:fn.connected:k==="error"?(R=g.errorText)!=null?R:fn.error:fn[k]})(c),g,c)},onStreamingChanged(c){zn=c,Ro(c),S&&mo($e,S.getMessages(),Ie),c||Vr(!0),Rr()},onVoiceStatusChanged(c){var g,y;if(((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":J(),Y();break;case"speaking":J(),Z();break;default:c==="idle"&&S.isBargeInActive()?(J(),M(),K==null||K.setAttribute("aria-label","End voice session")):(mt.active=!1,J(),nr("system"),Ln());break}},onArtifactsState(c){Fn=c,jn(),Wo()}}),Pt.current=S,((gc=(mc=r.voiceRecognition)==null?void 0:mc.provider)==null?void 0:gc.type)==="runtype")try{S.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&S.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(V||r.onSSEEvent)&&S.setSSEEventCallback((c,g)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,g),pe==null||pe.processEvent(c,g),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,y,b;c&&(c.metadata&&(d=dl(c.metadata),E.syncFromMetadata()),(g=c.messages)!=null&&g.length&&S.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&S.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var g,y,b;!F()||B||!((b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Rt(!0,"auto")},fs=c=>{var k;if(c.preventDefault(),S.isStreaming()){S.cancel(),pe==null||pe.reset(),fe==null||fe.update();return}let g=G.value.trim(),y=(k=et==null?void 0:et.hasAttachments())!=null?k:!1;if(!g&&!y)return;gs();let b;y&&(b=[],b.push(...et.getContentParts()),g&&b.push(La(g))),G.value="",G.style.height="auto",go(),S.sendMessage(g,{contentParts:b}),y&&et.clearAttachments()},da=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Bo={...Na},Do=!1,go=()=>{Bo={...Na}},pa=()=>S.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),ua=c=>{if(!G)return;Do=!0,G.value=c,G.dispatchEvent(new Event("input",{bubbles:!0})),Do=!1;let g=G.value.length;G.setSelectionRange(g,g)},hs=()=>{Do||go()},ys=c=>{if(G){if(da()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=G.selectionStart===0&&G.selectionEnd===0,y=zp({direction:c.key==="ArrowUp"?"up":"down",history:pa(),currentValue:G.value,atStart:g,state:Bo});if(Bo=y.state,y.handled){c.preventDefault(),y.value!==void 0&&ua(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(S.isStreaming()){c.preventDefault();return}go(),c.preventDefault(),Oe.click()}}},bs=c=>{c.key!=="Escape"||c.isComposing||S.isStreaming()&&c.composedPath().includes(de)&&(S.cancel(),pe==null||pe.reset(),fe==null||fe.update(),go(),c.preventDefault(),c.stopImmediatePropagation())},xs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!et)return;let g=wb(c.clipboardData);g.length!==0&&(c.preventDefault(),await et.handleFiles(g))},wn=null,Vn=!1,Hr=null,ot=null,vs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,fo=(c="user")=>{var D,O,U,R,we,le,ee;if(Vn||S.isStreaming())return;let g=vs();if(!g)return;wn=new g;let b=(O=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?O:2e3;wn.continuous=!0,wn.interimResults=!0,wn.lang="en-US";let k=G.value;wn.onresult=he=>{let Ae="",He="";for(let Je=0;Je<he.results.length;Je++){let it=he.results[Je],lt=it[0].transcript;it.isFinal?Ae+=lt+" ":He=lt}let tt=k+Ae+He;G.value=tt,Hr&&clearTimeout(Hr),(Ae||He)&&(Hr=window.setTimeout(()=>{let Je=G.value.trim();Je&&wn&&Vn&&(gr(),G.value="",G.style.height="auto",S.sendMessage(Je,{viaVoice:!0}))},b))},wn.onerror=he=>{he.error!=="no-speech"&&gr()},wn.onend=()=>{if(Vn){let he=G.value.trim();he&&he!==k.trim()&&(G.value="",G.style.height="auto",S.sendMessage(he,{viaVoice:!0})),gr()}};try{if(wn.start(),Vn=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),nr(c),Ln(),K){let he=(U=r.voiceRecognition)!=null?U:{};ot={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(R=he.iconName)!=null?R:"mic",iconSize:parseFloat((ee=(le=he.iconSize)!=null?le:(we=r.sendButton)==null?void 0:we.size)!=null?ee:"40")||24};let Ae=he.recordingBackgroundColor,He=he.recordingIconColor,tt=he.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=Ae!=null?Ae:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=He!=null?He:"var(--persona-voice-recording-indicator, #ffffff)",He){let Je=K.querySelector("svg");Je&&Je.setAttribute("stroke",He)}tt&&(K.style.borderColor=tt),K.setAttribute("aria-label","Stop voice recognition")}}catch{gr("system")}},gr=(c="user")=>{if(Vn){if(Vn=!1,Hr&&(clearTimeout(Hr),Hr=null),wn){try{wn.stop()}catch{}wn=null}if(mt.active=!1,nr(c),Ln(),K){if(K.classList.remove("persona-voice-recording"),ot){K.style.backgroundColor=ot.backgroundColor,K.style.color=ot.color,K.style.borderColor=ot.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",ot.color||"currentColor"),ot=null}K.setAttribute("aria-label","Start voice recognition")}}},No=(c,g)=>{var it,lt,Te,Ee,je,T,Se,Pe;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(y||b))return null;let D=h("div","persona-send-button-wrapper"),O=h("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 U=(lt=c==null?void 0:c.iconName)!=null?lt:"mic",R=(Te=g==null?void 0:g.size)!=null?Te:"40px",we=(Ee=c==null?void 0:c.iconSize)!=null?Ee:R,le=parseFloat(we)||24,ee=(je=c==null?void 0:c.backgroundColor)!=null?je:g==null?void 0:g.backgroundColor,he=(T=c==null?void 0:c.iconColor)!=null?T:g==null?void 0:g.textColor;O.style.width=we,O.style.height=we,O.style.minWidth=we,O.style.minHeight=we,O.style.fontSize="18px",O.style.lineHeight="1",he?O.style.color=he:O.style.color="var(--persona-text, #111827)";let He=be(U,le,he||"currentColor",1.5);He?O.appendChild(He):O.textContent="\u{1F3A4}",ee?O.style.backgroundColor=ee:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),D.appendChild(O);let tt=(Se=c==null?void 0:c.tooltipText)!=null?Se:"Start voice recognition";if(((Pe=c==null?void 0:c.showTooltip)!=null?Pe:!1)&&tt){let ze=h("div","persona-send-button-tooltip");ze.textContent=tt,D.appendChild(ze)}return{micButton:O,micButtonWrapper:D}},Ue=()=>{var g,y,b,k,D;if(!K||ot)return;let c=(g=r.voiceRecognition)!=null?g:{};ot={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((D=(k=c.iconSize)!=null?k:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},C=(c,g)=>{var D,O,U,R,we;if(!K)return;let y=K.querySelector("svg");y&&y.remove();let b=(we=ot==null?void 0:ot.iconSize)!=null?we:parseFloat((R=(U=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?U:(O=r.sendButton)==null?void 0:O.size)!=null?R:"40")||24,k=be(c,b,g,1.5);k&&K.appendChild(k)},$=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},M=()=>{var k;if(!K)return;Ue();let c=(k=r.voiceRecognition)!=null?k:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if($(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let D=K.querySelector("svg");D&&D.setAttribute("stroke",y)}b&&(K.style.borderColor=b),K.setAttribute("aria-label","Stop voice recognition")},Y=()=>{var U,R,we,le,ee,he,Ae,He;if(!K)return;Ue();let c=(U=r.voiceRecognition)!=null?U:{},g=S.getVoiceInterruptionMode(),y=(R=c.processingIconName)!=null?R:"loader",b=(le=(we=c.processingIconColor)!=null?we:ot==null?void 0:ot.color)!=null?le:"",k=(he=(ee=c.processingBackgroundColor)!=null?ee:ot==null?void 0:ot.backgroundColor)!=null?he:"",D=(He=(Ae=c.processingBorderColor)!=null?Ae:ot==null?void 0:ot.borderColor)!=null?He:"";$(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=k,K.style.borderColor=D;let O=b||"currentColor";K.style.color=O,C(y,O),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},Z=()=>{var we,le,ee,he,Ae,He,tt,Je,it,lt,Te,Ee;if(!K)return;Ue();let c=(we=r.voiceRecognition)!=null?we:{},g=S.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:y,k=(He=c.speakingIconColor)!=null?He:g==="barge-in"?(he=(ee=c.recordingIconColor)!=null?ee:ot==null?void 0:ot.color)!=null?he:"":(Ae=ot==null?void 0:ot.color)!=null?Ae:"",D=(it=c.speakingBackgroundColor)!=null?it:g==="barge-in"?(tt=c.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(Je=ot==null?void 0:ot.backgroundColor)!=null?Je:"",O=(Ee=c.speakingBorderColor)!=null?Ee:g==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Te=ot==null?void 0:ot.borderColor)!=null?Te:"";$(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=D,K.style.borderColor=O;let U=k||"currentColor";K.style.color=U,C(b,U);let R=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",R),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},J=()=>{var c,g,y;K&&($(),ot&&(K.style.backgroundColor=(c=ot.backgroundColor)!=null?c:"",K.style.color=(g=ot.color)!=null?g:"",K.style.borderColor=(y=ot.borderColor)!=null?y:"",C(ot.iconName,ot.color||"currentColor"),ot=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},qe=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let y=S.getVoiceStatus(),b=S.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){S.stopVoicePlayback();return}if(S.isBargeInActive()){S.stopVoicePlayback(),S.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Ln(),nr("user"),J()});return}S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),mt.manuallyDeactivated=!S.isVoiceActive(),Ln(),nr("user"),S.isVoiceActive()?M():J()});return}if(Vn){let y=G.value.trim();mt.manuallyDeactivated=!0,Ln(),gr("user"),y&&(G.value="",G.style.height="auto",S.sendMessage(y))}else mt.manuallyDeactivated=!1,Ln(),fo("user")};Bn=qe,K&&(K.addEventListener("click",qe),ft.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(S.isVoiceActive()&&S.toggleVoice(),J()):gr("system"),K&&K.removeEventListener("click",qe)}));let De=o.on("assistant:complete",()=>{is&&(mt.active||mt.manuallyDeactivated||is==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!mt.active&&!mt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("auto"),S.isVoiceActive()&&M()}):fo("auto"))},600))});ft.push(De);let at=o.on("action:resubmit",()=>{setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)});ft.push(at);let Ve=()=>{Rt(!B,"user")},Ke=null,Ye=null;if(A&&!F()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>Us(r,Ve).element,onToggle:Ve});g&&(Ye=g)}Ye||(Ke=Us(r,Ve))}Ke?e.appendChild(Ke.element):Ye&&e.appendChild(Ye),Xr(),cr.render(r.suggestionChips,S,G,void 0,r.suggestionChipsConfig),ms(),Ro(S.isStreaming()),Vr(!0),ea(),P&&(!A||F()?setTimeout(()=>Ho(),0):B&&setTimeout(()=>Ho(),200));let Xt=()=>{var R,we,le,ee,he,Ae,He,tt,Je,it,lt,Te,Ee,je,T,Se,Pe,ze,xe,Lt,st,Qt;if(F()){bt(),Xr();return}let c=an(r),g=(we=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?we:!1,y=c||g||((ee=(le=r.launcher)==null?void 0:le.fullHeight)!=null?ee:!1),b=(he=e.ownerDocument.defaultView)!=null?he:window,k=(He=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?He:!0,D=(Je=(tt=r.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Je:640,O=b.innerWidth<=D,U=k&&O&&A;try{if(U){lr(),Eo(e,r);return}if(W&&(W=!1,lr(),Eo(e,r)),!A&&!c){ae.style.height="",ae.style.width="";return}if(!g&&!c){let dn=(lt=(it=r==null?void 0:r.launcher)==null?void 0:it.width)!=null?lt:r==null?void 0:r.launcherWidth,It=dn!=null?dn:sr;ae.style.width=It,ae.style.maxWidth=It}if(vr(),!y){let dn=b.innerHeight,It=64,Cn=(Ee=(Te=r.launcher)==null?void 0:Te.heightOffset)!=null?Ee:0,pn=Math.max(200,dn-It),Ze=Math.min(640,pn),ct=Math.max(200,Ze-Cn);ae.style.height=`${ct}px`}}finally{if(bt(),Xr(),B&&A){let It=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((Se=(T=r.launcher)==null?void 0:T.mobileBreakpoint)!=null?Se:640),Cn=(ze=(Pe=r.launcher)==null?void 0:Pe.sidebarMode)!=null?ze:!1,pn=(Lt=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?Lt:!0,Ze=an(r)&&pn&&It,ct=Cn||pn&&It&&A||Ze;if(ct&&!Gt){let An=e.getRootNode(),mn=An instanceof ShadowRoot?An.host:e.closest(".persona-host");mn&&!Jt&&(Jt=Di(mn,(Qt=(st=r.launcher)==null?void 0:st.zIndex)!=null?Qt:hn)),Gt=Ni(e.ownerDocument)}else ct||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null)}}};Xt();let Et=(fc=e.ownerDocument.defaultView)!=null?fc:window;if(Et.addEventListener("resize",Xt),ft.push(()=>Et.removeEventListener("resize",Xt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bt()});c.observe(_e),ft.push(()=>c.disconnect())}ur=X.scrollTop;let kt=X.scrollHeight,rn=()=>{let c=X.scrollTop,g=X.scrollHeight,y=g<kt;kt=g;let{action:b,nextLastScrollTop:k}=Fa({following:pr.isFollowing(),currentScrollTop:c,lastScrollTop:ur,nearBottom:Ds(X,as),userScrollThreshold:Ys,isAutoScrolling:Pr||po||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ur=k,b==="resume"){zr();return}b==="pause"&&cs()};X.addEventListener("scroll",rn,{passive:!0}),ft.push(()=>X.removeEventListener("scroll",rn));let un=c=>{let g=_a({following:pr.isFollowing(),deltaY:c.deltaY,nearBottom:Ds(X,as),resumeWhenNearBottom:!0});g==="pause"?cs():g==="resume"&&zr()};X.addEventListener("wheel",un,{passive:!0}),ft.push(()=>X.removeEventListener("wheel",un)),Tt.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,ur=X.scrollTop,zr(),Vr(!0)}),ft.push(()=>Tt.remove()),ft.push(()=>{ls()});let cn=()=>{H&&(qn&&(H.removeEventListener("click",qn),qn=null),_()?(H.style.display="",qn=()=>{Rt(!1,"user")},H.addEventListener("click",qn)):H.style.display="none")};cn(),(()=>{let{clearChatButton:c}=Ce;c&&c.addEventListener("click",()=>{S.clearMessages(),dr.clear(),zr(),ko(Ce.composerOverlay);try{localStorage.removeItem(rs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},E.syncFromMetadata(),V==null||V.clear(),pe==null||pe.reset(),fe==null||fe.update()})})(),Dt&&Dt.addEventListener("submit",fs),G==null||G.addEventListener("keydown",ys),G==null||G.addEventListener("input",hs),G==null||G.addEventListener("paste",xs);let rr=(hc=e.ownerDocument)!=null?hc:document;rr.addEventListener("keydown",bs,!0);let Cl="persona-attachment-drop-active",ws=0,vi=()=>{ws=0,de.classList.remove(Cl)},Oo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&et!==null},Al=c=>{!di(c.dataTransfer)||!Oo()||(ws++,ws===1&&de.classList.add(Cl))},Sl=c=>{!di(c.dataTransfer)||!Oo()||(ws--,ws<=0&&vi())},El=c=>{!di(c.dataTransfer)||!Oo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Tl=c=>{var y;if(!di(c.dataTransfer)||!Oo())return;c.preventDefault(),c.stopPropagation(),vi();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&et.handleFiles(g)},Qr=!0;de.addEventListener("dragenter",Al,Qr),de.addEventListener("dragleave",Sl,Qr),e.addEventListener("dragover",El,Qr),e.addEventListener("drop",Tl,Qr);let ma=e.ownerDocument,Ml=c=>{Oo()&&c.preventDefault()},kl=c=>{Oo()&&c.preventDefault()};ma.addEventListener("dragover",Ml),ma.addEventListener("drop",kl),ft.push(()=>{Dt&&Dt.removeEventListener("submit",fs),G==null||G.removeEventListener("keydown",ys),G==null||G.removeEventListener("input",hs),G==null||G.removeEventListener("paste",xs),rr.removeEventListener("keydown",bs,!0)}),ft.push(()=>{de.removeEventListener("dragenter",Al,Qr),de.removeEventListener("dragleave",Sl,Qr),e.removeEventListener("dragover",El,Qr),e.removeEventListener("drop",Tl,Qr),ma.removeEventListener("dragover",Ml),ma.removeEventListener("drop",kl),vi()}),ft.push(()=>{S.cancel()}),Ke?ft.push(()=>{Ke==null||Ke.destroy()}):Ye&&ft.push(()=>{Ye==null||Ye.remove()});let tn={update(c){var nn,Ar,Dr,ga,fa,ha,vo,ya,Cs,Ac,Sc,Ec,Tc,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp;let g=r.toolCall,y=r.messageActions,b=(nn=r.layout)==null?void 0:nn.messages,k=r.colorScheme,D=r.loadingIndicator,O=r.iterationDisplay,U=(Ar=r.features)==null?void 0:Ar.showReasoning,R=(Dr=r.features)==null?void 0:Dr.showToolCalls,we=(ga=r.features)==null?void 0:ga.toolCallDisplay,le=(fa=r.features)==null?void 0:fa.reasoningDisplay;r={...r,...c},lr(),Eo(e,r),si(e,r),ai(e,r),jn(),r.colorScheme!==k&&qr();let ee=ii.getForInstance(r.plugins);s.length=0,s.push(...ee),A=(vo=(ha=r.launcher)==null?void 0:ha.enabled)!=null?vo:!0,I=(Cs=(ya=r.launcher)==null?void 0:ya.autoExpand)!=null?Cs:!1,Re=(Sc=(Ac=r.features)==null?void 0:Ac.showReasoning)!=null?Sc:!0,Ne=(Tc=(Ec=r.features)==null?void 0:Ec.showToolCalls)!=null?Tc:!0,ve=(kc=(Mc=r.features)==null?void 0:Mc.scrollToBottom)!=null?kc:{},qt(),Wr();let he=ce;if(ce=(Pc=(Lc=r.features)==null?void 0:Lc.showEventStreamToggle)!=null?Pc:!1,ce&&!he){if(V||(ne=new Xs(Le),V=new Gs(ke,ne),pe=pe!=null?pe:new Qs,ne.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),S.setSSEEventCallback((Q,vt)=>{var Nt;(Nt=r.onSSEEvent)==null||Nt.call(r,Q,vt),pe==null||pe.processEvent(Q,vt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(vt)})})),!ut&&Fe){let Q=(Wc=(Ic=r.features)==null?void 0:Ic.eventStream)==null?void 0:Wc.classNames,vt="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"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");ut=h("button",vt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Tn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Nt=be("activity","18px","currentColor",1.5);Nt&&ut.appendChild(Nt);let dt=Ce.clearChatButtonWrapper,Mt=Ce.closeButtonWrapper,on=dt||Mt;on&&on.parentNode===Fe?Fe.insertBefore(ut,on):Fe.appendChild(ut),ut.addEventListener("click",()=>{me?Dn():bn()})}}else!ce&&he&&(Dn(),ut&&(ut.remove(),ut=null),V==null||V.clear(),ne==null||ne.destroy(),V=null,ne=null,pe==null||pe.reset(),pe=null);if(((Rc=r.launcher)==null?void 0:Rc.enabled)===!1&&Ke&&(Ke.destroy(),Ke=null),((Hc=r.launcher)==null?void 0:Hc.enabled)===!1&&Ye&&(Ye.remove(),Ye=null),((Bc=r.launcher)==null?void 0:Bc.enabled)!==!1&&!Ke&&!Ye){let Q=s.find(vt=>vt.renderLauncher);if(Q!=null&&Q.renderLauncher){let vt=Q.renderLauncher({config:r,defaultRenderer:()=>Us(r,Ve).element,onToggle:Ve});vt&&(Ye=vt,e.appendChild(Ye))}Ye||(Ke=Us(r,Ve),e.appendChild(Ke.element))}Ke&&Ke.update(r),Be&&((Dc=r.launcher)==null?void 0:Dc.title)!==void 0&&(Be.textContent=r.launcher.title),Xe&&((Nc=r.launcher)==null?void 0:Nc.subtitle)!==void 0&&(Xe.textContent=r.launcher.subtitle);let Ae=(Oc=r.layout)==null?void 0:Oc.header;if((Ae==null?void 0:Ae.layout)!==w&&Fe){let Q=Ae?qs(r,Ae,{showClose:_(),onClose:()=>Rt(!1,"user")}):no({config:r,showClose:_(),onClose:()=>Rt(!1,"user")});Fe.replaceWith(Q.header),Fe=Q.header,oe=Q.iconHolder,Be=Q.headerTitle,Xe=Q.headerSubtitle,H=Q.closeButton,w=Ae==null?void 0:Ae.layout}else if(Ae&&(oe&&(oe.style.display=Ae.showIcon===!1?"none":""),Be&&(Be.style.display=Ae.showTitle===!1?"none":""),Xe&&(Xe.style.display=Ae.showSubtitle===!1?"none":""),H&&(H.style.display=Ae.showCloseButton===!1?"none":""),Ce.clearChatButtonWrapper)){let Q=Ae.showClearChat;if(Q!==void 0){Ce.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:vt}=Ce;vt&&!vt.classList.contains("persona-absolute")&&(Q?vt.classList.remove("persona-ml-auto"):vt.classList.add("persona-ml-auto"))}}let tt=((Fc=r.layout)==null?void 0:Fc.showHeader)!==!1;Fe&&(Fe.style.display=tt?"":"none");let Je=((_c=r.layout)==null?void 0:_c.showFooter)!==!1;_e&&(_e.style.display=Je?"":"none"),bt(),Wr(),A!==L?A?Rt(I,"auto"):(B=!0,Xr()):I!==N&&Rt(I,"auto"),N=I,L=A,Xt(),cn();let Te=JSON.stringify(c.toolCall)!==JSON.stringify(g),Ee=JSON.stringify(r.messageActions)!==JSON.stringify(y),je=JSON.stringify(($c=r.layout)==null?void 0:$c.messages)!==JSON.stringify(b),T=((jc=r.loadingIndicator)==null?void 0:jc.render)!==(D==null?void 0:D.render)||((Uc=r.loadingIndicator)==null?void 0:Uc.renderIdle)!==(D==null?void 0:D.renderIdle)||((qc=r.loadingIndicator)==null?void 0:qc.showBubble)!==(D==null?void 0:D.showBubble),Se=r.iterationDisplay!==O,Pe=((Vc=(zc=r.features)==null?void 0:zc.showReasoning)!=null?Vc:!0)!==(U!=null?U:!0)||((Jc=(Kc=r.features)==null?void 0:Kc.showToolCalls)!=null?Jc:!0)!==(R!=null?R:!0)||JSON.stringify((Gc=r.features)==null?void 0:Gc.toolCallDisplay)!==JSON.stringify(we)||JSON.stringify((Xc=r.features)==null?void 0:Xc.reasoningDisplay)!==JSON.stringify(le);(Te||Ee||je||T||Se||Pe)&&S&&(ss++,mo($e,S.getMessages(),Ie));let xe=(Qc=r.launcher)!=null?Qc:{},Lt=(Yc=xe.headerIconHidden)!=null?Yc:!1,st=(ed=(Zc=r.layout)==null?void 0:Zc.header)==null?void 0:ed.showIcon,Qt=Lt||st===!1,dn=xe.headerIconName,It=(td=xe.headerIconSize)!=null?td:"48px";if(oe){let Q=de.querySelector(".persona-border-b-persona-divider"),vt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Qt)oe.style.display="none",Q&&vt&&!Q.contains(vt)&&Q.insertBefore(vt,Q.firstChild);else{if(oe.style.display="",oe.style.height=It,oe.style.width=It,Q&&vt&&(Q.contains(oe)?oe.nextSibling!==vt&&(oe.remove(),Q.insertBefore(oe,vt)):Q.insertBefore(oe,vt)),dn){let dt=parseFloat(It)||24,Mt=be(dn,dt*.6,"#ffffff",2);Mt?oe.replaceChildren(Mt):oe.textContent=(nd=xe.agentIconText)!=null?nd:"\u{1F4AC}"}else if(xe.iconUrl){let dt=oe.querySelector("img");if(dt)dt.src=xe.iconUrl,dt.style.height=It,dt.style.width=It;else{let Mt=document.createElement("img");Mt.src=xe.iconUrl,Mt.alt="",Mt.className="persona-rounded-xl persona-object-cover",Mt.style.height=It,Mt.style.width=It,oe.replaceChildren(Mt)}}else{let dt=oe.querySelector("svg"),Mt=oe.querySelector("img");(dt||Mt)&&oe.replaceChildren(),oe.textContent=(rd=xe.agentIconText)!=null?rd:"\u{1F4AC}"}let Nt=oe.querySelector("img");Nt&&(Nt.style.height=It,Nt.style.width=It)}}let Cn=(sd=(od=r.layout)==null?void 0:od.header)==null?void 0:sd.showTitle,pn=(id=(ad=r.layout)==null?void 0:ad.header)==null?void 0:id.showSubtitle;if(Be&&(Be.style.display=Cn===!1?"none":""),Xe&&(Xe.style.display=pn===!1?"none":""),H){((cd=(ld=r.layout)==null?void 0:ld.header)==null?void 0:cd.showCloseButton)===!1?H.style.display="none":H.style.display="";let vt=(dd=xe.closeButtonSize)!=null?dd:"32px",Nt=(pd=xe.closeButtonPlacement)!=null?pd:"inline";H.style.height=vt,H.style.width=vt;let{closeButtonWrapper:dt}=Ce,Mt=Nt==="top-right",on=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Mt!==on)if(dt.remove(),Mt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",de.style.position="relative",de.appendChild(dt);else{let pt=(md=(ud=xe.clearChat)==null?void 0:ud.placement)!=null?md:"inline",sn=(fd=(gd=xe.clearChat)==null?void 0:gd.enabled)!=null?fd:!0;dt.className=sn&&pt==="inline"?"":"persona-ml-auto";let Rn=de.querySelector(".persona-border-b-persona-divider");Rn&&Rn.appendChild(dt)}if(H.style.color=xe.closeButtonColor||Tn.actionIconColor,xe.closeButtonBackgroundColor?(H.style.backgroundColor=xe.closeButtonBackgroundColor,H.classList.remove("hover:persona-bg-gray-100")):(H.style.backgroundColor="",H.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";H.style.border=`${pt} solid ${sn}`,H.classList.remove("persona-border-none")}else H.style.border="",H.classList.add("persona-border-none");xe.closeButtonBorderRadius?(H.style.borderRadius=xe.closeButtonBorderRadius,H.classList.remove("persona-rounded-full")):(H.style.borderRadius="",H.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(H.style.paddingLeft=xe.closeButtonPaddingX,H.style.paddingRight=xe.closeButtonPaddingX):(H.style.paddingLeft="",H.style.paddingRight=""),xe.closeButtonPaddingY?(H.style.paddingTop=xe.closeButtonPaddingY,H.style.paddingBottom=xe.closeButtonPaddingY):(H.style.paddingTop="",H.style.paddingBottom="");let gn=(hd=xe.closeButtonIconName)!=null?hd:"x",fr=(yd=xe.closeButtonIconText)!=null?yd:"\xD7";H.innerHTML="";let En=be(gn,"28px","currentColor",1);En?H.appendChild(En):H.textContent=fr;let Yt=(bd=xe.closeButtonTooltipText)!=null?bd:"Close chat",Jn=(xd=xe.closeButtonShowTooltip)!=null?xd:!0;if(H.setAttribute("aria-label",Yt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!H)return;let wo=H.ownerDocument,As=wo.body;if(!As)return;pt=Sr(wo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ss=Sr(wo,"div");Ss.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ss);let Co=H.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Zr),pt.style.left=`${Co.left+Co.width/2}px`,pt.style.top=`${Co.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Rn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};dt.addEventListener("mouseenter",sn),dt.addEventListener("mouseleave",Rn),H.addEventListener("focus",sn),H.addEventListener("blur",Rn),dt._cleanupTooltip=()=>{Rn(),dt&&(dt.removeEventListener("mouseenter",sn),dt.removeEventListener("mouseleave",Rn)),H&&(H.removeEventListener("focus",sn),H.removeEventListener("blur",Rn))}}}let{clearChatButton:Ze,clearChatButtonWrapper:ct}=Ce;if(Ze){let Q=(vd=xe.clearChat)!=null?vd:{},vt=(wd=Q.enabled)!=null?wd:!0,Nt=(Ad=(Cd=r.layout)==null?void 0:Cd.header)==null?void 0:Ad.showClearChat,dt=Nt!==void 0?Nt:vt,Mt=(Sd=Q.placement)!=null?Sd:"inline";if(ct){ct.style.display=dt?"":"none";let{closeButtonWrapper:on}=Ce;!F()&&on&&!on.classList.contains("persona-absolute")&&(dt?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let gn=Mt==="top-right",fr=ct.classList.contains("persona-absolute");if(!F()&&gn!==fr&&dt){if(ct.remove(),gn)ct.className="persona-absolute persona-top-4 persona-z-50",ct.style.right="48px",de.style.position="relative",de.appendChild(ct);else{ct.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ct.style.right="";let Yt=de.querySelector(".persona-border-b-persona-divider"),Jn=Ce.closeButtonWrapper;Yt&&Jn&&Jn.parentElement===Yt?Yt.insertBefore(ct,Jn):Yt&&Yt.appendChild(ct)}let En=Ce.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(gn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(dt){if(!F()){let pt=(Ed=Q.size)!=null?Ed:"32px";Ze.style.height=pt,Ze.style.width=pt}let on=(Td=Q.iconName)!=null?Td:"refresh-cw",gn=(Md=Q.iconColor)!=null?Md:"";Ze.style.color=gn||Tn.actionIconColor,Ze.innerHTML="";let fr=F()?"14px":"20px",En=be(on,fr,"currentColor",2);if(En&&Ze.appendChild(En),Q.backgroundColor?(Ze.style.backgroundColor=Q.backgroundColor,Ze.classList.remove("hover:persona-bg-gray-100")):(Ze.style.backgroundColor="",Ze.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let pt=Q.borderWidth||"0px",sn=Q.borderColor||"transparent";Ze.style.border=`${pt} solid ${sn}`,Ze.classList.remove("persona-border-none")}else Ze.style.border="",Ze.classList.add("persona-border-none");Q.borderRadius?(Ze.style.borderRadius=Q.borderRadius,Ze.classList.remove("persona-rounded-full")):(Ze.style.borderRadius="",Ze.classList.add("persona-rounded-full")),Q.paddingX?(Ze.style.paddingLeft=Q.paddingX,Ze.style.paddingRight=Q.paddingX):(Ze.style.paddingLeft="",Ze.style.paddingRight=""),Q.paddingY?(Ze.style.paddingTop=Q.paddingY,Ze.style.paddingBottom=Q.paddingY):(Ze.style.paddingTop="",Ze.style.paddingBottom="");let Yt=(kd=Q.tooltipText)!=null?kd:"Clear chat",Jn=(Ld=Q.showTooltip)!=null?Ld:!0;if(Ze.setAttribute("aria-label",Yt),ct&&(ct._cleanupTooltip&&(ct._cleanupTooltip(),delete ct._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!Ze)return;let wo=Ze.ownerDocument,As=wo.body;if(!As)return;pt=Sr(wo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let Ss=Sr(wo,"div");Ss.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ss);let Co=Ze.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Zr),pt.style.left=`${Co.left+Co.width/2}px`,pt.style.top=`${Co.top-8}px`,pt.style.transform="translate(-50%, -100%)",As.appendChild(pt)},Rn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};ct.addEventListener("mouseenter",sn),ct.addEventListener("mouseleave",Rn),Ze.addEventListener("focus",sn),Ze.addEventListener("blur",Rn),ct._cleanupTooltip=()=>{Rn(),ct&&(ct.removeEventListener("mouseenter",sn),ct.removeEventListener("mouseleave",Rn)),Ze&&(Ze.removeEventListener("focus",sn),Ze.removeEventListener("blur",Rn))}}}}let An=r.actionParsers&&r.actionParsers.length?r.actionParsers:[li],mn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick];E=ci({parsers:An,handlers:mn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ie=qu(r,E,re),S.updateConfig(r),mo($e,S.getMessages(),Ie),cr.render(r.suggestionChips,S,G,void 0,r.suggestionChipsConfig),ms(),Ro(S.isStreaming());let ho=((Pd=r.voiceRecognition)==null?void 0:Pd.enabled)===!0,yo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),bo=((Wd=(Id=r.voiceRecognition)==null?void 0:Id.provider)==null?void 0:Wd.type)==="runtype";if(ho&&(yo||bo))if(!K||!gt){let Q=No(r.voiceRecognition,r.sendButton);Q&&(K=Q.micButton,gt=Q.micButtonWrapper,Ft.insertBefore(gt,Mn),K.addEventListener("click",qe),K.disabled=S.isStreaming())}else{let Q=(Rd=r.voiceRecognition)!=null?Rd:{},vt=(Hd=r.sendButton)!=null?Hd:{},Nt=(Bd=Q.iconName)!=null?Bd:"mic",dt=(Dd=vt.size)!=null?Dd:"40px",Mt=(Nd=Q.iconSize)!=null?Nd:dt,on=parseFloat(Mt)||24;K.style.width=Mt,K.style.height=Mt,K.style.minWidth=Mt,K.style.minHeight=Mt;let gn=(Fd=(Od=Q.iconColor)!=null?Od:vt.textColor)!=null?Fd:"currentColor";K.innerHTML="";let fr=be(Nt,on,gn,2);fr?K.appendChild(fr):K.textContent="\u{1F3A4}";let En=(_d=Q.backgroundColor)!=null?_d:vt.backgroundColor;En?K.style.backgroundColor=En:K.style.backgroundColor="",gn?K.style.color=gn:K.style.color="var(--persona-text, #111827)",Q.borderWidth?(K.style.borderWidth=Q.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),Q.borderColor?K.style.borderColor=Q.borderColor:K.style.borderColor="",Q.paddingX?(K.style.paddingLeft=Q.paddingX,K.style.paddingRight=Q.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),Q.paddingY?(K.style.paddingTop=Q.paddingY,K.style.paddingBottom=Q.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Yt=gt==null?void 0:gt.querySelector(".persona-send-button-tooltip"),Jn=($d=Q.tooltipText)!=null?$d:"Start voice recognition";if(((jd=Q.showTooltip)!=null?jd:!1)&&Jn)if(Yt)Yt.textContent=Jn,Yt.style.display="";else{let sn=document.createElement("div");sn.className="persona-send-button-tooltip",sn.textContent=Jn,gt==null||gt.insertBefore(sn,K)}else Yt&&(Yt.style.display="none");gt.style.display="",K.disabled=S.isStreaming()}else K&&gt&&(gt.style.display="none",((qd=(Ud=r.voiceRecognition)==null?void 0:Ud.provider)==null?void 0:qd.type)==="runtype"?S.isVoiceActive()&&S.toggleVoice():Vn&&gr());if(((zd=r.attachments)==null?void 0:zd.enabled)===!0)if(!Ut||!nt){let Q=(Vd=r.attachments)!=null?Vd:{},Nt=(Jd=((Kd=r.sendButton)!=null?Kd:{}).size)!=null?Jd:"40px";ye||(ye=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ye.style.display="none",Dt.insertBefore(ye,G)),se||(se=document.createElement("input"),se.type="file",se.accept=((Gd=Q.allowedTypes)!=null?Gd:Nr).join(","),se.multiple=((Xd=Q.maxFiles)!=null?Xd:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),Dt.insertBefore(se,G)),Ut=h("div","persona-send-button-wrapper"),nt=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),nt.type="button",nt.setAttribute("aria-label",(Qd=Q.buttonTooltipText)!=null?Qd:"Attach file");let dt=(Yd=Q.buttonIconName)!=null?Yd:"paperclip",Mt=Nt,on=parseFloat(Mt)||40,gn=Math.round(on*.6);nt.style.width=Mt,nt.style.height=Mt,nt.style.minWidth=Mt,nt.style.minHeight=Mt,nt.style.fontSize="18px",nt.style.lineHeight="1",nt.style.backgroundColor="transparent",nt.style.color="var(--persona-primary, #111827)",nt.style.border="none",nt.style.borderRadius="6px",nt.style.transition="background-color 0.15s ease",nt.addEventListener("mouseenter",()=>{nt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),nt.addEventListener("mouseleave",()=>{nt.style.backgroundColor="transparent"});let fr=be(dt,gn,"currentColor",1.5);fr?nt.appendChild(fr):nt.textContent="\u{1F4CE}",nt.addEventListener("click",Jn=>{Jn.preventDefault(),se==null||se.click()}),Ut.appendChild(nt);let En=(Zd=Q.buttonTooltipText)!=null?Zd:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=En,Ut.appendChild(Yt),At.append(Ut),!et&&se&&ye&&(et=Ko.fromConfig(Q),et.setPreviewsContainer(ye),se.addEventListener("change",async()=>{et&&(se!=null&&se.files)&&(await et.handleFileSelect(se.files),se.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(zu(Q.dropOverlay))}else{Ut.style.display="";let Q=(ep=r.attachments)!=null?ep:{};se&&(se.accept=((tp=Q.allowedTypes)!=null?tp:Nr).join(","),se.multiple=((np=Q.maxFiles)!=null?np:4)>1),et&&et.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else Ut&&(Ut.style.display="none"),et&&et.clearAttachments(),(rp=de.querySelector(".persona-attachment-drop-overlay"))==null||rp.remove();let zt=(op=r.sendButton)!=null?op:{},xo=(sp=zt.useIcon)!=null?sp:!1,Yr=(ap=zt.iconText)!=null?ap:"\u2191",yt=zt.iconName,Pn=(ip=zt.tooltipText)!=null?ip:"Send message",Br=(lp=zt.showTooltip)!=null?lp:!1,Sn=(cp=zt.size)!=null?cp:"40px",In=zt.backgroundColor,Ht=zt.textColor;if(xo){if(Oe.style.width=Sn,Oe.style.height=Sn,Oe.style.minWidth=Sn,Oe.style.minHeight=Sn,Oe.style.fontSize="18px",Oe.style.lineHeight="1",Oe.innerHTML="",Ht?Oe.style.color=Ht:Oe.style.color="var(--persona-button-primary-fg, #ffffff)",yt){let Q=parseFloat(Sn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Nt=be(yt,Q,vt,2);Nt?Oe.appendChild(Nt):Oe.textContent=Yr}else Oe.textContent=Yr;Oe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",In?(Oe.style.backgroundColor=In,Oe.classList.remove("persona-bg-persona-primary")):(Oe.style.backgroundColor="",Oe.classList.add("persona-bg-persona-primary"))}else Oe.textContent=(pp=(dp=r.copy)==null?void 0:dp.sendButtonLabel)!=null?pp:"Send",Oe.style.width="",Oe.style.height="",Oe.style.minWidth="",Oe.style.minHeight="",Oe.style.fontSize="",Oe.style.lineHeight="",Oe.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",In?(Oe.style.backgroundColor=In,Oe.classList.remove("persona-bg-persona-accent")):Oe.classList.add("persona-bg-persona-accent"),Ht?Oe.style.color=Ht:Oe.classList.add("persona-text-white");zt.borderWidth?(Oe.style.borderWidth=zt.borderWidth,Oe.style.borderStyle="solid"):(Oe.style.borderWidth="",Oe.style.borderStyle=""),zt.borderColor?Oe.style.borderColor=zt.borderColor:Oe.style.borderColor="",zt.paddingX?(Oe.style.paddingLeft=zt.paddingX,Oe.style.paddingRight=zt.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),zt.paddingY?(Oe.style.paddingTop=zt.paddingY,Oe.style.paddingBottom=zt.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let $t=Mn==null?void 0:Mn.querySelector(".persona-send-button-tooltip");if(Br&&Pn)if($t)$t.textContent=Pn,$t.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Pn,Mn==null||Mn.insertBefore(Q,Oe)}else $t&&($t.style.display="none");let Bt=(hp=(up=r.layout)==null?void 0:up.contentMaxWidth)!=null?hp:F()?(fp=(gp=(mp=r.launcher)==null?void 0:mp.composerBar)==null?void 0:gp.contentMaxWidth)!=null?fp:"720px":void 0;Bt?($e.style.maxWidth=Bt,$e.style.marginLeft="auto",$e.style.marginRight="auto",$e.style.width="100%",Dt&&(Dt.style.maxWidth=Bt,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=Bt,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight="",$e.style.width="",Dt&&(Dt.style.maxWidth="",Dt.style.marginLeft="",Dt.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let Vt=(yp=r.statusIndicator)!=null?yp:{},Wn=(bp=Vt.visible)!=null?bp:!0;if(ln.style.display=Wn?"":"none",S){let Q=S.getStatus();ge(ln,(Nt=>{var dt,Mt,on,gn;return Nt==="idle"?(dt=Vt.idleText)!=null?dt:fn.idle:Nt==="connecting"?(Mt=Vt.connectingText)!=null?Mt:fn.connecting:Nt==="connected"?(on=Vt.connectedText)!=null?on:fn.connected:Nt==="error"?(gn=Vt.errorText)!=null?gn:fn.error:fn[Nt]})(Q),Vt,Q)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Kn=Vt.align==="left"?"persona-text-left":Vt.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Kn)},open(){_()&&Rt(!0,"api")},close(){_()&&Rt(!1,"api")},toggle(){_()&&Rt(!B,"api")},clearChat(){xn=!1,S.clearMessages(),dr.clear(),zr();try{localStorage.removeItem(rs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${rs}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},E.syncFromMetadata(),V==null||V.clear(),pe==null||pe.reset(),fe==null||fe.update()},setMessage(c){return!G||S.isStreaming()?!1:(!B&&_()&&Rt(!0,"system"),G.value=c,G.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(S.isStreaming())return!1;let g=(c==null?void 0:c.trim())||G.value.trim();return g?(!B&&_()&&Rt(!0,"system"),G.value="",G.style.height="auto",S.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return S.isStreaming()?!1:((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(S.isVoiceActive()||(!B&&_()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("user"),S.isVoiceActive()&&M()})),!0):Vn?!0:vs()?(!B&&_()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),fo("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?S.isVoiceActive()?(S.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,Ln(),nr("user"),J()}),!0):!1:Vn?(mt.manuallyDeactivated=!0,Ln(),gr("user"),!0):!1},injectMessage(c){return!B&&_()&&Rt(!0,"system"),S.injectMessage(c)},injectAssistantMessage(c){!B&&_()&&Rt(!0,"system");let g=S.injectAssistantMessage(c);return j&&(j=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{S&&!S.isStreaming()&&S.continueConversation()},100)),g},injectUserMessage(c){return!B&&_()&&Rt(!0,"system"),S.injectUserMessage(c)},injectSystemMessage(c){return!B&&_()&&Rt(!0,"system"),S.injectSystemMessage(c)},injectMessageBatch(c){return!B&&_()&&Rt(!0,"system"),S.injectMessageBatch(c)},injectComponentDirective(c){return!B&&_()&&Rt(!0,"system"),S.injectComponentDirective(c)},injectTestMessage(c){!B&&_()&&Rt(!0,"system"),S.injectTestEvent(c)},async connectStream(c,g){return S.connectStream(c,g)},__pushEventStreamEvent(c){V&&(pe==null||pe.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!ce||!V||bn()},hideEventStream(){me&&Dn()},isEventStreamVisible(){return me},showArtifacts(){ir(r)&&(xn=!1,jn(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(xn=!0,jn())},upsertArtifact(c){return ir(r)?(xn=!1,S.upsertArtifact(c)):null},selectArtifact(c){ir(r)&&S.selectArtifact(c)},clearArtifacts(){ir(r)&&S.clearArtifacts()},getArtifacts(){var c;return(c=S==null?void 0:S.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=S==null?void 0:S.getSelectedArtifactId())!=null?c:null},focusInput(){return A&&!B&&!F()||!G?!1:(G.focus(),!0)},async resolveApproval(c,g){let b=S.getMessages().find(k=>{var D;return k.variant==="approval"&&((D=k.approval)==null?void 0:D.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){S.resolveWebMcpApproval(b.id,g);return}return S.resolveApproval(b.approval,g)},getMessages(){return S.getMessages()},getStatus(){return S.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return _()&&B},isVoiceActive(){return mt.active},getState(){return{open:_()&&B,launcherEnabled:A,voiceActive:mt.active,streaming:S.isStreaming()}},showCSATFeedback(c){!B&&_()&&Rt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let y=ll({onSubmit:async(b,k)=>{var D;S.isClientTokenMode()&&await S.submitCSATFeedback(b,k),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!B&&_()&&Rt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let y=cl({onSubmit:async(b,k)=>{var D;S.isClientTokenMode()&&await S.submitNPSFeedback(b,k),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,k)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return S.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return S.submitNPSFeedback(c,g)},destroy(){Cr!=null&&(clearInterval(Cr),Cr=null),ft.forEach(c=>c()),ie.remove(),Qe==null||Qe.remove(),Ke==null||Ke.destroy(),Ye==null||Ye.remove(),qn&&H.removeEventListener("click",qn)}};if((((yc=n==null?void 0:n.debugTools)!=null?yc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:y=>y?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ft.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",g),ft.push(()=>{window.removeEventListener("persona:focusInput",g)}),ce){let U=we=>{let le=we.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&tn.showEventStream()},R=we=>{let le=we.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",R),ft.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",R)})}let y=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&tn.showArtifacts()},b=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&tn.hideArtifacts()},k=U=>{let R=U.detail;R!=null&&R.instanceId&&R.instanceId!==c||R!=null&&R.artifact&&tn.upsertArtifact(R.artifact)},D=U=>{let R=U.detail;R!=null&&R.instanceId&&R.instanceId!==c||typeof(R==null?void 0:R.id)=="string"&&tn.selectArtifact(R.id)},O=U=>{let R=U.detail;(!(R!=null&&R.instanceId)||R.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",O),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",O)})}let or=Cb(r.persistState);if(or&&_()){let c=Ab(or.storage),g=`${or.keyPrefix}widget-open`,y=`${or.keyPrefix}widget-voice`,b=`${or.keyPrefix}widget-voice-mode`;if(c){let k=((bc=or.persist)==null?void 0:bc.openState)&&c.getItem(g)==="true",D=((xc=or.persist)==null?void 0:xc.voiceState)&&c.getItem(y)==="true",O=((vc=or.persist)==null?void 0:vc.voiceState)&&c.getItem(b)==="true";if(k&&setTimeout(()=>{tn.open(),setTimeout(()=>{var U;if(D||O)tn.startVoiceRecognition();else if((U=or.persist)!=null&&U.focusInput){let R=e.querySelector("textarea");R&&R.focus()}},100)},0),(wc=or.persist)!=null&&wc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(Cc=or.persist)!=null&&Cc.voiceState&&(o.on("voice:state",U=>{c.setItem(y,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(b,U.viaVoice?"true":"false")})),or.clearOnChatClear){let U=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(b)},R=()=>U();window.addEventListener("persona:clear-chat",R),ft.push(()=>{window.removeEventListener("persona:clear-chat",R)})}}}return u&&_()&&setTimeout(()=>{tn.open()},0),Rr(),tn};var Sb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Vu=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},fl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Ku=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",fl(e)},ul=e=>{e.style.transition=""},ml=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},gl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},pi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Eb=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Tb=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Ju=(e,t,n,r,s,o,a)=>{var v,x,E,A,I,P;let i=yr(o),d=i.reveal==="push";Eb(e,t,n,r,d),Tb(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,p=(A=(E=o==null?void 0:o.launcher)==null?void 0:E.mobileBreakpoint)!=null?A:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ml(t),ul(r),Ku(r),gl(n),pi(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((P=(I=o==null?void 0:o.launcher)==null?void 0:I.zIndex)!=null?P:hn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ku(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ml(t),ul(r),gl(n),pi(s,r);let N=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":L;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=N,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ul(r),fl(r),pi(s,r);let N=Sb(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",W=i.side==="right"?a?`translateX(-${N}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${N}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${L+N}px`,t.style.transition=w,t.style.transform=W,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${L}px`,n.style.maxWidth=`${L}px`,n.style.minWidth=`${L}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ml(t),fl(r),gl(n),pi(s,r);let N=i.reveal==="emerge";N?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",w=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 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",r.style.position="relative",r.style.overflow=N||W?"hidden":"visible",r.style.transition=w,N&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Mb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Vu(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Vu(n,r)},destroy(){n.remove()}}},kb=(e,t)=>{var I,P,N,L;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),u=n.createElement("div"),p=(P=(I=t==null?void 0:t.launcher)==null?void 0:I.enabled)==null||P?(L=(N=t==null?void 0:t.launcher)==null?void 0:N.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),r.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),yr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Ju(a,i,d,l,u,t,p)}),f.observe(a))},x=()=>{Ju(a,i,d,l,u,t,p),v()},E=a.ownerDocument.defaultView,A=()=>{x()};return E==null||E.addEventListener("resize",A),yr(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(w){let W=w.launcherEnabled?w.open:!0;p!==W&&(p=W,x())},updateConfig(w){var W,F;t=w,((F=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)!=null?F:!0)===!1&&(p=!0),x()},destroy(){E==null||E.removeEventListener("resize",A),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ui=(e,t)=>an(t)?kb(e,t):Mb(e,t);var hl={},Lb=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Pb=()=>{try{if(typeof hl!="undefined"&&hl.url)return new URL("../widget.css",hl.url).href}catch{}return null},Gu=(e,t)=>{let n=Pb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Xu=e=>{var E;let t=Lb(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=ui(t,s),a,i=[],d=(A,I)=>{var w,W;let N=!((W=(w=I==null?void 0:I.launcher)==null?void 0:w.enabled)!=null?W:!0)||an(I),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),N&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),n){let F=A.attachShadow({mode:"open"});F.appendChild(L),Gu(F,r)}else A.appendChild(L),Gu(A,r);return t.id&&L.setAttribute("data-persona-instance",t.id),L},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let A=d(o.host,s);a=pl(A,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(A=>A()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=A=>{f(),o.destroy(),o=ui(t,A),s=A,p()},v={update(A){var W,F,_,B,j,q;let I={...s,...A,launcher:{...(W=s==null?void 0:s.launcher)!=null?W:{},...(F=A==null?void 0:A.launcher)!=null?F:{},dock:{...(B=(_=s==null?void 0:s.launcher)==null?void 0:_.dock)!=null?B:{},...(q=(j=A==null?void 0:A.launcher)==null?void 0:j.dock)!=null?q:{}}}},P=an(s),N=an(I),L=to(s),w=to(I);if(P!==N||L!==w){m(I);return}s=I,o.updateConfig(s),a.update(A),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(A,I,P){if(I==="host")return o.host;if(I in A)return Reflect.get(A,I,P);let N=a[I];return typeof N=="function"?N.bind(a):N}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var tm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Ib=new Set(["button","a","input","select","textarea","details","summary"]),Wb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),yl=/\b(product|card|item|listing|result)\b/i,xl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Rb=3e3,Hb=100;function nm(e){let t=typeof e.className=="string"?e.className:"";if(yl.test(t)||e.id&&yl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&yl.test(r.value))return!0}return!1}function rm(e){var t;return xl.test(((t=e.textContent)!=null?t:"").trim())}function om(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Bb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Qu(e){let t=e.match(xl);return t?t[0]:null}function Yu(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Db(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var Nb="commerce-card",Ob="result-card";function Zu(e){return!nm(e)||!rm(e)||!om(e)&&!Bb(e)?0:5200}function em(e){var r;return!nm(e)||rm(e)||!om(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var sm=[{id:Nb,scoreElement(e){return Zu(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||xl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,u;if(Zu(e)===0)return null;let{title:n,href:r}=Yu(e),s=(u=(l=Qu(((d=e.textContent)!=null?d:"").trim()))!=null?l:Qu(t.text))!=null?u:"",o=Db(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
+ `)}},{id:Ob,scoreElement(e){return em(e)},formatSummary(e,t){if(em(e)===0)return null;let{title:n,href:r}=Yu(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
+ `)}}];function Fb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function _b(e){var u,p,f,m,v,x,E,A,I,P,N,L,w;let t=(u=e.options)!=null?u:{},n=(f=(p=t.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(v=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(E=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?E:200,o=(I=(A=t.visibleOnly)!=null?A:e.visibleOnly)!=null?I:!0,a=(P=t.root)!=null?P:e.root,i=(N=t.mode)!=null?N:"structured",d=(L=t.maxCandidates)!=null?L:Math.max(500,n*10),l=(w=e.rules)!=null?w:sm;return i==="simple"&&e.rules&&e.rules.length>0?(Fb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function bl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var $b=["data-testid","data-product","data-action","data-id","data-name","data-type"];function jb(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Ib.has(t)||n&&Wb.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function am(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Ub(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function im(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${bl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of $b){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${bl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>bl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function qb(e){return e==="static"?Hb:Rb}function lm(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:im(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:jb(e),attributes:Ub(e)}}function zb(e,t,n,r){let s=qb(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Vb(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function Kb(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(tm.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!am(l)){i=a.nextNode();continue}let p=lm(l,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(E=>E==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:v,formattingRule:x}=zb(l,p,e.rules,n);s.push({el:l,domIndex:o,enriched:p,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;Vb(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,n);m&&(u=m)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function Jb(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(tm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!am(d)){o=s.nextNode();continue}let u=lm(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),n.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Gb(e={}){var r;let t=_b(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Jb(t,n):Kb(t,n):[]}var mi=100;function Xb(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
110
110
  ${a.map(i=>`- ${i.split(`
111
111
  `).join(`
112
112
  `)}`).join(`
113
- `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,ci)}" (clickable)`);r.push(`Interactive elements:
113
+ `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,mi)}" (clickable)`);r.push(`Interactive elements:
114
114
  ${a.join(`
115
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,ci)}" (navigable)`);r.push(`Navigation links:
115
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,mi)}" (navigable)`);r.push(`Navigation links:
116
116
  ${a.join(`
117
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,ci)}" (input)`);r.push(`Form inputs:
117
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,mi)}" (input)`);r.push(`Form inputs:
118
118
  ${a.join(`
119
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,ci)}"`);r.push(`Content:
119
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,mi)}"`);r.push(`Content:
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
123
- `)}var em={name:"@runtypelabs/persona",version:"3.22.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var ts=em.version;function Hr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function Ib(e){if(e)return{getHeaders:Hr(e.getHeaders),onFeedback:Hr(e.onFeedback),onCopy:Hr(e.onCopy),requestMiddleware:Hr(e.requestMiddleware),actionHandlers:Hr(e.actionHandlers),actionParsers:Hr(e.actionParsers),postprocessMessage:Hr(e.postprocessMessage),contextProviders:Hr(e.contextProviders),streamParser:Hr(e.streamParser)}}var tm=`({ text, message }: any) => {
123
+ `)}var cm={name:"@runtypelabs/persona",version:"3.23.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --minify --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --minify --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run",size:"size-limit"},dependencies:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@size-limit/file":"^12.1.0","@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5","size-limit":"^12.1.0",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var os=cm.version;function Or(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Yb(e){if(e)return{getHeaders:Or(e.getHeaders),onFeedback:Or(e.onFeedback),onCopy:Or(e.onCopy),requestMiddleware:Or(e.requestMiddleware),actionHandlers:Or(e.actionHandlers),actionParsers:Or(e.actionParsers),postprocessMessage:Or(e.postprocessMessage),contextProviders:Or(e.contextProviders),streamParser:Or(e.streamParser)}}var dm=`({ text, message }: any) => {
124
124
  const jsonSource = (message as any).rawContent || text || message.content;
125
125
  if (!jsonSource || typeof jsonSource !== 'string') return null;
126
126
  let cleanJson = jsonSource
@@ -133,7 +133,7 @@ ${a.join(`
133
133
  if (parsed.action) return { type: parsed.action, payload: parsed };
134
134
  } catch (e) { return null; }
135
135
  return null;
136
- }`,nm=`function(ctx) {
136
+ }`,pm=`function(ctx) {
137
137
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
138
138
  if (!jsonSource || typeof jsonSource !== 'string') return null;
139
139
  var cleanJson = jsonSource
@@ -146,7 +146,7 @@ ${a.join(`
146
146
  if (parsed.action) return { type: parsed.action, payload: parsed };
147
147
  } catch (e) { return null; }
148
148
  return null;
149
- }`,rm=`(action: any, context: any) => {
149
+ }`,um=`(action: any, context: any) => {
150
150
  if (action.type !== 'nav_then_click') return;
151
151
  const payload = action.payload || action.raw || {};
152
152
  const url = payload?.page;
@@ -163,7 +163,7 @@ ${a.join(`
163
163
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
164
164
  window.location.href = targetUrl;
165
165
  return { handled: true, displayText: text };
166
- }`,om=`function(action, context) {
166
+ }`,mm=`function(action, context) {
167
167
  if (action.type !== 'nav_then_click') return;
168
168
  var payload = action.payload || action.raw || {};
169
169
  var url = payload.page;
@@ -180,26 +180,26 @@ ${a.join(`
180
180
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
181
181
  window.location.href = targetUrl;
182
182
  return { handled: true, displayText: text };
183
- }`,Wb=`(parsed: any) => {
183
+ }`,Zb=`(parsed: any) => {
184
184
  if (!parsed || typeof parsed !== 'object') return null;
185
185
  if (parsed.action === 'nav_then_click') return 'Navigating...';
186
186
  if (parsed.action === 'message') return parsed.text || '';
187
187
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
188
188
  return parsed.text || null;
189
- }`,Rb=`function(parsed) {
189
+ }`,ex=`function(parsed) {
190
190
  if (!parsed || typeof parsed !== 'object') return null;
191
191
  if (parsed.action === 'nav_then_click') return 'Navigating...';
192
192
  if (parsed.action === 'message') return parsed.text || '';
193
193
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
194
194
  return parsed.text || null;
195
- }`;function Hb(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function di(e){var n,t;return(t=(n=e.parserType)!=null?n:Hb(e.streamParser))!=null?t:"plain"}function pi(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function ui(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function mi(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function gi(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${n} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${n} ${d}: ${l},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function fl(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function sm(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),sm(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function ao(e,n,t,r){t&&(e.push(`${r}${n}: {`),sm(e,t,`${r} `),e.push(`${r}},`))}function Bb(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:Ib(t.hooks)}:void 0;return n==="esm"?Db(r,s):n==="script-installer"?Fb(r,s):n==="script-advanced"?_b(r,s):n==="react-component"?Nb(r,s):n==="react-advanced"?Ob(r,s):$b(r,s)}function Db(e,n){let t=n==null?void 0:n.hooks,r=di(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...pi(e," ")),o.push(...ui(e," ",t)),o.push(...mi(e," ")),o.push(...gi(e," ")),o.push(...fl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
196
- `)}function Nb(e,n){let t=n==null?void 0:n.hooks,r=di(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...pi(e," ")),o.push(...ui(e," ",t)),o.push(...mi(e," ")),o.push(...gi(e," ")),o.push(...fl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
197
- `)}function Ob(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(r,"theme",e.theme," "),e.launcher&&ao(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...pi(e," ")),r.push(...ui(e," ",t)),r.push(...mi(e," ")),r.push(...gi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Wb}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${tm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${tm}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${rm}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${rm}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
198
- `)}function am(e){var s;let n=di(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function Fb(e,n){let t=am(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/install.global.js" data-config='${s}'></script>`}function $b(e,n){let t=n==null?void 0:n.hooks,r=di(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...pi(e," ")),o.push(...ui(e," ",t)),o.push(...mi(e," ")),o.push(...gi(e," ")),o.push(...fl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
199
- `)}function _b(e,n){let t=n==null?void 0:n.hooks,r=am(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
195
+ }`;function tx(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function gi(e){var t,n;return(n=(t=e.parserType)!=null?t:tx(e.streamParser))!=null?n:"plain"}function fi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&n.push(`${t} ${r}: "${s}",`)}),n.push(`${t}},`)),n}function hi(e,t,n){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(s||o)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function yi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function bi(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${o}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${o}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function vl(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function gm(e,t,n){Object.entries(t).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${r}: {`),gm(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(s)},`)}})}function lo(e,t,n,r){n&&(e.push(`${r}${t}: {`),gm(e,n,`${r} `),e.push(`${r}},`))}function nx(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=n?{...n,hooks:Yb(n.hooks)}:void 0;return t==="esm"?rx(r,s):t==="script-installer"?ax(r,s):t==="script-advanced"?lx(r,s):t==="react-component"?ox(r,s):t==="react-advanced"?sx(r,s):ix(r,s)}function rx(e,t){let n=t==null?void 0:t.hooks,r=gi(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&lo(o,"theme",e.theme," "),e.launcher&&lo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...fi(e," ")),o.push(...hi(e," ",n)),o.push(...yi(e," ")),o.push(...bi(e," ")),o.push(...vl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
196
+ `)}function ox(e,t){let n=t==null?void 0:t.hooks,r=gi(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&lo(o,"theme",e.theme," "),e.launcher&&lo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...fi(e," ")),o.push(...hi(e," ",n)),o.push(...yi(e," ")),o.push(...bi(e," ")),o.push(...vl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
197
+ `)}function sx(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&lo(r,"theme",e.theme," "),e.launcher&&lo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...fi(e," ")),r.push(...hi(e," ",n)),r.push(...yi(e," ")),r.push(...bi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Zb}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${dm}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${dm}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${um}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${um}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
198
+ `)}function fm(e){var s;let t=gi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function ax(e,t){let n=fm(e),r=t!=null&&t.windowKey?{config:n,windowKey:t.windowKey}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/install.global.js" data-config='${s}'></script>`}function ix(e,t){let n=t==null?void 0:t.hooks,r=gi(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&lo(o,"theme",e.theme," "),e.launcher&&lo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...fi(e," ")),o.push(...hi(e," ",n)),o.push(...yi(e," ")),o.push(...bi(e," ")),o.push(...vl(n," ")),e.debug&&o.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
199
+ `)}function lx(e,t){let n=t==null?void 0:t.hooks,r=fm(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
200
200
  `).map((a,i)=>i===0?a:" "+a).join(`
201
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${Rb});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${nm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${nm}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${om}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${om}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
202
- `)}var im={desktop:{w:1280,h:800},mobile:{w:390,h:844}},lm=.1,cm=.15,dm=1.5,hl=24,pm=40,jb=`
201
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${os}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(o.push(` widgetConfig.getHeaders = ${n.getHeaders};`),o.push("")),n!=null&&n.contextProviders&&(o.push(` widgetConfig.contextProviders = ${n.contextProviders};`),o.push("")),n!=null&&n.streamParser?o.push(` widgetConfig.streamParser = ${n.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${ex});`),o.push(" };")),o.push(""),n!=null&&n.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${n.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${pm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${pm}`),o.push(" ];")),o.push(""),n!=null&&n.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${n.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${mm}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${mm}`),o.push(" ];")),o.push(""),n!=null&&n.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${n.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),n!=null&&n.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
202
+ `)}var hm={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ym=.1,bm=.15,xm=1.5,wl=24,vm=40,cx=`
203
203
  /* \u2500\u2500 Root \u2500\u2500 */
204
204
  .persona-dc-root {
205
205
  display: flex;
@@ -350,7 +350,7 @@ ${a.join(`
350
350
  .persona-dc-stage {
351
351
  height: 550px;
352
352
  min-height: 400px;
353
- padding: ${hl}px;
353
+ padding: ${wl}px;
354
354
  overflow: auto;
355
355
  background: #f0f1f3;
356
356
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -440,5 +440,5 @@ ${a.join(`
440
440
  min-height: 300px;
441
441
  }
442
442
  }
443
- `;function Ub(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=jb,document.head.appendChild(e)}function qb(e,n){let t=e.clientWidth-hl*2-pm,r=e.clientHeight-hl*2-pm;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function zb(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function Vb(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Ub();let u=Math.max(0,Math.min(r,t.length-1)),p=s,f=o,m=null,v=1,x=!1,S=h("div","persona-dc-root"),A=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),R=h("div","persona-dc-toolbar-trail"),H=_t({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Re(-1)}),L=h("div");L.style.position="relative";let w=h("button","persona-dc-title-btn");w.type="button",w.setAttribute("aria-expanded","false"),w.setAttribute("aria-haspopup","listbox");let B=h("span","persona-dc-title-text"),F=h("span","persona-dc-title-chevron"),$=fe("chevron-down",12,"currentColor",2);$&&F.appendChild($),w.append(B,F);let W=h("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let O=!1;function V(){W.innerHTML="";for(let J=0;J<t.length;J++){let z=t[J],we=h("button","persona-dc-dropdown-item");we.type="button",we.setAttribute("role","option"),we.setAttribute("aria-current",J===u?"true":"false");let $e=h("span");if($e.textContent=z.title,we.appendChild($e),z.description){let ne=h("span","persona-dc-dropdown-desc");ne.textContent=z.description,we.appendChild(ne)}we.addEventListener("click",()=>{Ie(),tt(J)}),W.appendChild(we)}}function oe(){O=!O,W.style.display=O?"":"none",w.setAttribute("aria-expanded",O?"true":"false"),O&&V()}function Ie(){O&&(O=!1,W.style.display="none",w.setAttribute("aria-expanded","false"))}w.addEventListener("click",J=>{J.stopPropagation(),oe()});let Pe=()=>Ie();document.addEventListener("click",Pe),L.append(w,W);let ze=_t({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Re(1)}),pe=h("span","persona-dc-counter");k.append(H,L,ze,pe);let ce=null;i&&(ce=za({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:J=>{p=J,G.dataset.device=p,m=null,K()}}),R.appendChild(ce.element));let Ee=null;if(a){let J=h("div","persona-dc-zoom-controls"),z=_t({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ne=m!=null?m:v;m=Math.max(cm,ne-lm),K()}});Ee=h("span","persona-dc-zoom-level"),Ee.title="Reset to 100%",Ee.style.cursor="pointer",Ee.addEventListener("click",()=>{m=1,K()});let we=_t({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ne=m!=null?m:v;m=Math.min(dm,ne+lm),K()}}),$e=_t({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,K()}});J.append(z,Ee,we,$e),R.appendChild(J)}if(d){let J=h("div","persona-dc-separator");R.appendChild(J);let z=za({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:we=>{f=we,G.dataset.colorScheme=f,He()}});R.appendChild(z.element)}let je=h("div","persona-dc-separator");R.appendChild(je);let te=_t({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});R.appendChild(te),A.append(k,R);let xe=h("div","persona-dc-stage"),G=h("div","persona-dc-iframe-wrapper");G.dataset.device=p,G.dataset.colorScheme=f;let ae=h("iframe","persona-dc-iframe");ae.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ae.setAttribute("loading","lazy"),ae.title=t[u].title,G.appendChild(ae),xe.appendChild(G),S.append(A,xe),e.appendChild(S);function He(){var J;try{let z=(J=ae.contentDocument)==null?void 0:J.body;if(!z)return;f==="dark"?z.classList.add("theme-dark"):z.classList.remove("theme-dark")}catch{}}ae.addEventListener("load",()=>He());function ue(){let J=t[u];B.textContent=J.title,pe.textContent=`${u+1} / ${t.length}`,ae.title=J.title}function Re(J){let z=((u+J)%t.length+t.length)%t.length;tt(z)}function tt(J){J<0||J>=t.length||(u=J,ae.src=t[u].url,ue(),l==null||l(u,t[u]))}function K(){var we;if(x)return;let J=(we=im[p])!=null?we:im.desktop;v=qb(xe,J);let z=Math.max(cm,Math.min(dm,m!=null?m:v));zb(G,ae,J,z,p),Ee&&(Ee.textContent=`${Math.round(z*100)}%`)}let se=new ResizeObserver(()=>K());se.observe(xe),ue(),ae.src=t[u].url,requestAnimationFrame(()=>K());function Oe(){x||(x=!0,se.disconnect(),document.removeEventListener("click",Pe),S.remove())}return{element:S,goTo:tt,next:()=>Re(1),prev:()=>Re(-1),getIndex:()=>u,setDevice(J){p=J,G.dataset.device=J,ce==null||ce.setSelected(J),m=null,K()},setColorScheme(J){f=J,G.dataset.colorScheme=J},setZoom(J){m=J,K()},destroy:Oe}}function Kb(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Jb(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Gb(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:xr(e.colors.primary,.95),100:xr(e.colors.primary,.9),200:xr(e.colors.primary,.8),300:xr(e.colors.primary,.7),400:xr(e.colors.primary,.6),500:e.colors.primary,600:xr(e.colors.primary,.8),700:xr(e.colors.primary,.7),800:xr(e.colors.primary,.6),900:xr(e.colors.primary,.5),950:xr(e.colors.primary,.45)}}),{...n,palette:t}}}}function Xb(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Yb(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function xr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Qb(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Zb={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},um={components:{panel:{borderRadius:"0",shadow:"none"}}},mm={id:"shop",label:"Shopping Assistant",config:{theme:Zb,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},gm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:um}},fm={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:um}},hm={shop:mm,minimal:gm,fullscreen:fm};function ex(e){return hm[e]}var TA=_u;export{lu as ASK_USER_QUESTION_TOOL_NAME,_o as AgentWidgetClient,ks as AgentWidgetSession,qo as AttachmentManager,Hp as DEFAULT_COMPONENTS,Si as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Gn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Wp as DEFAULT_PALETTE,Rp as DEFAULT_SEMANTIC,Ft as DEFAULT_WIDGET_CONFIG,hm as PRESETS,fm as PRESET_FULLSCREEN,gm as PRESET_MINIMAL,mm as PRESET_SHOP,lh as THEME_ZONES,ts as VERSION,ya as WEBMCP_TOOL_PREFIX,As as WebMcpBridge,Kb as accessibilityPlugin,Jb as animationsPlugin,So as applyThemeVariables,Vo as attachHeaderToContainer,Gb as brandPlugin,js as buildComposer,Jp as buildDefaultHeader,eo as buildHeader,_s as buildHeaderWithLayout,Gp as buildMinimalHeader,kb as collectEnrichedPageContext,so as componentRegistry,si as createActionManager,al as createAgentExperience,wy as createAskUserQuestionBubble,Ai as createBestAvailableVoiceProvider,qh as createBubbleWithLayout,rl as createCSATFeedback,Hi as createComboButton,Xy as createComponentMiddleware,Zi as createComponentStreamParser,yp as createDefaultSanitizer,Vb as createDemoCarousel,vm as createDirectivePostprocessor,Eo as createDropdownMenu,Bm as createFlexibleJsonStreamParser,_t as createIconButton,zm as createImagePart,vi as createJsonStreamParser,qa as createLabelButton,Qi as createLocalStorageAdapter,fa as createMarkdownProcessor,Oo as createMarkdownProcessorFromConfig,ou as createMessageActions,ol as createNPSFeedback,bi as createPlainTextParser,Qb as createPlugin,xi as createRegexJsonParser,Us as createStandardBubble,Ta as createTextPart,Ps as createTheme,ki as createThemeObserver,za as createToggleGroup,Ko as createTypingIndicator,Uo as createVoiceProvider,li as createWidgetHostLayout,wi as createXmlParser,TA as default,Zo as defaultActionHandlers,oi as defaultJsonActionParser,Xu as defaultParseRules,Wa as detectColorScheme,wm as directivePostprocessor,zs as ensureAskUserQuestionSheet,Fo as escapeHtml,nl as extractComponentDirectiveFromMessage,Vm as fileToImagePart,Lb as formatEnrichedContext,jo as generateAssistantMessageId,Bb as generateCodeSnippet,$m as generateMessageId,Qu as generateStableSelector,Ts as generateUserMessageId,Is as getActiveTheme,Op as getColorScheme,jm as getDisplayText,Xp as getHeaderLayout,qm as getImageParts,ex as getPreset,tl as hasComponentDirective,Um as hasImages,Bi as headerLayouts,Yb as highContrastPlugin,_u as initAgentWidget,to as isAskUserQuestionMessage,Gy as isComponentDirectiveType,on as isDockedMountMode,Pa as isVoiceSupported,ba as isWebMcpToolName,bh as listRegisteredStreamAnimations,gp as markdownPostprocessor,Ei as mergeWithDefaults,_m as normalizeContent,no as parseAskUserQuestionPayload,ri as pluginRegistry,Xb as reducedMotionPlugin,hh as registerStreamAnimationPlugin,Mo as removeAskUserQuestionSheet,el as renderComponentDirective,ru as renderLoadingIndicatorWithFallback,fe as renderLucideIcon,lr as resolveDockConfig,Cs as resolveSanitizer,Ti as resolveTokens,bp as stripWebMcpPrefix,Mi as themeToCssVariables,yh as unregisterStreamAnimationPlugin,Km as validateImageFile,Bp as validateTheme};
443
+ `;function dx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=cx,document.head.appendChild(e)}function px(e,t){let n=e.clientWidth-wl*2-vm,r=e.clientHeight-wl*2-vm;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function ux(e,t,n,r,s){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function mx(e,t){let{items:n,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");dx();let u=Math.max(0,Math.min(r,n.length-1)),p=s,f=o,m=null,v=1,x=!1,E=h("div","persona-dc-root"),A=h("div","persona-dc-toolbar"),I=h("div","persona-dc-toolbar-lead"),P=h("div","persona-dc-toolbar-trail"),N=jt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>ue(-1)}),L=h("div");L.style.position="relative";let w=h("button","persona-dc-title-btn");w.type="button",w.setAttribute("aria-expanded","false"),w.setAttribute("aria-haspopup","listbox");let W=h("span","persona-dc-title-text"),F=h("span","persona-dc-title-chevron"),_=be("chevron-down",12,"currentColor",2);_&&F.appendChild(_),w.append(W,F);let B=h("div","persona-dc-dropdown");B.setAttribute("role","listbox"),B.style.display="none";let j=!1;function q(){B.innerHTML="";for(let ge=0;ge<n.length;ge++){let ie=n[ge],ae=h("button","persona-dc-dropdown-item");ae.type="button",ae.setAttribute("role","option"),ae.setAttribute("aria-current",ge===u?"true":"false");let Qe=h("span");if(Qe.textContent=ie.title,ae.appendChild(Qe),ie.description){let Ce=h("span","persona-dc-dropdown-desc");Ce.textContent=ie.description,ae.appendChild(Ce)}ae.addEventListener("click",()=>{Ie(),Ge(ge)}),B.appendChild(ae)}}function re(){j=!j,B.style.display=j?"":"none",w.setAttribute("aria-expanded",j?"true":"false"),j&&q()}function Ie(){j&&(j=!1,B.style.display="none",w.setAttribute("aria-expanded","false"))}w.addEventListener("click",ge=>{ge.stopPropagation(),re()});let Re=()=>Ie();document.addEventListener("click",Re),L.append(w,B);let Ne=jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ue(1)}),ce=h("span","persona-dc-counter");I.append(N,L,Ne,ce);let ve=null;i&&(ve=Ja({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:ge=>{p=ge,V.dataset.device=p,m=null,z()}}),P.appendChild(ve.element));let Me=null;if(a){let ge=h("div","persona-dc-zoom-controls"),ie=jt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Ce=m!=null?m:v;m=Math.max(bm,Ce-ym),z()}});Me=h("span","persona-dc-zoom-level"),Me.title="Reset to 100%",Me.style.cursor="pointer",Me.addEventListener("click",()=>{m=1,z()});let ae=jt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Ce=m!=null?m:v;m=Math.min(xm,Ce+ym),z()}}),Qe=jt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,z()}});ge.append(ie,Me,ae,Qe),P.appendChild(ge)}if(d){let ge=h("div","persona-dc-separator");P.appendChild(ge);let ie=Ja({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ae=>{f=ae,V.dataset.colorScheme=f,fe()}});P.appendChild(ie.element)}let Le=h("div","persona-dc-separator");P.appendChild(Le);let ne=jt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});P.appendChild(ne),A.append(I,P);let ke=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=p,V.dataset.colorScheme=f;let pe=h("iframe","persona-dc-iframe");pe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),pe.setAttribute("loading","lazy"),pe.title=n[u].title,V.appendChild(pe),ke.appendChild(V),E.append(A,ke),e.appendChild(E);function fe(){var ge;try{let ie=(ge=pe.contentDocument)==null?void 0:ge.body;if(!ie)return;f==="dark"?ie.classList.add("theme-dark"):ie.classList.remove("theme-dark")}catch{}}pe.addEventListener("load",()=>fe());function me(){let ge=n[u];W.textContent=ge.title,ce.textContent=`${u+1} / ${n.length}`,pe.title=ge.title}function ue(ge){let ie=((u+ge)%n.length+n.length)%n.length;Ge(ie)}function Ge(ge){ge<0||ge>=n.length||(u=ge,pe.src=n[u].url,me(),l==null||l(u,n[u]))}function z(){var ae;if(x)return;let ge=(ae=hm[p])!=null?ae:hm.desktop;v=px(ke,ge);let ie=Math.max(bm,Math.min(xm,m!=null?m:v));ux(V,pe,ge,ie,p),Me&&(Me.textContent=`${Math.round(ie*100)}%`)}let te=new ResizeObserver(()=>z());te.observe(ke),me(),pe.src=n[u].url,requestAnimationFrame(()=>z());function We(){x||(x=!0,te.disconnect(),document.removeEventListener("click",Re),E.remove())}return{element:E,goTo:Ge,next:()=>ue(1),prev:()=>ue(-1),getIndex:()=>u,setDevice(ge){p=ge,V.dataset.device=ge,ve==null||ve.setSelected(ge),m=null,z()},setColorScheme(ge){f=ge,V.dataset.colorScheme=ge},setZoom(ge){m=ge,z()},destroy:We}}function gx(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function fx(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function hx(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Er(e.colors.primary,.95),100:Er(e.colors.primary,.9),200:Er(e.colors.primary,.8),300:Er(e.colors.primary,.7),400:Er(e.colors.primary,.6),500:e.colors.primary,600:Er(e.colors.primary,.8),700:Er(e.colors.primary,.7),800:Er(e.colors.primary,.6),900:Er(e.colors.primary,.5),950:Er(e.colors.primary,.45)}}),{...t,palette:n}}}}function yx(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function bx(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Er(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function xx(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var vx={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},wm={components:{panel:{borderRadius:"0",shadow:"none"}}},Cm={id:"shop",label:"Shopping Assistant",config:{theme:vx,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:sr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Am={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:wm}},Sm={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:wm}},Em={shop:Cm,minimal:Am,fullscreen:Sm};function wx(e){return Em[e]}var GA=Xu;export{gu as ASK_USER_QUESTION_TOOL_NAME,qo as AgentWidgetClient,Is as AgentWidgetSession,Ko as AttachmentManager,_p as DEFAULT_COMPONENTS,ki as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Op as DEFAULT_PALETTE,Fp as DEFAULT_SEMANTIC,Ot as DEFAULT_WIDGET_CONFIG,Em as PRESETS,Sm as PRESET_FULLSCREEN,Am as PRESET_MINIMAL,Cm as PRESET_SHOP,yh as THEME_ZONES,os as VERSION,va as WEBMCP_TOOL_PREFIX,Ts as WebMcpBridge,gx as accessibilityPlugin,fx as animationsPlugin,Eo as applyThemeVariables,Go as attachHeaderToContainer,hx as brandPlugin,zs as buildComposer,eu as buildDefaultHeader,no as buildHeader,qs as buildHeaderWithLayout,tu as buildMinimalHeader,Gb as collectEnrichedPageContext,io as componentRegistry,ci as createActionManager,pl as createAgentExperience,Py as createAskUserQuestionBubble,Mi as createBestAvailableVoiceProvider,Zh as createBubbleWithLayout,ll as createCSATFeedback,Oi as createComboButton,yb as createComponentMiddleware,ol as createComponentStreamParser,Ap as createDefaultSanitizer,mx as createDemoCarousel,Lm as createDirectivePostprocessor,To as createDropdownMenu,qm as createFlexibleJsonStreamParser,jt as createIconButton,eg as createImagePart,Si as createJsonStreamParser,Ka as createLabelButton,rl as createLocalStorageAdapter,ba as createMarkdownProcessor,$o as createMarkdownProcessorFromConfig,du as createMessageActions,cl as createNPSFeedback,Ci as createPlainTextParser,xx as createPlugin,Ai as createRegexJsonParser,Vs as createStandardBubble,La as createTextPart,Rs as createTheme,Wi as createThemeObserver,Ja as createToggleGroup,Xo as createTypingIndicator,Vo as createVoiceProvider,ui as createWidgetHostLayout,Ei as createXmlParser,GA as default,ns as defaultActionHandlers,li as defaultJsonActionParser,sm as defaultParseRules,Ba as detectColorScheme,Pm as directivePostprocessor,Js as ensureAskUserQuestionSheet,jo as escapeHtml,il as extractComponentDirectiveFromMessage,tg as fileToImagePart,Xb as formatEnrichedContext,zo as generateAssistantMessageId,nx as generateCodeSnippet,Gm as generateMessageId,im as generateStableSelector,Ls as generateUserMessageId,Hs as getActiveTheme,qp as getColorScheme,Qm as getDisplayText,nu as getHeaderLayout,Zm as getImageParts,wx as getPreset,al as hasComponentDirective,Ym as hasImages,Fi as headerLayouts,bx as highContrastPlugin,Xu as initAgentWidget,ro as isAskUserQuestionMessage,hb as isComponentDirectiveType,an as isDockedMountMode,Ra as isVoiceSupported,wa as isWebMcpToolName,Mh as listRegisteredStreamAnimations,vp as markdownPostprocessor,Li as mergeWithDefaults,Xm as normalizeContent,oo as parseAskUserQuestionPayload,ii as pluginRegistry,yx as reducedMotionPlugin,Eh as registerStreamAnimationPlugin,ko as removeAskUserQuestionSheet,sl as renderComponentDirective,cu as renderLoadingIndicatorWithFallback,be as renderLucideIcon,yr as resolveDockConfig,Es as resolveSanitizer,Pi as resolveTokens,Sp as stripWebMcpPrefix,Ii as themeToCssVariables,Th as unregisterStreamAnimationPlugin,ng as validateImageFile,$p as validateTheme};
444
444
  //# sourceMappingURL=index.js.map