@runtypelabs/persona 3.23.0 → 3.24.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 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?`
1
+ import{Marked as km}from"marked";var Lm=e=>{if(e)return e},ya=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new km({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=Lm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},$o=e=>e?ya({markedOptions:e.options,renderer:e.renderer}):ya(),Pm=ya(),vp=e=>Pm(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,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=xp(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=xp(n.length);return n.push({token:o,type:s}),o}),t},Im=e=>{let n=$o(e);return t=>{let r=[],s=Cp(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="${wp(i)}"></div>`;o=o.replace(d,u)}),o}},Wm=e=>{let n=[],t=Cp(e,n),r=vp(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="${wp(o)}"></div>`;r=r.replace(a,d)}),r};import Rm from"dompurify";var Hm={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"]},Bm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ap=()=>{let e=Rm(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:")&&!Bm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,Hm)},Ts=e=>e===!1?null:typeof e=="function"?e:Ap();var va="webmcp:",xa={warn(e,...n){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...n)}};function Tp(e){if(e.length===0)return"0:empty";let n=e.map(t=>{var r,s;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(s=t.origin)!=null?s:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${e.length}:${Dm(n.join(""))}`}function Sp(e,n){let t=3735928559^n,r=1103547991^n;for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);t=Math.imul(t^o,2654435761),r=Math.imul(r^o,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Dm(e){let n=Sp(e,0).toString(36),t=Sp(e,2654435761).toString(36);return`${n}.${t}`}var Es=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 xa.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=Om(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(n,t,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=Ep(n),a;try{a=await s.getTools()}catch(m){let x=m instanceof Error?m.message:String(m);return hr(`Failed to read WebMCP registry: ${x}`)}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:t,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,jm(t),{signal:l.signal});return Fm(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 x=m instanceof Error?m.message:String(m);return hr(x)}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){xa.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,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):n}async requestConfirm(n){var r;let t=(r=this.confirmHandler)!=null?r:_m;try{return await t(n)}catch(s){return xa.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=>Nm(n,r))}},Ep=e=>e.startsWith(va)?e.slice(va.length):e,wa=e=>e.startsWith(va),Nm=(e,n)=>{if(n==="*")return!0;let t=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)},Om=e=>{if(!(e===void 0||e===""))try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:void 0}catch{return}},Fm=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:Um(n)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),_m=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let n=$m(e.args),t=`Allow the AI to call ${e.toolName}`+(n?`
2
2
 
3
3
  Arguments:
4
- ${t}`:"")+(e.description?`
4
+ ${n}`:"")+(e.description?`
5
5
 
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,`
6
+ ${e.description}`:"");return window.confirm(t)},$m=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)}},jm=e=>{if(e===void 0)return"{}";try{let n=JSON.stringify(e);return n===void 0?"{}":n}catch{return"{}"}},Um=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Mp,STR as kp,OBJ as Lp}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)}},qm=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`},Pp=e=>e.status==="complete"?qm(e):e.status==="pending"?"Waiting":"",zm=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 Ip=e=>e.status==="complete"?zm(e):"Using tool...",Aa=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},ks=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 Aa(n)},Sa=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 Aa(n)},wi=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=ks(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ta=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Ms(r,t.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<t.length&&Ms(r,t.slice(o),[]),r},Ms=(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})},Vm=()=>{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,`
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<=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(`
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()=>{}}},Ao=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Ci=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ai=()=>{var n;let e=Vm();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)}},Si=()=>{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=Mp(t,kp|Lp);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 n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Km=e=>{let n=null,t=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:()=>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=Mp(o,kp|Lp),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},Ti=()=>{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 Ea=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 Jm="https://api.runtype.com/v1/dispatch",Ma="https://api.runtype.com";function Gm(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 Ei=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 Xm(e){switch(e){case"json":return Si;case"regex-json":return Ai;case"xml":return Ti;default:return Ci}}var Wp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Qm(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=Wp(t);if(!Wp(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Ao(e);return Ao(n)!==null&&a===null?n:e}var qo=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,s,o;this.apiUrl=(t=n.apiUrl)!=null?t:Jm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Xm(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 Es(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$/,""))||Ma}/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,this.resetClientToolsFingerprint(),(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,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ma}/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.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let I=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:I}),I}let l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(Ei).map(I=>{var L,w,R;return{id:I.id,role:I.role,content:(R=(w=(L=I.contentParts)!=null?L:I.llmContent)!=null?w:I.rawContent)!=null?R:I.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}},f=l.clientTools,m=!!(f&&f.length>0),x=m?Tp(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&v&&this.lastSentClientToolsFingerprint===x,A=!1,W=null,P;for(let I=0;;I++){let w={...p,...m&&(A||!T)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:r.signal}),P.status===409&&I===0&&m){let R=await P.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){A=!0,this.lastSentClientToolsFingerprint=null;continue}W=R!=null?R:{error:"Chat request failed"}}break}if(!P.ok){let I=W!=null?W:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:w}),w}if(P.status===429){let w=new Error(I.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let L=new Error(I.error||"Failed to send message");throw t({type:"error",error:L}),L}if(!P.body){let I=new Error("No response body received");throw t({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(P.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$/,""))||Ma}/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(/\/+$/,""))||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: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(Ei).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(Ei).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 Dt,ln,Hn,Xn;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=B=>{let oe=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,Be=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Xe=B.tools?B.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...B,reasoning:oe,toolCall:Be,tools:Xe}},p=B=>{t({type:"message",message:u(B)})},f=null,m=null,x={current:null},v={current:null},T=!1,A=new Map,W=new Map,P=new Map,I=new Map,L={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},R=(B,oe,Be="")=>`${B}::${oe}::${Be}`,F=(B,oe)=>`${B}::${oe}::`,_=(B,oe,Be,Xe)=>{let Fe=R(B,oe,Be),_e=P.get(Fe);if(_e)return _e;let rt=Be?`-${Be}`:"",At={id:`nested-${B}-${oe}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:Xe,parentToolId:B,parentStepId:oe}};return P.set(Fe,At),p(At),At},D=B=>{if(B==null)return null;try{return String(B)}catch{return null}},j=B=>{var oe,Be,Xe,Fe,_e;return D((_e=(Fe=(Xe=(Be=(oe=B.stepId)!=null?oe:B.step_id)!=null?Be:B.step)!=null?Xe:B.parentId)!=null?Fe:B.flowStepId)!=null?_e:B.flow_step_id)},q=B=>{var oe,Be,Xe,Fe,_e,rt,At;return D((At=(rt=(_e=(Fe=(Xe=(Be=(oe=B.callId)!=null?oe:B.call_id)!=null?Be:B.requestId)!=null?Xe:B.request_id)!=null?Fe:B.toolCallId)!=null?_e:B.tool_call_id)!=null?rt:B.stepId)!=null?At:B.step_id)},re=r,Ie=!1,Re=()=>{if(f)return f;let B;return!Ie&&re?(B=re,Ie=!0):re&&v.current?B=`${re}_${v.current}`:B=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:B,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Ne=(B,oe)=>{L.lastId=oe,B&&L.byStep.set(B,oe)},ce=(B,oe)=>{var _e;let Be=(_e=B.reasoningId)!=null?_e:B.id,Xe=j(B);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=B=>{let oe=A.get(B);if(oe)return oe;let Be={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:B,status:"streaming",chunks:[]}};return A.set(B,Be),p(Be),Be},Me=(B,oe)=>{w.lastId=oe,B&&w.byCall.set(B,oe)},Le=new Set,ne=new Map,ke=new Set,V=new Map,pe=B=>{if(!B)return!1;let oe=B.replace(/_+/g,"_").replace(/^_|_$/g,"");return oe==="emit_artifact_markdown"||oe==="emit_artifact_component"},fe=(B,oe)=>{var _e;let Be=(_e=B.toolId)!=null?_e:B.id,Xe=q(B);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=B=>{let oe=W.get(B);if(oe)return oe;let Be={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:B,status:"pending"}};return W.set(B,Be),p(Be),Be},ue=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let oe=Number(B);if(!Number.isNaN(oe)&&Number.isFinite(oe))return oe;let Be=Date.parse(B);if(!Number.isNaN(Be))return Be}return Date.now()},Ge=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},z=new Map,te=new Map,We=new Map,ge=new Map,ie=null,ae=(B,oe,Be)=>{var At;let Xe=We.get(B);Xe||(Xe=[],We.set(B,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=(B,oe)=>{let Be=Ge(oe),Xe=te.get(B.id),Fe=Qm(Xe,Be);B.rawContent=Fe;let _e=z.get(B.id),rt=gt=>{var Ut;let nt=(Ut=B.content)!=null?Ut:"";gt.trim()!==""&&(nt.trim().length===0||gt.startsWith(nt)||gt.trimStart().startsWith(nt.trim()))&&(B.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(B.id),te.delete(B.id),B.streaming=!1,p(B)};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 Ea((B,oe)=>{Ce.push({payloadType:B,payload:oe}),$e()}),G=null,Oe=new Map,Mn=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(X=()=>{var B,oe,Be,Xe,Fe,_e,rt,At,Ft,Kt,K,gt,nt,Ut,se,be,wt,_t,Zt,bn,Et,St,ht,yt,qt,et,Bn,Qn,yn,Dn,ut,xr,Nn,co,kn,Po,Fr,Er,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,bs,ys,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 $=(B=ce(C,!0))!=null?B:`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=(be=ce(C,!1))!=null?be: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,((bn=M.reasoning.completedAt)!=null?bn:Date.now())-Z),M.streaming=!1,p(M)}let Y=j(C);Y&&L.byStep.delete(Y)}else if(Ue==="tool_start"){let $=(Et=fe(C,!0))!=null?Et:`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((yt=C.startedAt)!=null?yt: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 $=(yn=(Qn=fe(C,!1))!=null?Qn:fe(C,!0))!=null?yn:`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:(Er=J==null?void 0:J.iteration)!=null?Er: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&&v.current!==null&&$!==v.current){let M=f;M&&(M.streaming=!1,p(M),ie=M,f=null,T=!0)}$!==void 0&&(v.current=$)}else if(Ue==="text_end"){if((lr=C.toolContext)!=null&&lr.toolId)continue;let $=f;$&&($.streaming=!1,p($),ie=$,f=null,T=!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=I.get(Ve);if(at!==""&&Ke!==void 0&&Ke!==""&&Ke!==at){let Tt=P.get(R(Y.toolId,De,Ke));Tt&&Tt.streaming!==!1&&(Tt.streaming=!1,p(Tt))}at!==""&&I.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&&v.current!==null&&Z!==v.current){let De=f;De&&(De.streaming=!1,p(De),ie=De,f=null,T=!0)}Z!==void 0&&(v.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 Tt=Ke.processChunk(Ve);if(Tt instanceof Promise)Tt.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 Tt=="string"?Tt:(wr=Tt==null?void 0:Tt.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 Tt=Ke.processChunk(Ve);Tt instanceof Promise?(Xt=!0,Tt.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 Tt=="string"?Tt:(ur=Tt==null?void 0:Tt.text)!=null?ur:null}if(!Xt){Ye!==null&&Ye.trim()!==""?J.content=Ye:te.has(J.id)||(J.content=Ge(De));let Tt=z.get(J.id);if(Tt){let kt=(mr=Tt.close)==null?void 0:mr.call(Tt);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));I.delete(`${Y.toolId}::${De}`)}continue}let Z=C.stopReason;if(T){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 Tt=Ao(Xt);if(Tt!==null)qe.content=Tt,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(T){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 Tt=typeof Xt=="string"?Xt:(kt=Xt==null?void 0:Xt.text)!=null?kt:null;Tt!==null&&(M.content=Tt,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))}t({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=W.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=W.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=W.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:Gm(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,x.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($)),t({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:",$):t({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:(ys=(bs=C.executionId)!=null?bs:G==null?void 0:G.executionId)!=null?ys:"",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(t({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:"");t({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:{};t({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ue==="artifact_complete"){let $=String(C.id);t({type:"artifact_complete",id:$});let 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,x.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($){t({type:"error",error:$});let M=f;M&&M.streaming&&(M.streaming=!1,p(M)),t({type:"status",status:"idle"})}}}}}Ce.length=0};;){let{done:B,value:oe}=await s.read();if(B)break;a+=o.decode(oe,{stream:!0});let Be=a.split(`
10
10
 
11
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}
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){t({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){x.current=f;let Kt=await this.handleCustomSSEEvent(At,t,x,p,l,v);if(x.current&&x.current!==f&&(f=x.current),Kt)continue}Ct.push(Ft,At),X()}}Ct.flushPending(),X(),Ct.destroy()}};function Ym(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ls(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function zo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var ka="[Image]";function Zm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function eg(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function tg(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function ng(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function La(e){return{type:"text",text:e}}function rg(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 og(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 sg(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 Rp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ag=["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=[...Rp,...ag];function ig(e){return Rp.includes(e)||e.startsWith("image/")}function Pa(e){return ig(e.type)}async function Hp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Pa(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 Bp(e,n=Nr,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 lg(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Dp(e,n){let t=lg(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 Ia=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 Wa=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 Ps=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 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(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 x=!1,v=A=>{x||(x=!0,clearTimeout(T),m(new Error(A)))},T=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(T),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!x){let W=A.code!==1006?` (code ${A.code})`:"";v("WebSocket connection failed"+W+"."+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 Ia(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 So=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 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 Np(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}
13
13
 
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=`
14
+ _Details: ${t.message}_`:r}var Is=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)&&wa(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 qo(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 Ra((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=Vo(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,x,v;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 T=(v=this.pendingVoiceAssistantMessageId)!=null?v:(x=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:x.id;T&&this.ttsSpokenMessageIds.add(T)}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 qo(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"?Ls():t==="assistant"?zo():`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,v={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}};t.push(v)}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=Ls(),o=zo(),a={id:s,role:"user",content:r||ka,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(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let T=Np(x,this.config.errorMessage);if(T){let A={id:o,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(A)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,x):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=zo();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=Np(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 x=await f.json().catch(()=>null);throw new Error((l=x==null?void 0:x.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,x,v,T,A,W,P,I,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){(x=(m=this.callbacks).onError)==null||x.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=(v=n.toolCall)==null?void 0:v.args,R=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(R.length===1){let F=typeof((T=R[0])==null?void 0:T.question)=="string"?R[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=(W=n.toolCall)==null?void 0:W.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(([R,F])=>`${R}: ${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((R,F)=>{let _=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!_)return;let D=w[_],j=Array.isArray(D)?D.join(", "):typeof D=="string"?D:"";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]:t});if(!w.ok){let R=await w.json().catch(()=>null);throw new Error((P=R==null?void 0:R.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 R=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(L=(I=this.callbacks).onError)==null||L.call(I,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 W,P,I,L,w,R,F;let p=(W=u.toolCall)==null?void 0:W.name,f=(P=u.toolCall)==null?void 0:P.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 x=new AbortController;this.webMcpResolveControllers.add(x),s.push(x);let v=(L=(I=u.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?L:p,T=this.client.executeWebMcpToolCall(p,(w=u.toolCall)==null?void 0:w.args,x.signal),A;if(!T)A={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{A=await T}catch(_){return _ instanceof Error&&(_.name==="AbortError"||_.message.includes("aborted")||_.message.includes("abort"))||(F=(R=this.callbacks).onError)==null||F.call(R,_ instanceof Error?_:new Error(String(_))),this.webMcpInflightKeys.delete(m),null}return x.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:v,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,x,v,T,A,W,P,I,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){(x=(m=this.callbacks).onError)==null||x.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(R){(T=(v=this.callbacks).onError)==null||T.call(v,R instanceof Error?R:new Error(String(R)))}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 R=(P=(W=n.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?P:r;await this.resumeWithToolOutput(t,R,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=(I=this.callbacks).onError)==null||L.call(I,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.client.resetClientToolsFingerprint(),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,x,v;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&&wa(i)&&d&&l&&((x=t.agentMetadata)==null?void 0:x.awaitingLocalTool)===!0){let T=`${d}:${l}`;(this.webMcpInflightKeys.has(T)||this.webMcpResolvedKeys.has(T))&&(a.agentMetadata={...(v=a.agentMetadata)!=null?v:{},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},Sr=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as cg,ArrowDown as dg,ArrowUp as pg,ArrowUpRight as ug,Bot as mg,ChevronDown as gg,ChevronUp as fg,ChevronRight as hg,ChevronLeft as bg,Check as yg,Clipboard as xg,ClipboardCopy as vg,Copy as wg,File as Cg,FileCode as Ag,FileSpreadsheet as Sg,FileText as Tg,ImagePlus as Eg,Loader as Mg,LoaderCircle as kg,Mic as Lg,Paperclip as Pg,RefreshCw as Ig,Search as Wg,Send as Rg,ShieldAlert as Hg,ShieldCheck as Bg,ShieldX as Dg,Square as Ng,ThumbsDown as Og,ThumbsUp as Fg,Upload as _g,Volume2 as $g,X as jg,User as Ug,Mail as qg,Phone as zg,Calendar as Vg,Clock as Kg,Building as Jg,MapPin as Gg,Lock as Xg,Key as Qg,CreditCard as Yg,AtSign as Zg,Hash as ef,Globe as tf,Link as nf,CircleCheck as rf,CircleX as of,TriangleAlert as sf,Info as af,Ban as lf,Shield as cf,ArrowLeft as df,ArrowRight as pf,ExternalLink as uf,Ellipsis as mf,EllipsisVertical as gf,Menu as ff,House as hf,Plus as bf,Minus as yf,Pencil as xf,Trash as vf,Trash2 as wf,Save as Cf,Download as Af,Share as Sf,Funnel as Tf,Settings as Ef,RotateCw as Mf,Maximize as kf,Minimize as Lf,ShoppingCart as Pf,ShoppingBag as If,Package as Wf,Truck as Rf,Tag as Hf,Gift as Bf,Receipt as Df,Wallet as Nf,Store as Of,DollarSign as Ff,Percent as _f,Play as $f,Pause as jf,VolumeX as Uf,Camera as qf,Image as zf,Film as Vf,Headphones as Kf,MessageCircle as Jf,MessageSquare as Gf,Bell as Xf,Heart as Qf,Star as Yf,Eye as Zf,EyeOff as eh,Bookmark as th,CalendarDays as nh,History as rh,Timer as oh,Folder as sh,FolderOpen as ah,Files as ih,Sparkles as lh,Zap as ch,Sun as dh,Moon as ph,Flag as uh,Monitor as mh,Smartphone as gh}from"lucide";var fh={activity:cg,"arrow-down":dg,"arrow-up":pg,"arrow-up-right":ug,bot:mg,"chevron-down":gg,"chevron-up":fg,"chevron-right":hg,"chevron-left":bg,check:yg,clipboard:xg,"clipboard-copy":vg,copy:wg,file:Cg,"file-code":Ag,"file-spreadsheet":Sg,"file-text":Tg,"image-plus":Eg,loader:Mg,"loader-circle":kg,mic:Lg,paperclip:Pg,"refresh-cw":Ig,search:Wg,send:Rg,"shield-alert":Hg,"shield-check":Bg,"shield-x":Dg,square:Ng,"thumbs-down":Og,"thumbs-up":Fg,upload:_g,"volume-2":$g,x:jg,user:Ug,mail:qg,phone:zg,calendar:Vg,clock:Kg,building:Jg,"map-pin":Gg,lock:Xg,key:Qg,"credit-card":Yg,"at-sign":Zg,hash:ef,globe:tf,link:nf,"circle-check":rf,"circle-x":of,"triangle-alert":sf,info:af,ban:lf,shield:cf,"arrow-left":df,"arrow-right":pf,"external-link":uf,ellipsis:mf,"ellipsis-vertical":gf,menu:ff,house:hf,plus:bf,minus:yf,pencil:xf,trash:vf,"trash-2":wf,save:Cf,download:Af,share:Sf,funnel:Tf,settings:Ef,"rotate-cw":Mf,maximize:kf,minimize:Lf,"shopping-cart":Pf,"shopping-bag":If,package:Wf,truck:Rf,tag:Hf,gift:Bf,receipt:Df,wallet:Nf,store:Of,"dollar-sign":Ff,percent:_f,play:$f,pause:jf,"volume-x":Uf,camera:qf,image:zf,film:Vf,headphones:Kf,"message-circle":Jf,"message-square":Gf,bell:Xf,heart:Qf,star:Yf,eye:Zf,"eye-off":eh,bookmark:th,"calendar-days":nh,history:rh,timer:oh,folder:sh,"folder-open":ah,files:ih,sparkles:lh,zap:ch,sun:dh,moon:ph,flag:uh,monitor:mh,smartphone:gh},ye=(e,n=24,t="currentColor",r=2)=>{let s=fh[e];return s?hh(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 hh(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 Ha={allowedTypes:Nr,maxFileSize:10*1024*1024,maxFiles:4};function bh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function yh(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(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ha.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ha.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ha.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:Ha.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=Bp(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 Hp(l),f=Pa(l)?URL.createObjectURL(l):null,m={id:bh(),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=Pa(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=yh(n.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=Dp(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=ye("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 Op=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ws(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];Op(o)&&Op(s)?t[r]=Ws(o,s):t[r]=s}return t}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 Fp(e,n){if(!(!e&&!n))return e?n?Ws(e,n):e:n}function Li(e){var n,t,r,s,o,a,i,d,l,u,p,f,m,x,v,T,A,W,P,I,L;return e?{...Ot,...e,theme:Fp(Ot.theme,e.theme),darkTheme:Fp(Ot.darkTheme,e.darkTheme),launcher:{...Ot.launcher,...e.launcher,dock:{...(n=Ot.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.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,R=(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,D=(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&&R===void 0?void 0:{...w,...R,layout:{...w==null?void 0:w.layout,...R==null?void 0:R.layout}},Re=F===void 0&&_===void 0?void 0:{...F,..._},Ne=D===void 0&&j===void 0?void 0:{...D,...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:{...(v=(x=Ot.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(A=(T=e.layout)==null?void 0:T.messages)==null?void 0:A.timestamp}},slots:{...(W=Ot.layout)==null?void 0:W.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Ot.markdown,...e.markdown,options:{...(I=Ot.markdown)==null?void 0:I.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Ot.messageActions,...e.messageActions}}:Ot}var _p={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"}},$p={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"}},jp={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,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."))?Jo(e,r):r}function Pi(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=Jo(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 Up(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 qp(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]=qp(o,s):t[r]=s}return t}function xh(e,n){return n?qp(e,n):e}function Rs(e,n={}){var s,o,a,i,d,l,u,p,f,m,x,v,T;let t={palette:_p,semantic:$p,components:jp},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,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...t.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:xh(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let A=Up(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(W=>W.message).join(", ")}`)}if(n.plugins)for(let A of n.plugins)r=A.transform(r);return r}function Ii(e){var v,T,A,W,P,I,L,w,R,F,_,D,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,B,oe,Be,Xe,Fe,_e,rt,At,Ft,Kt,K,gt,nt,Ut,se,be,wt,_t,Zt,bn,Et,St,ht,yt,qt,et,Bn,Qn,yn,Dn,ut,xr,Nn,co,kn,Po,Fr,Er,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 n=Pi(e),t={};for(let[S,zn]of Object.entries(n)){let dr=S.replace(/\./g,"-");t[`--persona-${dr}`]=zn.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T: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"]=(W=t["--persona-semantic-colors-surface"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(P=t["--persona-semantic-colors-background"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(I=t["--persona-semantic-colors-container"])!=null?I:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(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"]=(R=t["--persona-semantic-colors-text-inverse"])!=null?R: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"]=(D=t["--persona-components-voice-recording-indicator"])!=null?D:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(j=t["--persona-components-voice-recording-background"])!=null?j:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(q=t["--persona-components-voice-processing-icon"])!=null?q:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re: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"]=(Re=t["--persona-components-approval-requested-border"])!=null?Re:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ne=t["--persona-components-approval-requested-text"])!=null?Ne:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ce=t["--persona-components-approval-approve-background"])!=null?ce:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ve=t["--persona-components-approval-deny-background"])!=null?ve:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Me=t["--persona-components-attachment-image-background"])!=null?Me:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Le=t["--persona-components-attachment-image-border"])!=null?Le:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ne=t["--persona-semantic-typography-fontFamily"])!=null?ne:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ke=t["--persona-semantic-typography-fontSize"])!=null?ke:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(V=t["--persona-semantic-typography-fontWeight"])!=null?V:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(pe=t["--persona-semantic-typography-lineHeight"])!=null?pe: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"]=(fe=t["--persona-palette-radius-sm"])!=null?fe:"0.125rem",t["--persona-radius-md"]=(me=t["--persona-palette-radius-md"])!=null?me:"0.375rem",t["--persona-radius-lg"]=(ue=t["--persona-palette-radius-lg"])!=null?ue:"0.5rem",t["--persona-radius-xl"]=(Ge=t["--persona-palette-radius-xl"])!=null?Ge:"0.75rem",t["--persona-radius-full"]=(z=t["--persona-palette-radius-full"])!=null?z:"9999px",t["--persona-launcher-radius"]=(We=(te=t["--persona-components-launcher-borderRadius"])!=null?te:t["--persona-palette-radius-full"])!=null?We:"9999px",t["--persona-launcher-bg"]=(ge=t["--persona-components-launcher-background"])!=null?ge:t["--persona-primary"],t["--persona-launcher-fg"]=(ie=t["--persona-components-launcher-foreground"])!=null?ie:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ae=t["--persona-components-launcher-border"])!=null?ae:t["--persona-border"],t["--persona-button-primary-bg"]=(Qe=t["--persona-components-button-primary-background"])!=null?Qe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Ce=t["--persona-components-button-primary-foreground"])!=null?Ce:t["--persona-text-inverse"],t["--persona-button-radius"]=(X=(de=t["--persona-components-button-primary-borderRadius"])!=null?de:t["--persona-palette-radius-full"])!=null?X:"9999px",t["--persona-panel-radius"]=(Ct=($e=t["--persona-components-panel-borderRadius"])!=null?$e:t["--persona-radius-xl"])!=null?Ct:"0.75rem",t["--persona-panel-border"]=(G=t["--persona-components-panel-border"])!=null?G:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Mn=(Oe=t["--persona-components-panel-shadow"])!=null?Oe:t["--persona-palette-shadows-xl"])!=null?Mn:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ln=(Dt=t["--persona-components-input-borderRadius"])!=null?Dt:t["--persona-radius-lg"])!=null?ln:"0.5rem",t["--persona-message-user-radius"]=(Xn=(Hn=t["--persona-components-message-user-borderRadius"])!=null?Hn:t["--persona-radius-lg"])!=null?Xn:"0.5rem",t["--persona-message-assistant-radius"]=(oe=(B=t["--persona-components-message-assistant-borderRadius"])!=null?B:t["--persona-radius-lg"])!=null?oe:"0.5rem",t["--persona-header-bg"]=(Be=t["--persona-components-header-background"])!=null?Be:t["--persona-surface"],t["--persona-header-border"]=(Xe=t["--persona-components-header-border"])!=null?Xe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Fe=t["--persona-components-header-iconBackground"])!=null?Fe:t["--persona-primary"],t["--persona-header-icon-fg"]=(_e=t["--persona-components-header-iconForeground"])!=null?_e:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(rt=t["--persona-components-header-titleForeground"])!=null?rt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(At=t["--persona-components-header-subtitleForeground"])!=null?At:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Ft=t["--persona-components-header-actionIconForeground"])!=null?Ft:t["--persona-muted"];let r=(Kt=e.components)==null?void 0:Kt.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(K=e.components)==null?void 0:K.introCard;t["--persona-intro-card-bg"]=(gt=t["--persona-components-introCard-background"])!=null?gt:t["--persona-surface"],t["--persona-intro-card-radius"]=(nt=t["--persona-components-introCard-borderRadius"])!=null?nt:"1rem",t["--persona-intro-card-padding"]=(Ut=t["--persona-components-introCard-padding"])!=null?Ut:"1.5rem",t["--persona-intro-card-shadow"]=(be=(se=s==null?void 0:s.shadow)!=null?se:t["--persona-components-introCard-shadow"])!=null?be:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(wt=t["--persona-components-input-background"])!=null?wt:t["--persona-surface"],t["--persona-input-placeholder"]=(_t=t["--persona-components-input-placeholder"])!=null?_t:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Zt=t["--persona-components-message-user-background"])!=null?Zt:t["--persona-accent"],t["--persona-message-user-text"]=(bn=t["--persona-components-message-user-text"])!=null?bn:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Et=t["--persona-components-message-user-shadow"])!=null?Et:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(St=t["--persona-components-message-assistant-background"])!=null?St:t["--persona-surface"],t["--persona-message-assistant-text"]=(ht=t["--persona-components-message-assistant-text"])!=null?ht:t["--persona-text"],t["--persona-message-assistant-border"]=(yt=t["--persona-components-message-assistant-border"])!=null?yt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(qt=t["--persona-components-message-assistant-shadow"])!=null?qt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Bn=(et=t["--persona-components-scrollToBottom-background"])!=null?et:t["--persona-button-primary-bg"])!=null?Bn:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(yn=(Qn=t["--persona-components-scrollToBottom-foreground"])!=null?Qn:t["--persona-button-primary-fg"])!=null?yn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Dn=t["--persona-components-scrollToBottom-border"])!=null?Dn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(ut=t["--persona-components-scrollToBottom-size"])!=null?ut:"40px",t["--persona-scroll-to-bottom-radius"]=(co=(Nn=(xr=t["--persona-components-scrollToBottom-borderRadius"])!=null?xr:t["--persona-button-radius"])!=null?Nn:t["--persona-radius-full"])!=null?co:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Po=(kn=t["--persona-components-scrollToBottom-shadow"])!=null?kn:t["--persona-palette-shadows-sm"])!=null?Po:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Fr=t["--persona-components-scrollToBottom-padding"])!=null?Fr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Er=t["--persona-components-scrollToBottom-gap"])!=null?Er:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(On=(xt=t["--persona-components-scrollToBottom-fontSize"])!=null?xt:t["--persona-palette-typography-fontSize-sm"])!=null?On:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Fn=t["--persona-components-scrollToBottom-iconSize"])!=null?Fn:"14px",t["--persona-tool-bubble-shadow"]=(xn=t["--persona-components-toolBubble-shadow"])!=null?xn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Pt=t["--persona-components-reasoningBubble-shadow"])!=null?Pt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Yn=t["--persona-components-composer-shadow"])!=null?Yn:"none",t["--persona-md-inline-code-bg"]=(Zn=t["--persona-components-markdown-inlineCode-background"])!=null?Zn:t["--persona-container"],t["--persona-md-inline-code-color"]=(_n=t["--persona-components-markdown-inlineCode-foreground"])!=null?_n:t["--persona-text"],t["--persona-md-link-color"]=(Mr=(_r=t["--persona-components-markdown-link-foreground"])!=null?_r:t["--persona-accent"])!=null?Mr:"#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"]=($r=t["--persona-components-markdown-codeBlock-background"])!=null?$r:t["--persona-container"],t["--persona-md-code-block-border-color"]=($n=t["--persona-components-markdown-codeBlock-borderColor"])!=null?$n:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Wt=t["--persona-components-markdown-codeBlock-textColor"])!=null?Wt:"inherit",t["--persona-md-table-header-bg"]=(vn=t["--persona-components-markdown-table-headerBackground"])!=null?vn:t["--persona-container"],t["--persona-md-table-border-color"]=(er=t["--persona-components-markdown-table-borderColor"])!=null?er:t["--persona-border"],t["--persona-md-hr-color"]=(jr=t["--persona-components-markdown-hr-color"])!=null?jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(kr=t["--persona-components-markdown-blockquote-borderColor"])!=null?kr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Ur=t["--persona-components-markdown-blockquote-background"])!=null?Ur:"transparent",t["--persona-md-blockquote-text-color"]=(vr=t["--persona-components-markdown-blockquote-textColor"])!=null?vr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(jn=t["--persona-components-collapsibleWidget-container"])!=null?jn:t["--persona-surface"],t["--cw-surface"]=(lr=t["--persona-components-collapsibleWidget-surface"])!=null?lr:t["--persona-surface"],t["--cw-border"]=(ft=t["--persona-components-collapsibleWidget-border"])!=null?ft: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 x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let S=x.toolbar;S.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=S.iconHoverColor),S.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=S.iconHoverBackground),S.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=S.iconPadding),S.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=S.iconBorderRadius),S.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=S.iconBorder),S.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=S.toggleGroupGap),S.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=S.toggleBorderRadius),S.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=S.copyBackground),S.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=S.copyBorder),S.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=S.copyColor),S.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=S.copyBorderRadius),S.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=S.copyPadding),S.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=S.copyMenuBackground,t["--persona-dropdown-bg"]=(Gt=t["--persona-dropdown-bg"])!=null?Gt:S.copyMenuBackground),S.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=S.copyMenuBorder,t["--persona-dropdown-border"]=(Un=t["--persona-dropdown-border"])!=null?Un:S.copyMenuBorder),S.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=S.copyMenuShadow,t["--persona-dropdown-shadow"]=(qr=t["--persona-dropdown-shadow"])!=null?qr:S.copyMenuShadow),S.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=S.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(tr=t["--persona-dropdown-radius"])!=null?tr:S.copyMenuBorderRadius),S.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=S.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(cr=t["--persona-dropdown-item-hover-bg"])!=null?cr:S.copyMenuItemHoverBackground),S.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=S.iconBackground),S.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=S.toolbarBorder)}if(x!=null&&x.tab){let S=x.tab;S.background&&(t["--persona-artifact-tab-bg"]=S.background),S.activeBackground&&(t["--persona-artifact-tab-active-bg"]=S.activeBackground),S.activeBorder&&(t["--persona-artifact-tab-active-border"]=S.activeBorder),S.borderRadius&&(t["--persona-artifact-tab-radius"]=S.borderRadius),S.textColor&&(t["--persona-artifact-tab-color"]=S.textColor),S.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=S.hoverBackground),S.listBackground&&(t["--persona-artifact-tab-list-bg"]=S.listBackground),S.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=S.listBorderColor),S.listPadding&&(t["--persona-artifact-tab-list-padding"]=S.listPadding)}if(x!=null&&x.pane){let S=x.pane;if(S.toolbarBackground){let zn=(qn=Jo(e,S.toolbarBackground))!=null?qn:S.toolbarBackground;t["--persona-artifact-toolbar-bg"]=zn}}return t}var vh={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 wh={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"}}},zp=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"},Ch=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Ba()},Vp=e=>Ch(e),Ah=e=>Rs(e),Sh=e=>{var t;let n=Rs(void 0,{validate:!1});return Rs({...e,palette:{...n.palette,colors:{...wh.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Hs=e=>{let n=Vp(e),t=zp(e==null?void 0:e.theme),r=zp(e==null?void 0:e.darkTheme);return n==="dark"?Sh(Ws(t!=null?t:{},r!=null?r:{})):Ah(t)},Th=e=>Ii(e),To=(e,n)=>{var o;let t=Hs(n),r=Th(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)},Wi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Ba())});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(Ba());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 Eh}from"idiomorph";var Da=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Eh.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 Na={index:-1,draft:""};function Kp(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:{...Na}}}function Jp(e,n){var t,r,s,o,a,i,d,l,u,p,f,m,x,v,T,A,W,P,I,L,w,R,F,_,D,j,q,re,Ie,Re,Ne,ce,ve,Me,Le,ne,ke,V;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:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(T=(v=e.toolCall)==null?void 0:v.name)!=null?T:"",(P=(W=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:W.length)!=null?P:0,(R=(w=(L=(I=e.toolCall)==null?void 0:I.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?R:"",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=(D=e.reasoning)==null?void 0:D.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:"",n].join("\0")}function Gp(){return new Map}function Xp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Qp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Yp(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Oa(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Bs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ds(e,n){return Bs(e)-e.scrollTop<=n}function Fa(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 _a(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 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"},Mh=["pre","code","a","script","style"],$a=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Ns.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t: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}},eu=[{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 eu)Os.set(e.name,e);var kh=e=>{Os.set(e.name,e)},Lh=e=>{eu.some(n=>n.name===e)||Os.delete(e)},Ph=()=>Array.from(Os.keys()),Fs=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Os.get(e))!=null?r:null},ja=(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},Ih=(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},Wh=(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},Ri=/\s/,Rh=(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},Hh=(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(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(Ih(r,o[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},Bh=(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(Wh(r,l,n,t.value)),t.value+=1));s.replaceChild(a,e)},_s=(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:Mh).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Rh(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?Hh:Bh;for(let m of i)u(m,t,l);return s.innerHTML},Ua=(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},$s=(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,Dh=(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)},Hi=new WeakMap,Nh=(e,n)=>{if(!e.onAttach)return;let t=Hi.get(n);if(t||(t=new Map,Hi.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},tu=e=>{let n=Hi.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},Bi=(e,n)=>{Dh(e,n),Nh(e,n)};function Di(e,n=hn){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 js=0,eo=null;function Ni(e=document){var t;if(js++,js===1){let r=e.body,o=((t=e.defaultView)!=null?t: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 n=!1;return()=>{var r;if(!n&&(n=!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 n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},to=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},br=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:qa.side,width:(s=n==null?void 0:n.width)!=null?s:qa.width,animate:(o=n==null?void 0:n.animate)!=null?o:qa.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:qa.reveal}};var yr={"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,n)=>{let t=h("button");t.type="button",t.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: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;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
- `,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=`
23
+ `,t.addEventListener("click",n);let r=o=>{var P,I,L,w,R,F,_,D,j,q,re,Ie,Re,Ne;let a=(P=o.launcher)!=null?P:{},i=an(o),d=t.querySelector("[data-role='launcher-title']");if(d){let ce=(I=a.title)!=null?I:"Chat Assistant";d.textContent=ce,d.setAttribute("title",ce)}let l=t.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=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 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=ye(a.agentIconName,ve*.6,"var(--persona-text-inverse, #ffffff)",2);Me?(p.appendChild(Me),p.style.display=""):(p.textContent=(R=a.agentIconText)!=null?R:"\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 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=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ce=(D=a.callToActionIconSize)!=null?D:"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=ye(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 x=a.position&&yr[a.position]?yr[a.position]:yr["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?T:`${v} ${x}`,i||(t.style.zIndex=String((re=a.zIndex)!=null?re:hn));let A="1px solid var(--persona-border, #e5e7eb)",W="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=(Re=a.shadow)!=null?Re:W,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=(Ne=a.collapsedMaxWidth)!=null?Ne:"",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 Oh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",za=(e,n={})=>{var v,T,A,W,P,I;let{showClose:t=!0,wrapperClassName:r=Oh,buttonSize:s,iconSize:o="28px"}=n,a=(v=e==null?void 0:e.launcher)!=null?v:{},i=(T=s!=null?s:a.closeButtonSize)!=null?T:"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=(W=a.closeButtonShowTooltip)!=null?W:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(P=a.closeButtonIconName)!=null?P:"x",m=(I=a.closeButtonIconText)!=null?I:"\xD7";l.style.color=a.closeButtonColor||En.actionIconColor;let x=ye(f,o,"currentColor",1);if(x?(x.style.display="block",l.appendChild(x)):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 D=Sr(F,"div");D.className="persona-clear-chat-tooltip-arrow",L.appendChild(D);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)},R=()=>{L&&L.parentNode&&(L.parentNode.removeChild(L),L=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",R),l.addEventListener("focus",w),l.addEventListener("blur",R),d._cleanupTooltip=()=>{R(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",R),l.removeEventListener("focus",w),l.removeEventListener("blur",R)}}return{button:l,wrapper:d}},Fh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Va=(e,n={})=>{var L,w,R,F,_,D,j,q,re,Ie,Re,Ne,ce;let{wrapperClassName:t=Fh,buttonSize:r,iconSize:s="20px"}=n,a=(w=((L=e==null?void 0:e.launcher)!=null?L:{}).clearChat)!=null?w:{},i=(R=r!=null?r:a.size)!=null?R:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",l=(_=a.iconColor)!=null?_:"",u=(D=a.backgroundColor)!=null?D:"",p=(j=a.borderWidth)!=null?j:"",f=(q=a.borderColor)!=null?q:"",m=(re=a.borderRadius)!=null?re:"",x=(Ie=a.paddingX)!=null?Ie:"",v=(Re=a.paddingY)!=null?Re:"",T=(Ne=a.tooltipText)!=null?Ne:"Clear chat",A=(ce=a.showTooltip)!=null?ce:!0,W=h("div",t),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",T),P.style.color=l||En.actionIconColor;let I=ye(d,s,"currentColor",1);if(I&&(I.style.display="block",P.appendChild(I)),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")),x&&(P.style.paddingLeft=x,P.style.paddingRight=x),v&&(P.style.paddingTop=v,P.style.paddingBottom=v),W.appendChild(P),A&&T){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=T;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)};W.addEventListener("mouseenter",Me),W.addEventListener("mouseleave",Le),P.addEventListener("focus",Me),P.addEventListener("blur",Le),W._cleanupTooltip=()=>{Le(),W.removeEventListener("mouseenter",Me),W.removeEventListener("mouseleave",Le),P.removeEventListener("focus",Me),P.removeEventListener("blur",Le)}}return{button:P,wrapper:W}};var En={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,R,F,_,D,j,q,re,Ie,Re,Ne,ce,ve,Me,Le;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=(R=s.closeButtonPlacement)!=null?R:"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=ye(d,ne*.6,"currentColor",1);ke?l.replaceChildren(ke):l.textContent=(D=(_=n==null?void 0:n.launcher)==null?void 0:_.agentIconText)!=null?D:"\u{1F4AC}"}else if((j=n==null?void 0:n.launcher)!=null&&j.iconUrl){let ne=h("img");ne.src=n.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=n==null?void 0:n.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=En.titleColor,p.textContent=(Re=(Ie=n==null?void 0:n.launcher)==null?void 0:Ie.title)!=null?Re:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=En.subtitleColor,f.textContent=(ce=(Ne=n==null?void 0:n.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:{},x=(Me=m.enabled)!=null?Me:!0,v=(Le=m.placement)!=null?Le:"inline",T=null,A=null;if(x){let ke=Va(n,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=ke.button,A=ke.wrapper,v==="top-right"&&(A.style.right="48px"),v==="inline"&&r.appendChild(A)}let W=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:I}=za(n,{showClose:t,wrapperClassName:W});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:P,closeButtonWrapper:I,clearChatButton:T,clearChatButtonWrapper:A}},Go=(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(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 n){if(m.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let T=ye(m.icon,16,"currentColor",1.5);T&&x.appendChild(T)}let v=document.createElement("span");v.textContent=m.label,x.appendChild(v),x.addEventListener("click",T=>{T.stopPropagation(),u(),t(m.id)}),a.appendChild(x)}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=x=>{!a.contains(x.target)&&!r.contains(x.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: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=ye(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 Ka(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=ye(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 Ja(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=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,x;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=ye(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=(x=d.padding)!=null?x:"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 v,T;l.style.backgroundColor=(v=d.background)!=null?v:"",l.style.borderColor=(T=d.border)!=null?T:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Eo({items:r,onSelect:v=>{l.setAttribute("aria-expanded","false"),s(v)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",v=>{v.stopPropagation();let T=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",T?"false":"true"),f.toggle()}),l.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l.click())}),{element:l,setLabel:v=>{u.textContent=v,l.setAttribute("aria-label",v)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var nu=e=>{var r;let n=no({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 _h(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=ye(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 ru=e=>{var W,P,I,L,w,R,F,_,D;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(W=n==null?void 0:n.launcher)!=null?W:{},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=En.titleColor,u=(I=l.querySelector(".persona-combo-btn-label"))!=null?I: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=En.titleColor,u.textContent=(L=a.title)!=null?L:"Chat Assistant",l.appendChild(u),_h(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=(R=j.borderRadius)!=null?R:"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=t?"":"none",m.style.color=a.closeButtonColor||En.actionIconColor;let x=(D=a.closeButtonIconName)!=null?D:"x",v=ye(x,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let T=h("div");T.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:A,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Fi={default:nu,minimal:ru},ou=e=>{var n;return(n=Fi[e])!=null?n:Fi.default},qs=(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 x=h("div");return x.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=ou(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 Ga=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}},Xa=e=>{var L,w,R,F,_,D,j,q,re,Ie,Re,Ne;let n=(L=e==null?void 0:e.sendButton)!=null?L:{},t=(w=n.useIcon)!=null?w:!1,r=(R=n.iconText)!=null?R:"\u2191",s=n.iconName,o=(F=n.stopIconName)!=null?F:"square",a=(_=n.tooltipText)!=null?_:"Send message",i=(D=n.stopTooltipText)!=null?D:"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=n.showTooltip)!=null?Re:!1,p=(Ne=n.size)!=null?Ne:"40px",f=n.backgroundColor,m=n.textColor,x=h("div","persona-send-button-wrapper"),v=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");v.type="submit",v.setAttribute("data-persona-composer-submit","");let T=null,A=null;if(t){v.style.width=p,v.style.height=p,v.style.minWidth=p,v.style.minHeight=p,v.style.fontSize="18px",v.style.lineHeight="1",v.innerHTML="",m?v.style.color=m:v.style.color="var(--persona-button-primary-fg, #ffffff)";let ce=parseFloat(p)||24,ve=(m==null?void 0:m.trim())||"currentColor";s?(T=ye(s,ce,ve,2),T?v.appendChild(T):v.textContent=r):v.textContent=r,A=ye(o,ce,ve,2),f?v.style.backgroundColor=f:v.classList.add("persona-bg-persona-primary")}else v.textContent=d,m?v.style.color=m:v.classList.add("persona-text-white");n.borderWidth&&(v.style.borderWidth=n.borderWidth,v.style.borderStyle="solid"),n.borderColor&&(v.style.borderColor=n.borderColor),n.paddingX?(v.style.paddingLeft=n.paddingX,v.style.paddingRight=n.paddingX):(v.style.paddingLeft="",v.style.paddingRight=""),n.paddingY?(v.style.paddingTop=n.paddingY,v.style.paddingBottom=n.paddingY):(v.style.paddingTop="",v.style.paddingBottom="");let W=null;u&&a&&(W=h("div","persona-send-button-tooltip"),W.textContent=a,x.appendChild(W)),v.setAttribute("aria-label",a),x.appendChild(v);let P="send";return{button:v,wrapper:x,setMode:ce=>{if(ce===P)return;P=ce;let ve=ce==="stop"?i:a;if(v.setAttribute("aria-label",ve),W&&(W.textContent=ve),t){if(T&&A){let Me=ce==="stop"?A:T;v.replaceChildren(Me)}}else v.textContent=ce==="stop"?l:d}}},Qa=e=>{var W,P,I,L,w,R,F,_,D,j,q,re;let n=(W=e==null?void 0:e.voiceRecognition)!=null?W:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((P=n.provider)==null?void 0:P.type)==="runtype";if(!(r||s))return null;let a=(L=(I=e==null?void 0:e.sendButton)==null?void 0:I.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=(R=n.iconSize)!=null?R:a,p=parseFloat(u)||24,f=(_=n.backgroundColor)!=null?_:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,m=(j=n.iconColor)!=null?j:(D=e==null?void 0:e.sendButton)==null?void 0:D.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 v=ye(l,p,m||"currentColor",1.5);v?d.appendChild(v):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 T=(q=n.tooltipText)!=null?q:"Start voice recognition";if(((re=n.showTooltip)!=null?re:!1)&&T){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=T,i.appendChild(Ie)}return{button:d,wrapper:i}},Ya=e=>{var x,v,T,A,W,P,I,L;let n=(x=e==null?void 0:e.attachments)!=null?x:{};if(n.enabled!==!0)return null;let t=(T=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?T:"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:Nr).join(","),s.multiple=((W=n.maxFiles)!=null?W: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=n.buttonTooltipText)!=null?P:"Attach file");let i=(I=n.buttonIconName)!=null?I:"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=ye(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}},Za=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},ei=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var zs=e=>{var x,v,T,A,W,P;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=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(n);a();let i=Xa(n),d=Qa(n),l=Ya(n),u=Za(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",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.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:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(W=l==null?void 0:l.input)!=null?W:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:p,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var su=()=>{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=ye("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=ye("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},au=e=>{var x,v,T,A,W,P;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=ei();r.style.display="none";let s=Za(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=Ga(n);o.style.maxHeight="100px",a();let i=Xa(n),d=Qa(n),l=Ya(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",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(l==null?void 0:l.button)&&I.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:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:s,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(W=l==null?void 0:l.input)!=null?W:null,attachmentPreviewsContainer:(P=l==null?void 0:l.previewsContainer)!=null?P:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var iu=e=>{var u,p,f,m,x,v,T,A,W,P,I,L,w,R,F,_,D;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=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=(x=j.expandedSize)!=null?x:"anchored",q.style.zIndex=String((T=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?T: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=(W=e==null?void 0:e.launcher)==null?void 0:W.zIndex)!=null?P:hn),{wrapper:q,panel:re,pillRoot:Ie}}if(t){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(!n){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=(I=e==null?void 0:e.launcher)==null?void 0:I.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&&yr[s.position]?yr[s.position]:yr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((F=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?F:hn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(D=(_=e==null?void 0:e.launcher)==null?void 0:_.width)!=null?D: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}},$h=(e,n)=>{var I,L,w,R,F,_,D,j,q;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}=za(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=(I=e==null?void 0:e.launcher)==null?void 0:I.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=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?F:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(D=(_=e==null?void 0:e.copy)==null?void 0:_.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",u.append(p,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),x=(j=e==null?void 0:e.layout)==null?void 0:j.contentMaxWidth;x&&(m.style.maxWidth=x,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 T=h("div","persona-composer-overlay persona-pointer-events-none");T.setAttribute("data-persona-composer-overlay",""),T.style.position="absolute",T.style.left="0",T.style.right="0",T.style.bottom="0",T.style.zIndex="20";let A=au({config:e}),{root:W,textNode:P}=su();return t.append(d,s,l,T),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:m,composerOverlay:T,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:W,peekTextNode:P}},lu=(e,n=!0)=>{var T,A,W,P,I,L,w,R,F;if(to(e))return $h(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=(T=e==null?void 0:e.layout)==null?void 0:T.header,s=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,o=r?qs(e,r,{showClose:n}):no({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=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=(W=e==null?void 0:e.copy)==null?void 0:W.welcomeTitle)!=null?P:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(L=(I=e==null?void 0:e.copy)==null?void 0:I.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",""),((R=e==null?void 0:e.copy)==null?void 0:R.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}),x=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;s?Go(t,o,e):(o.header.style.display="none",Go(t,o,e)),t.append(a);let v=h("div","persona-composer-overlay persona-pointer-events-none");return v.setAttribute("data-persona-composer-overlay",""),v.style.position="absolute",v.style.left="0",v.style.right="0",v.style.bottom="0",v.style.zIndex="20",x||(m.footer.style.display="none"),t.append(m.footer),t.append(v),{container:t,body:a,messagesWrapper:u,composerOverlay:v,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 jh=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}},Uh=(e,n)=>{if(!e)return null;let t=jh(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},qh=(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},zh=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},_i=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(":"))},$i=320,du=320,Vh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Kh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),Jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),Gh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),Xh=(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=`${$i}px`,l.style.maxHeight=`${du}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}),zh(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}},Qh=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(!_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`,n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Yh=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(!_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=`${du}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}},Zh=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(!_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",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}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 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},pu=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Xo};if(n){let s=n(r);if(s!==null)return s}return Xo()},eb=(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},cu=(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},tb=(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},uu=(e,n,t)=>{var m,x,v,T,A,W;let r=(m=n.showCopy)!=null?m:!0,s=(x=n.showUpvote)!=null?x:!0,o=(v=n.showDownvote)!=null?v:!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=(T=n.visibility)!=null?T:"hover",i=(A=n.align)!=null?A:"right",d=(W=n.layout)!=null?W:"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,I,L)=>{let w=jt({icon:P,label:I,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,n,t,r,s,o)=>{var ne,ke,V,pe,fe,me,ue,Ge,z,te,We,ge,ie,ae,Qe,Ce,de;let a=t!=null?t:{},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",x=tb(e.role,i),v=h("div",x.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Vh(e),A=(ue=(me=e.content)==null?void 0:me.trim())!=null?ue:"",P=T.length>0&&A===ka,I=$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"&&I.type!=="none"?Fs(I.type,L):null,R=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||R);F&&(w!=null&&w.bubbleClass)&&v.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",`${I.speed}ms`),_.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let D=F?ja((ae=e.content)!=null?ae:"",I.buffer,w,e,!!e.streaming):(Qe=e.content)!=null?Qe:"",j=n({text:D,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=cu(e,l);X.classList.add("persona-ml-2","persona-inline"),_.appendChild(X)}if(T.length>0){let X=Xh(T,!P&&!!A,()=>{P&&re&&(re.style.display="")});X?v.appendChild(X):P&&re&&(re.style.display="")}let Ie=Kh(e);if(Ie.length>0){let X=Qh(Ie);X&&v.appendChild(X)}let Re=Jh(e);if(Re.length>0){let X=Yh(Re);X&&v.appendChild(X)}let Ne=Gh(e);if(Ne.length>0){let X=Zh(Ne);X&&v.appendChild(X)}if(v.appendChild(_),p&&m==="below"&&e.createdAt){let X=cu(e,l);X.classList.add("persona-mt-1"),v.appendChild(X)}let ce=e.role==="assistant"?Uh(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=!!(D&&D.trim()),$e=I.placeholder==="skeleton",Ct=$e&&I.buffer==="line"&&X;if(X)Ct&&v.appendChild($s());else if($e)v.appendChild($s());else{let G=pu("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);G&&v.appendChild(G)}}if(ce&&e.stopReason&&!e.streaming&&(A||(_.style.display="none"),v.appendChild(qh(e.stopReason,ce))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=uu(e,r,s);v.appendChild(X)}if(!u||e.role==="system")return v;let Me=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Le=eb(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Me.append(v,Le):Me.append(Le,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Me},nb=(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}):Vs(e,n,t,r,s,o)};var Qo=new Set,rb=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),ob=(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
+ `):""},mu=(e,n)=>{let t=Qo.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=ye(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")},ji=(e,n)=>{var Re,Ne,ce,ve,Me,Le,ne,ke,V,pe,fe;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=(Ne=(Re=n==null?void 0:n.features)==null?void 0:Re.reasoningDisplay)!=null?Ne:{},o=s.expandable!==!1,a=o&&Qo.has(e.id),i=t.status!=="complete",d=ob(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=n==null?void 0:n.reasoning)!=null?ve:{},x=String((Me=t.startedAt)!=null?Me:Date.now()),v=()=>{let me=h("span","");return me.setAttribute("data-tool-elapsed",x),me.textContent=Sa(t),me},T=(Le=m.renderCollapsedSummary)==null?void 0:Le.call(m,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:Sa(t),createElapsedElement:v});typeof T=="string"&&T.trim()?(p.textContent=T,u.appendChild(p)):T instanceof HTMLElement?u.appendChild(T):(p.textContent=f,u.appendChild(p));let A=h("span","persona-text-xs persona-text-persona-primary");A.textContent=Pp(t),u.appendChild(A);let W=(ne=s.loadingAnimation)!=null?ne:"none",P=m.activeTextTemplate,I=m.completeTextTemplate,L=i?P:I,w=T instanceof HTMLElement,R=(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=Ta(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(v());else{let ge=te.isDuration?Sa(t):te.text;ue?z=R(We,ge,z):We.appendChild(document.createTextNode(ge))}}};if(!w&&L)if(A.style.display="none",p.style.display="",i&&W!=="none"){let me=(ke=m.loadingAnimationDuration)!=null?ke:2e3;p.setAttribute("data-preserve-animation","true"),W==="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-${W}`),p.style.setProperty("--persona-tool-anim-duration",`${me}ms`),W==="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&&W!=="none"){p.style.display="";let me=(V=m.loadingAnimationDuration)!=null?V:2e3;if(p.setAttribute("data-preserve-animation","true"),W==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${me}ms`);else{p.classList.add(`persona-tool-loading-${W}`),p.style.setProperty("--persona-tool-anim-duration",`${me}ms`),W==="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="",R(p,ue,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 ue=ye(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 D=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","reasoning"),D.style.display="none",D.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let me=(fe=(pe=n==null?void 0:n.reasoning)==null?void 0:pe.renderCollapsedPreview)==null?void 0:fe.call(pe,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});rb(D,me)||(D.textContent=d),D.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,D),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=t.chunks.join(""),re=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return re.textContent=q||(t.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=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);ue?_.appendChild(ue):_.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",D.style.display=a?"none":D.textContent||D.childNodes.length?"":"none"})(),r.append(l,D,j),r};var Yo=new Set,sb=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),ab=(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=Uo(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
26
+ `):""},ib=(e,n)=>{var u,p,f,m,x;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=ab(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?Ip(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=((x=t.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=wi(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=wi(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},gu=(e,n,t)=>{var u;let r=Yo.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=ye(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,n)=>{var q,re,Ie,Re,Ne,ce,ve,Me,Le;let t=e.toolCall,r=(q=n==null?void 0:n.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),!t)return s;let o=(Ie=(re=n==null?void 0:n.features)==null?void 0:re.toolCallDisplay)!=null?Ie:{},a=o.expandable!==!1,i=a&&Yo.has(e.id),{summary:d,previewText:l,isActive:u}=ib(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 x=String((Re=t.startedAt)!=null?Re:Date.now()),v=()=>{let ne=h("span","");return ne.setAttribute("data-tool-elapsed",x),ne.textContent=ks(t),ne},T=(ce=r.renderCollapsedSummary)==null?void 0:ce.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Ne=o.collapsedMode)!=null?Ne:"tool-call",isActive:u,config:n!=null?n:{},elapsed:ks(t),createElapsedElement:v});typeof T=="string"&&T.trim()?(m.textContent=T,f.appendChild(m)):T instanceof HTMLElement?f.appendChild(T):(m.textContent=d,f.appendChild(m));let A=(ve=o.loadingAnimation)!=null?ve:"none",W=r.activeTextTemplate,P=r.completeTextTemplate,I=u?W:P,L=T 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},R=(ne,ke)=>{var me;m.textContent="";let V=((me=t.name)==null?void 0:me.trim())||"tool",pe=Ta(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(v());else{let z=ue.isDuration?ks(t):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`),I&&R(I,!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)),I)R(I,!0);else{let ke=m.textContent||d;m.textContent="",w(m,ke,0)}}else I&&R(I,!1);let F=null;if(a){F=h("div","persona-flex persona-items-center");let ne=r.toggleTextColor||r.headerTextColor||"currentColor",ke=ye(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:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});sb(_,ne)||(_.textContent=l),_.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,_),s;let D=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(D.style.display=i?"":"none",r.contentBackgroundColor&&(D.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(D.style.color=r.contentTextColor),r.contentPaddingX&&(D.style.paddingLeft=r.contentPaddingX,D.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(D.style.paddingTop=r.contentPaddingY,D.style.paddingBottom=r.contentPaddingY),t.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=t.name,D.appendChild(ne)}if(t.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(t.args),ne.append(ke,V),D.appendChild(ne)}if(t.chunks&&t.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=t.chunks.join(""),ne.append(ke,V),D.appendChild(ne)}if(t.status==="complete"&&t.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(t.result),ne.append(ke,V),D.appendChild(ne)}if(t.status==="complete"&&typeof t.duration=="number"){let ne=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ne.style.color=r.contentTextColor),ne.textContent=`Duration: ${t.duration}ms`,D.appendChild(ne)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let ne=r.toggleTextColor||r.headerTextColor||"currentColor",ke=ye(i?"chevron-up":"chevron-down",16,ne,2);ke?F.appendChild(ke):F.textContent=i?"Hide":"Show"}D.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),s.append(p,_,D),s};import{parse as lb,ARR as cb,OBJ as db,STR as pb}from"partial-json";var hu="ask_user_question",qi=8,Zo="data-persona-ask-sheet-for",ub="Other",mb="Other\u2026",bu="Type your own answer here",yu="Send",gb="Next",fb="Back",hb="Submit all",bb="Skip",yb=3,zi="data-ask-current-index",Vi="data-ask-question-count",xu="data-ask-answers",Ki="data-ask-grouped",vu="data-ask-layout",xb=e=>e.layout==="pills"?"pills":"rows",vb=e=>e.getAttribute(vu)==="pills"?"pills":"rows",fu=!1,wu=e=>e.replace(/["\\]/g,"\\$&"),ro=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===hu,ti=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},oo=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=lb(s,pb|db|cb);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},Ks=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>qi&&!fu&&(fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${qi}.`)),n.slice(0,qi)},wb=e=>{var n;return(n=Ks(e)[0])!=null?n:null},Cb=(e,n)=>{var t;return(t=Ks(e)[n])!=null?t:null},Cu=(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))},Au=(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},Ab=(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=Au(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},Sb=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},Tb=(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<yb;m++)o.appendChild(Sb(r));return o}if(d.forEach((m,x)=>{o.appendChild(Ab(m,x,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?ub:mb;if(r==="rows"){let x=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=h("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=n.freeTextPlaceholder)!=null?u:bu,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:m),v.appendChild(T),x.appendChild(v);let A=Au(r,a,d.length);A&&x.appendChild(A),o.appendChild(x)}else{let x=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=n.freeTextLabel)!=null?f:m,o.appendChild(x)}}return o},Su=(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:bu,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:yu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Eb=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:yu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},Mb=(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:fb,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:bb,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:hb:(f=t.nextLabel)!=null?f:gb,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Mo=e=>{let n=e.getAttribute(xu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Tu=(e,n)=>{e.setAttribute(xu,JSON.stringify(n))},ar=e=>{var t;let n=Number((t=e.getAttribute(zi))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},kb=(e,n)=>{e.setAttribute(zi,String(Math.max(0,Math.floor(n))))},es=e=>{var t;let n=Number((t=e.getAttribute(Vi))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},so=e=>e.getAttribute(Ki)==="true",Lb=(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},Pb=(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)))},ni=(e,n)=>{let{payload:t}=oo(n),r=Ks(t),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},Eu=e=>{let n=Mo(e),t=ar(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=""},Mu=e=>{if(!so(e))return;let n=Mo(e),t=ar(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}},Ji=(e,n,t)=>{let r=ti(t),s=vb(e),{payload:o,complete:a}=oo(n),i=so(e),d=ar(e),l=es(e),u=i?Cb(o,d):wb(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 x=e.querySelector('[data-ask-question="true"]');if(x){let W=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=W,x.classList.toggle("persona-ask-question-skeleton",!W&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let W=Tb(u,r,a,s);v.replaceWith(W)}if(s!=="rows"){let W=e.querySelector('[data-ask-free-text-row="true"]');W&&W.replaceWith(Su(r,s))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!T?e.appendChild(Eb(r)):(!p||i)&&T&&T.remove(),e.setAttribute("data-multi-select",p?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let W=Mb(d,l,r);A?A.replaceWith(W):e.appendChild(W)}else A&&A.remove();Eu(e),Mu(e)},Ib=(e,n,t)=>{let r=ti(n),s=xb(r),o=e.toolCall.id,a=Ks(t),i=Math.max(1,a.length),d=i>1,l=Lb(e,a),u=d?Pb(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(vu,s),Tu(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`),Cu(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 x=h("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),p.appendChild(f);let T=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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),p.appendChild(T),s!=="rows"&&p.appendChild(Su(r,s)),Ji(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Wb=(e,n,t)=>{let{payload:r}=oo(n),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,n,t)},Rb=(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=ti(n);Cu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=oo(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},Js=(e,n,t)=>{if(!t||!ro(e)||ti(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Zo}]`).forEach(l=>{l.getAttribute(Zo)!==s&&l.remove()});let a=t.querySelector(`[${Zo}="${wu(s)}"]`);if(a){Wb(a,e,n);return}let{payload:i}=oo(e),d=Ib(e,n,i);t.appendChild(d)},ko=(e,n)=>{if(!e)return;let t=n?`[${Zo}="${wu(n)}"]`:`[${Zo}]`;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)})},Gi=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),ao=(e,n)=>{let t=Mo(e),r=ar(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Tu(e,t),Eu(e),Mu(e)},ri=(e,n,t,r)=>{let s=es(e),o=Math.max(0,Math.min(s-1,r));kb(e,o),Ji(e,n,t)};var Xi=(e,n)=>{var v,T,A,W,P,I,L,w,R,F,_,D;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=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(T=r==null?void 0:r.borderColor)!=null?T:"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=ye(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=(W=r==null?void 0:r.title)!=null?W:"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",t.status),t.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"):t.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"):t.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 x=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(x.style.color=r.descriptionColor),x.textContent=t.description,p.appendChild(x),t.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(t.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=(I=r==null?void 0:r.approveButtonTextColor)!=null?I:"#ffffff",q.setAttribute("data-approval-action","approve");let re=ye("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=(R=r==null?void 0:r.denyButtonColor)!=null?R:"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=ye("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((D=r==null?void 0:r.denyLabel)!=null?D:"Deny");Re.appendChild(ce),j.append(q,Re),p.appendChild(j)}return a.append(i,p),o.appendChild(a),o};var ku=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 x=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");x.type="button",x.textContent=m,x.disabled=p,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(x),n.push(x)}),e.appendChild(u)}}};var Gs=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 Xs=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{}}};var Hb=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Bb=new Set(["step_start","execution_start"]),Db=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Nb=new Set(["step_complete","agent_turn_complete"]),Ob=new Set(["flow_complete","agent_complete"]),Lu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Iu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Lo=(e,n)=>{let t=e[n];return Iu(t)?t:void 0};function Qi(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function oi(e,n){if(!(e<=0||n===void 0||n<250))return e/(n/1e3)}function Fb(e,n){return typeof n.type=="string"?n.type:e}function _b(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 $b(e,n){return e==="step_delta"||e==="step_chunk"?n.stepType!=="tool"&&n.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof n.contentType=="string"?n.contentType:typeof n.content_type=="string"?n.content_type:void 0)==="text"}function Pu(e){var r,s,o,a,i;let n=Lo(e,"result"),t=[Lo(e,"tokens"),Lo(e,"totalTokens"),n?Lo(n,"tokens"):void 0,Lo(e,"usage"),n?Lo(n,"usage"):void 0];for(let d of t){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:n?(a=Gn(n.outputTokens))!=null?a:Gn(n.completionTokens):void 0}function jb(e){var t,r,s,o,a;let n=Lo(e,"result");return(a=(s=(r=(t=Gn(e.executionTime))!=null?t:Gn(e.executionTimeMs))!=null?r:Gn(e.execution_time))!=null?s:Gn(e.duration))!=null?a:n?(o=Gn(n.executionTime))!=null?o:Gn(n.executionTimeMs):void 0}function Ub(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Qs=class{constructor(n=Ub){this.metric={status:"idle"};this.run=null;this.now=n}getMetric(){let n=this.run;if(n&&this.metric.status==="running"&&n.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-n.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:oi(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(n){this.run={startedAt:n,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(n,t){var o;if(!Iu(t)){Lu.has(n)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Fb(n,t),s=this.now();if(Hb.has(r)){this.startRun(s);return}if(Bb.has(r)){this.run||this.startRun(s);return}if(Db.has(r)){if(!$b(r,t))return;let a=_b(t);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(Nb.has(r)){if(!this.run)return;let a=this.run,i=Pu(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Qi(a.visibleCharCount),u=this.resolveDuration(a,t,s);this.metric={status:"running",tokensPerSecond:oi(l,u),outputTokens:l,durationMs:u,source:d?"usage":"estimate"};return}if(Ob.has(r)){if(!this.run)return;let a=this.run,i=Pu(t),d=i!=null?i:a.exactOutputTokens+Qi(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,t,s);this.metric={status:"complete",tokensPerSecond:oi(d,u),outputTokens:d,durationMs:u,source:l},this.run=null;return}if(Lu.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(n,t,r){let s=n.firstDeltaAt!==void 0?r-n.firstDeltaAt:void 0;if(s!==void 0&&s>=250)return s;let o=jb(t);return o!=null?o:r-n.startedAt}};function ts(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var qb={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)"}},zb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Vb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Kb=100;function Jb(e,n){let t={...qb,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return zb}function Gb(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Xb(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 Qb(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 Yb(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 Zb(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 ey(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function ty(e){let n=[];return e.outputTokens!==void 0&&n.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&n.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&n.push(e.source),n.join(" \xB7 ")}function ny(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 Yi(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");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: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 q,re;let m=h("div",""),x=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");x.setAttribute("data-event-id",e.id);let v=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&v.appendChild(T);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),W=(q=r.timestampFormat)!=null?q:"relative";A.textContent=W==="relative"?Gb(e.timestamp,t):Xb(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(n+1));let I=Jb(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=I.bg,L.style.color=I.text,L.style.borderColor=I.text+"50",L.textContent=e.type;let w=(re=r.descriptionFields)!=null?re:Vb,R=Qb(e.payload,w),F=null;R&&(F=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=R);let _=h("div","persona-flex-1 persona-min-w-0"),D=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=ye("clipboard","12px","currentColor",1.5);return j&&D.appendChild(j),D.addEventListener("click",async Ie=>{Ie.stopPropagation(),await Yb(Zb(e)),D.innerHTML="";let Re=ye("check","12px","currentColor",1.5);Re&&D.appendChild(Re),setTimeout(()=>{D.innerHTML="";let Ne=ye("clipboard","12px","currentColor",1.5);Ne&&D.appendChild(Ne)},1500)}),x.appendChild(v),x.appendChild(A),P&&x.appendChild(P),x.appendChild(L),F&&x.appendChild(F),x.appendChild(_),x.appendChild(D),m.appendChild(x),d&&m.appendChild(ny(e,a,i)),m}}function Wu(e){var x,v,T,A,W;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[],getThroughput:a}=e,i=(x=s==null?void 0:s.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",p=(W=(A=s==null?void 0:s.features)==null?void 0:A.eventStream)!=null?W:{},f=o.find(P=>P.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&s){let P=f.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>m().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return m();function m(){let P=p.classNames,I=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ts(I,P==null?void 0:P.panel);let L=[],w="",R="",F=null,_=[],D={},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"),be=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(be,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,yn=We,Dn=()=>{if(!yn.textContent)return;let xr=Qn.getBoundingClientRect(),Nn=se.getBoundingClientRect();yn.style.left=`${xr.left-Nn.left}px`,yn.style.top=`${xr.bottom-Nn.top+4}px`,yn.style.display="block"},ut=()=>{yn.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 Et=ye("clipboard-copy","12px","currentColor",1.5);Et&&me.appendChild(Et);let St=h("span","persona-text-xs");St.textContent="Copy All",me.appendChild(St),be.appendChild(wt),be.appendChild(pe),te&&be.appendChild(te),be.appendChild(_t),be.appendChild(fe),be.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 yt=ye("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");yt&&qt.appendChild(yt),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=ye("x","12px","currentColor",2);return et&&Ge.appendChild(et),ht.appendChild(qt),ht.appendChild(ue),ht.appendChild(Ge),se.appendChild(be),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:n.getSize(),filteredCount:0,onFilterChange:be=>{w=be,Hn(),oe()},onSearchChange:be=>{R=be,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=ey(se);let be=ty(se);We&&(We.textContent=be,be||(We.style.display="none")),be?te.setAttribute("aria-label",be):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=ye(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),I.setAttribute("tabindex","0"),I.appendChild(ie),I.appendChild(Qe),I.appendChild(de);function Mn(){let se=n.getAll(),be={};for(let St of se)be[St.type]=(be[St.type]||0)+1;let wt=Object.keys(be).sort(),_t=wt.length!==_.length||!wt.every((St,ht)=>St===_[ht]),Zt=!_t&&wt.some(St=>be[St]!==D[St]),bn=se.length!==Object.values(D).reduce((St,ht)=>St+ht,0);if(!_t&&!Zt&&!bn||(_=wt,D=be,!fe))return;let Et=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} (${be[St]||0})`,fe.appendChild(ht)}Et&&wt.includes(Et)?fe.value=Et:Et&&(fe.value="",w="")}else for(let St=1;St<fe.options.length;St++){let ht=fe.options[St];ht.textContent=`${ht.value} (${be[ht.value]||0})`}}function Dt(){let se=n.getAll();if(w&&(se=se.filter(be=>be.type===w)),R){let be=R.toLowerCase();se=se.filter(wt=>wt.type.toLowerCase().includes(be)||wt.payload.toLowerCase().includes(be))}return se}function ln(){return w!==""||R!==""}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 be=X.scrollTop,wt=q.isFollowing();ce=!0,q.pause(),oe(),X.scrollTop=be,wt&&q.resume(),ce=!1}function B(){return Ds(X,50)}function oe(){Ie=Date.now(),Re=!1,Ce(),Mn();let se=n.getEvictedCount();se>0?(Qe.textContent=`${se.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",L=Dt();let be=L.length,wt=n.getSize()>0;pe&&(pe.textContent=String(n.getSize())),be===0&&wt&&ln()?(Oe.textContent=R?`No events matching '${R}'`:"No events matching filter",Oe.style.display="",X.style.display="none"):(Oe.style.display="none",X.style.display=""),me&&(me.title=ln()?`Copy Filtered (${be})`:"Copy All"),d&&!q.isFollowing()&&be>j&&(re+=be-j,G.textContent=u?`${u}${re>0?` (${re})`:""}`:"",$e.style.display=""),j=be;let _t=n.getAll(),Zt=_t.length>0?_t[0].timestamp:0,bn=new Set(L.map(ht=>ht.id));for(let ht of Me)bn.has(ht)||Me.delete(ht);let Et=w!==ne||R!==ke,St=Le.size===0&&L.length>0;if(Et||St||L.length===0){X.innerHTML="",Le.clear();let ht=document.createDocumentFragment();for(let yt=0;yt<L.length;yt++){let qt=Yi(L[yt],yt,Zt,p,Me,Xn,o,s);Le.set(L[yt].id,qt),ht.appendChild(qt)}X.appendChild(ht),ne=w,ke=R,V=null}else{if(V!==null){let yt=Le.get(V);if(yt&&yt.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,yt),yt.remove(),Le.set(V,et)}}V=null}let ht=new Set(L.map(yt=>yt.id));for(let[yt,qt]of Le)ht.has(yt)||(qt.remove(),Le.delete(yt));for(let yt=0;yt<L.length;yt++){let qt=L[yt];if(!Le.has(qt.id)){let et=Yi(qt,yt,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>=Kb){Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),oe();return}Re||(Re=!0,Ne=requestAnimationFrame(()=>{Ne=null,oe()}))}let Xe=(se,be)=>{if(!me)return;me.innerHTML="";let wt=ye(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=ye("clipboard-copy","12px","currentColor",1.5);Zt&&me.appendChild(Zt);let bn=h("span","persona-text-xs");bn.textContent="Copy All",me.appendChild(bn),me.disabled=!1},be)},Fe=async()=>{if(me){me.disabled=!0;try{let se;ln()?se=L:t?(se=await t(),se.length===0&&(se=n.getAll())):se=n.getAll();let be=se.map(wt=>{try{return JSON.parse(wt.payload)}catch{return wt.payload}});await navigator.clipboard.writeText(JSON.stringify(be,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(()=>{R=ue.value,Hn(),oe()},150))},At=()=>{!ue||!Ge||(ue.value="",R="",Ge.style.display="none",F&&clearTimeout(F),Hn(),oe())},Ft=()=>{if(ce)return;let se=X.scrollTop,{action:be,nextLastScrollTop:wt}=Fa({following:q.isFollowing(),currentScrollTop:se,lastScrollTop:ve,nearBottom:B(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ve=wt,be==="resume"?(q.resume(),re=0,$e.style.display="none"):be==="pause"&&(q.pause(),d&&(G.textContent=u,$e.style.display=""))},Kt=se=>{let be=_a({following:q.isFollowing(),deltaY:se.deltaY,nearBottom:B(),resumeWhenNearBottom:!0});be==="pause"?(q.pause(),d&&(G.textContent=u,$e.style.display="")):be==="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 be=se.target;if(!be||be.closest("button"))return;let wt=be.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(),I.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),I.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),I.removeEventListener("keydown",nt)}return{element:I,update:Be,destroy:Ut}}}function Ru(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 Hu=(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:()=>Ru(e,n)});if(u)return u}return Ru(e,n)};var Zi=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)})}},io=new Zi;io.register("PersonaArtifactCard",Hu);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 Bu(e,n){var fe,me,ue,Ge;let t=(me=(fe=e.features)==null?void 0:fe.artifacts)==null?void 0:me.layout,s=((ue=t==null?void 0:t.toolbarPreset)!=null?ue:"default")==="document",o=(Ge=t==null?void 0:t.panePadding)==null?void 0:Ge.trim(),a=e.markdown?$o(e.markdown):null,i=Ts(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=n.onDismiss)==null||z.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 x=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var z;u(),(z=n.onDismiss)==null||z.call(n)});let v="rendered",T=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"}),W=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"),I=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,R=!!(L&&w&&w.length>0),F=null,_,D=null,j=null;if(s&&(I||L)&&!R){if(_=I?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=ye("chevron-down",14,"currentColor",2);z&&_.appendChild(z)}}else s&&R?(F=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=I?Ka({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=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(_,D)):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=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(z&&R){let{markdown:te,jsonPayload:We,id:ge}=Ie();try{await z({actionId:"primary",artifactId:ge,markdown:te,jsonPayload:We})}catch{}return}await Re()}),D&&(w!=null&&w.length)){let z=()=>{var We;return(We=p.closest("[data-persona-root]"))!=null?We:document.body},te=()=>{j=Eo({items:w.map(We=>({id:We.id,label:We.label})),onSelect:async We=>{let{markdown:ge,jsonPayload:ie,id:ae}=Ie(),Qe=t==null?void 0:t.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:D,position:"bottom-right",portal:z()})};p.isConnected?te():requestAnimationFrame(te),D.addEventListener("click",We=>{We.stopPropagation(),j==null||j.toggle()})}q.addEventListener("click",async()=>{var z;try{await((z=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:z.call(t))}catch{}V()}),re.addEventListener("click",()=>{var z;u(),(z=n.onDismiss)==null||z.call(n)});let Ne=()=>{s&&(A.setAttribute("aria-pressed",v==="rendered"?"true":"false"),W.setAttribute("aria-pressed",v==="source"?"true":"false"))};A.addEventListener("click",()=>{v="rendered",Ne(),V()}),W.addEventListener("click",()=>{v="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(),T.append(A,W),F?P.append(F,q,re):P.append(_,q,re),f.append(T,ce,P),Ne()):(f.appendChild(m),f.appendChild(x)),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",()=>n.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&&v==="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(ry(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 n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Du(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"),!ir(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 oy(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,n){var d,l,u,p,f,m,x,v,T,A;if(!ir(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"),oy(e),Du(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=(x=t==null?void 0:t.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(T=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(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"),Du(e,n)}var Nu=["panel","seamless"];function ai(e,n){var i,d,l,u,p,f;for(let m of Nu)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(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=Nu.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 Ou(e,n){var t,r,s;return!n||!ir(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function sy(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 ay(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 iy(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function ly(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function Fu(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 _u(e,n,t,r,s,o){let a=sy(s,200),i=ly(n,t,r,200);i=Math.max(a,i);let d=ay(o);return d!==null&&(i=Math.min(i,d)),iy(e,a,i)}var $u={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,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,v,T;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(v=$u[a])!=null?v:$u.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,R;let W=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");W.htmlFor=`${n.id}-${a}-${A.name}`;let P=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=A.label,W.appendChild(P);let I=(w=A.type)!=null?w:"text",L;I==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=I),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=(R=A.placeholder)!=null?R:"",A.required&&(L.required=!0),W.appendChild(L),u.appendChild(W)});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=(T=i.submitLabel)!=null?T:"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 W=(L=t.formEndpoint)!=null?L:"/form",P=new FormData(u),I={};P.forEach((R,F)=>{I[F]=R}),I.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let F=await R.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(R){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var tl=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()}},ii=new tl;var ju=()=>{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 cy=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},dy=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},li=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=cy(e),t=dy(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}},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,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=nl(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:nl(t.text)}}},Uu=e=>Array.isArray(e)?e.map(n=>String(n)):[],ci=e=>{let n=new Set(Uu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Uu(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 py=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}},uy=e=>e.map(n=>({...n,streaming:!1})),my=e=>e.map(n=>({...n,status:"complete"})),rl=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?py(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?uy(t.messages):void 0,artifacts:t.artifacts?my(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 gy,STR as fy,OBJ as hy}from"partial-json";function by(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function yy(e,n){if(!by(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 ol(){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=gy(t,fy|hy),o=yy(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function xy(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function sl(e,n){let{config:t,message:r,onPropsUpdate:s}=n,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: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 vy(){let e=ol();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function qu(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 al(e){let n=qu(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 il(e){let n=qu(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 wy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ll(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=wy}=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 x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,m.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,m.appendChild(v),f.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let w=1;w<=5;w++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),R.title=l[w-1],R.dataset.rating=String(w),R.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
- `,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=`
30
+ `,R.addEventListener("click",()=>{p=w,A.forEach((F,_)=>{let D=_<w;F.classList.toggle("selected",D),F.setAttribute("aria-checked",_===w-1?"true":"false")})}),A.push(R),T.appendChild(R)}f.appendChild(T);let W=null;if(d){let w=document.createElement("div");w.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"),w.appendChild(W),f.appendChild(w)}let P=document.createElement("div");P.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{t==null||t(),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){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=(W==null?void 0:W.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)}}),P.appendChild(I),P.appendChild(L),f.appendChild(P),u.appendChild(f),u}function cl(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 x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,x.appendChild(T),m.appendChild(x);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 W=document.createElement("div");W.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=l;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=u,W.appendChild(P),W.appendChild(I);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(W),A.appendChild(L),m.appendChild(A);let R=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=o,R.rows=3,R.setAttribute("aria-label","Additional comments"),j.appendChild(R),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",()=>{t==null||t(),p.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let j=(R==null?void 0:R.value.trim())||void 0;await n(f,j),p.remove()}catch(j){D.disabled=!1,D.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),F.appendChild(_),F.appendChild(D),m.appendChild(F),p.appendChild(m),p}var rs="persona-chat-history",Cy=30*1e3,Ay={"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 Sy(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=Ay[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 di(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 Ty(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 Ey(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var dl=e=>!e||typeof e!="object"?{}:{...e},zu=e=>e.map(n=>({...n,streaming:!1})),Vu=(e,n,t)=>{let r=e!=null&&e.markdown?$o(e.markdown):null,s=Ts(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=jo(a),s?s(d):d}};function Ku(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=ye(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 pl=(e,n,t)=>{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,bc,yc,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(n),s=ii.getForInstance(r.plugins);r.components&&io.registerAll(r.components);let o=ju(),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:b,open:y}=g;return y&&(u=!0),b}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 b=g!=null?g:{messages:[],metadata:{}};return p(b)});else{let g=c!=null?c:{messages:[],metadata:{}},b=p(g);b.metadata&&(d=dl(b.metadata)),(Pl=b.messages)!=null&&Pl.length&&(r={...r,initialMessages:b.messages}),(Il=b.artifacts)!=null&&Il.length&&(r={...r,initialArtifacts:b.artifacts,initialSelectedArtifactId:(Wl=b.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 b;d=(b=c({...d}))!=null?b:{},Wo()},x=r.actionParsers&&r.actionParsers.length?r.actionParsers:[li],v=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ns.message,ns.messageAndClick],T=ci({parsers:x,handlers:v,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let A=(Bl=(Hl=r.launcher)==null?void 0:Hl.enabled)!=null?Bl:!0,W=(Nl=(Dl=r.launcher)==null?void 0:Dl.autoExpand)!=null?Nl:!1,P=(Ol=r.autoFocusInput)!=null?Ol:!1,I=W,L=A,w=(_l=(Fl=r.layout)==null?void 0:Fl.header)==null?void 0:_l.layout,R=!1,F=()=>to(r),_=()=>A||F(),D=F()?!1:A?W:!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=Vu(r,T,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,b;o.emit("message:copy",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onCopy)==null||b.call(g,c)},onFeedback:c=>{var g,b;o.emit("message:feedback",c),S!=null&&S.isClientTokenMode()&&S.submitMessageFeedback(c.messageId,c.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(b=(g=r.messageActions)==null?void 0:g.onFeedback)==null||b.call(g,c)}},te=(ec=r.statusIndicator)!=null?ec:{},We=c=>{var g,b,y,k;return c==="idle"?(g=te.idleText)!=null?g:fn.idle:c==="connecting"?(b=te.connectingText)!=null?b:fn.connecting:c==="connected"?(y=te.connectedText)!=null?y:fn.connected:c==="error"?(k=te.errorText)!=null?k:fn.error:fn[c]};function ge(c,g,b,y){if(y==="idle"&&b.idleLink){c.textContent="";let k=document.createElement("a");k.href=b.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}=iu(r),Ce=lu(r,_()),{container:de,body:X,messagesWrapper:$e,suggestions:Ct,textarea:G,sendButton:Oe,sendButtonWrapper:Mn,composerForm:Dt,statusText:ln,introTitle:Hn,introSubtitle:Xn,closeButton:B,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,be=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"},bn=()=>ve.enabled!==!1,Et=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");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let St=h("span","persona-flex persona-items-center"),ht=h("span","");Et.append(St,ht),de.appendChild(Et);let yt=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;Et.style.bottom=`${g+wt}px`};yt();let qt=()=>{let c=!!_t();Et.setAttribute("aria-label",_t()||"Jump to latest"),Et.title=_t(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),St.innerHTML="";let g=ye(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 yn=()=>{var g,b,y,k;if(!V)return;if(me=!0,!fe&&V&&(fe=Wu({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>Dn(),config:r,plugins:s,getThroughput:()=>{var N;return(N=pe==null?void 0:pe.getMetric())!=null?N:{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 ${En.actionIconColor}`;let N=(k=(y=(b=r.features)==null?void 0:b.eventStream)==null?void 0:y.classNames)==null?void 0:k.toggleButtonActive;N&&N.split(/\s+/).forEach(O=>O&&ut.classList.add(O))}let c=()=>{if(!me)return;let N=Date.now();N-Ge>=200&&(fe==null||fe.update(),Ge=N),ue=requestAnimationFrame(c)};Ge=0,ue=requestAnimationFrame(c),Wr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Dn=()=>{var c,g,b;if(me){if(me=!1,fe&&fe.element.remove(),X.style.display="",ut){ut.style.boxShadow="";let y=(b=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:b.toggleButtonActive;y&&y.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=En.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let b=ye("activity","18px","currentColor",1.5);b&&ut.appendChild(b);let y=Ce.clearChatButtonWrapper,k=Ce.closeButtonWrapper,N=y||k;N&&N.parentNode===Fe?Fe.insertBefore(ut,N):Fe.appendChild(ut),ut.addEventListener("click",()=>{me?Dn():yn()})}let xr=c=>{var y,k,N;let g=r.attachments;if(!(g!=null&&g.enabled))return;let b=c.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.style.display="none";let O=c.querySelector("[data-persona-composer-form]");O!=null&&O.parentNode?O.parentNode.insertBefore(b,O):c.insertBefore(b,c.firstChild)}if(!c.querySelector('input[type="file"]')){let O=h("input");O.type="file",O.accept=((y=g.allowedTypes)!=null?y:Nr).join(","),O.multiple=((k=g.maxFiles)!=null?k:4)>1,O.style.display="none",O.setAttribute("aria-label",(N=g.buttonTooltipText)!=null?N:"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:b=>{var O;if(!S||S.isStreaming())return;let y=b.trim(),k=(O=et==null?void 0:et.hasAttachments())!=null?O:!1;if(!y&&!k)return;gs();let N;k&&(N=[],N.push(...et.getContentParts()),y&&N.push(La(y))),S.sendMessage(y,{contentParts:N}),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:b=>{r.composer={...r.composer,selectedModelId:b},r.agent&&(r.agent={...r.agent,model:b})},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]"),b=c.querySelector("[data-persona-composer-input]"),y=c.querySelector("[data-persona-composer-submit]"),k=c.querySelector("[data-persona-composer-mic]"),N=c.querySelector("[data-persona-composer-status]");g&&(Dt=g),b&&(G=b),y&&(Oe=y),k&&(K=k,gt=k.parentElement),N&&(ln=N);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"]'),be=c.querySelector(".persona-attachment-previews");let H=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");H&&(rt=H)};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&&be&&!F()&&(be.style.maxWidth=kn,be.style.marginLeft="auto",be.style.marginRight="auto"),(cc=r.attachments)!=null&&cc.enabled&&se&&be){et=Ko.fromConfig(r.attachments),et.setPreviewsContainer(be),se.addEventListener("change",b=>{let y=b.target;et==null||et.handleFileSelect(y.files),y.value=""});let c=r.attachments.dropOverlay,g=Ku(c);de.appendChild(g)}(()=>{var y,k;let c=(k=(y=r.layout)==null?void 0:y.slots)!=null?k:{},g=N=>{switch(N){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}},b=(N,O)=>{var U;switch(N){case"header-left":case"header-center":case"header-right":if(N==="header-left")Fe.insertBefore(O,Fe.firstChild);else if(N==="header-right")Fe.appendChild(O);else{let H=Fe.querySelector(".persona-flex-col");H?(U=H.parentNode)==null||U.insertBefore(O,H.nextSibling):Fe.appendChild(O)}break;case"body-top":{let H=X.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.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[N,O]of Object.entries(c))if(O)try{let U=O({config:r,defaultContent:()=>g(N)});U&&b(N,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${N}":`,U)}})();let Fr=c=>{let b=c.target.closest('button[data-expand-header="true"]');if(!b)return;let y=b.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!y)return;let k=y.getAttribute("data-message-id");if(!k)return;let N=b.getAttribute("data-bubble-type");N==="reasoning"?(Qo.has(k)?Qo.delete(k):Qo.add(k),mu(k,y)):N==="tool"&&(Yo.has(k)?Yo.delete(k):Yo.add(k),gu(k,y,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 Er=new Map;$e.addEventListener("click",c=>{var O;let b=c.target.closest(".persona-message-action-btn[data-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest("[data-actions-for]");if(!y)return;let k=y.getAttribute("data-actions-for");if(!k)return;let N=b.getAttribute("data-action");if(N==="copy"){let H=S.getMessages().find(we=>we.id===k);if(H&&z.onCopy){let we=H.content||"";navigator.clipboard.writeText(we).then(()=>{b.classList.add("persona-message-action-success");let le=ye("check",14,"currentColor",2);le&&(b.innerHTML="",b.appendChild(le)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ee=ye("copy",14,"currentColor",2);ee&&(b.innerHTML="",b.appendChild(ee))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),z.onCopy(H)}}else if(N==="upvote"||N==="downvote"){let H=((O=Er.get(k))!=null?O:null)===N,we=N==="upvote"?"thumbs-up":"thumbs-down";if(H){Er.delete(k),b.classList.remove("persona-message-action-active");let le=ye(we,14,"currentColor",2);le&&(b.innerHTML="",b.appendChild(le))}else{let le=N==="upvote"?"downvote":"upvote",ee=y.querySelector(`[data-action="${le}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Je=ye(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Je&&(ee.innerHTML="",ee.appendChild(Je))}Er.set(k,N),b.classList.add("persona-message-action-active");let he=ye(we,14,"currentColor",2);he&&(he.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(he)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let He=S.getMessages().find(tt=>tt.id===k);He&&z.onFeedback&&z.onFeedback({type:N,messageId:He.id,message:He})}}}),$e.addEventListener("click",c=>{let b=c.target.closest("button[data-approval-action]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.closest(".persona-approval-bubble");if(!y)return;let k=y.getAttribute("data-message-id");if(!k)return;let N=b.getAttribute("data-approval-action");if(!N)return;let O=N==="approve"?"approved":"denied",H=S.getMessages().find(le=>le.id===k);if(!(H!=null&&H.approval))return;let we=y.querySelector("[data-approval-buttons]");we&&we.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?S.resolveWebMcpApproval(k,O):S.resolveApproval(H.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 b=c.target.closest("[data-download-artifact]");if(!b)return;c.preventDefault(),c.stopPropagation();let y=b.getAttribute("data-download-artifact");if(!y||((Ae=(he=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:he.onArtifactAction)==null?void 0:Ae.call(he,{type:"download",artifactId:y}))===!0)return;let N=S.getArtifactById(y),O=N==null?void 0:N.markdown,U=(N==null?void 0:N.title)||"artifact";if(!O){let Je=b.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 Te=S.getMessages().find(je=>je.id===lt);if(Te!=null&&Te.rawContent)try{let je=JSON.parse(Te.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 H=new Blob([O],{type:"text/markdown"}),we=URL.createObjectURL(H),le=document.createElement("a");le.href=we,le.download=`${U}.md`,le.click(),URL.revokeObjectURL(we)}),$e.addEventListener("click",c=>{var N,O,U;let b=c.target.closest("[data-open-artifact]");if(!b)return;let y=b.getAttribute("data-open-artifact");!y||((U=(O=(N=r.features)==null?void 0:N.artifacts)==null?void 0:O.onArtifactAction)==null?void 0:U.call(O,{type:"open",artifactId:y}))===!0||(c.preventDefault(),c.stopPropagation(),xn=!1,S.selectArtifact(y),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,b)=>{var U,H,we,le;let y=g.trim();if(!y||!Pt.current)return;let k=(U=c.getAttribute("data-tool-call-id"))!=null?U:"",N=b.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:y,answers:b.structured,values:(H=b.values)!=null?H:b.source==="multi"?y.split(", "):[y],isFreeText:N,source:b.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=b.structured)!=null?le:y):Pt.current.sendMessage(y)},_n=c=>{var k;let g=Pt.current;if(!g)return;let b=(k=c.getAttribute("data-tool-call-id"))!=null?k:"",y=g.getMessages().find(N=>{var O;return((O=N.toolCall)==null?void 0:O.id)===b});y&&g.persistAskUserQuestionProgress(y,{answers:ni(c,y),currentIndex:ar(c)})},_r=c=>Object.entries(c).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Mr=c=>{var k,N,O;if(((N=(k=r.features)==null?void 0:k.askUserQuestion)==null?void 0:N.groupedAutoAdvance)===!1)return;let g=ar(c),b=es(c);if(g>=b-1)return;let y=(O=Pt.current)==null?void 0:O.getMessages().find(U=>{var H;return((H=U.toolCall)==null?void 0:H.id)===c.getAttribute("data-tool-call-id")});y&&(ri(c,y,r,g+1),_n(c))};Yn.addEventListener("click",c=>{var N,O,U,H,we,le,ee,he,Ae,He,tt,Je,it,lt;let b=c.target.closest("[data-ask-user-action]");if(!b)return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;let k=b.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),k==="dismiss"){let Ee=(N=y.getAttribute("data-tool-call-id"))!=null?N:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ee},bubbles:!0,composed:!0})),ko(Yn,Ee);let Te=(O=Pt.current)==null?void 0:O.getMessages().find(je=>{var E;return((E=je.toolCall)==null?void 0:E.id)===Ee});(U=Te==null?void 0:Te.agentMetadata)!=null&&U.awaitingLocalTool&&((H=Pt.current)==null||H.markAskUserQuestionResolved(Te),(we=Pt.current)==null||we.resolveAskUserQuestion(Te,"(dismissed)"));return}if(k==="pick"){let Ee=b.getAttribute("data-option-label");if(!Ee)return;let Te=y.getAttribute("data-multi-select")==="true",je=so(y);if(je&&Te){let E=Mo(y)[ar(y)],Se=new Set(Array.isArray(E)?E:[]);Se.has(Ee)?Se.delete(Ee):Se.add(Ee),ao(y,Array.from(Se)),_n(y);return}if(je){ao(y,Ee),_n(y),Mr(y);return}if(Te){let E=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",E?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!E);let Se=y.querySelector('[data-ask-user-action="submit-multi"]');Se&&(Se.disabled=Gi(y).length===0);return}Zn(y,Ee,{source:"pick",values:[Ee]});return}if(k==="submit-multi"){let Ee=Gi(y);if(Ee.length===0)return;Zn(y,Ee.join(", "),{source:"multi",values:Ee});return}if(k==="open-free-text"){let Ee=y.querySelector('[data-ask-free-text-row="true"]');if(Ee){Ee.classList.remove("persona-hidden");let Te=Ee.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus()}return}if(k==="focus-free-text"){let Ee=y.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus();return}if(k==="submit-free-text"){let Ee=y.querySelector('[data-ask-free-text-input="true"]'),Te=(le=Ee==null?void 0:Ee.value)!=null?le:"";if(!Te.trim())return;if(so(y)){ao(y,Te.trim()),_n(y),Mr(y);return}Zn(y,Te,{source:"free-text"});return}if(k==="next"||k==="back"){if(!Pt.current)return;let Ee=(ee=y.getAttribute("data-tool-call-id"))!=null?ee:"",Te=Pt.current.getMessages().find(ze=>{var xe;return((xe=ze.toolCall)==null?void 0:xe.id)===Ee});if(!Te)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),E=(Ae=(he=je==null?void 0:je.value)==null?void 0:he.trim())!=null?Ae:"";if(E){let ze=Mo(y)[ar(y)];(typeof ze!="string"||ze!==E)&&ao(y,E)}let Se=k==="next"?1:-1,Pe=ar(y)+Se;ri(y,Te,r,Pe),_n(y);return}if(k==="submit-all"){if(!Pt.current)return;let Ee=(He=y.getAttribute("data-tool-call-id"))!=null?He:"",Te=Pt.current.getMessages().find(ze=>{var xe;return((xe=ze.toolCall)==null?void 0:xe.id)===Ee});if(!Te)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),E=(Je=(tt=je==null?void 0:je.value)==null?void 0:tt.trim())!=null?Je:"";E&&ao(y,E);let Se=ni(y,Te);Pt.current.persistAskUserQuestionProgress(Te,{answers:Se,currentIndex:ar(y)});let Pe=_r(Se);Zn(y,Pe||"(submitted)",{source:"submit-all",structured:Se});return}if(k==="skip"){if(!Pt.current)return;let Ee=(it=y.getAttribute("data-tool-call-id"))!=null?it:"",Te=Pt.current.getMessages().find(xe=>{var Lt;return((Lt=xe.toolCall)==null?void 0:Lt.id)===Ee});if(!Te)return;let je=so(y),E=ar(y),Se=es(y),Pe=E>=Se-1;if(!je){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ee},bubbles:!0,composed:!0})),ko(Yn,Ee),(lt=Te.agentMetadata)!=null&&lt.awaitingLocalTool&&(Pt.current.markAskUserQuestionResolved(Te),Pt.current.resolveAskUserQuestion(Te,"(dismissed)"));return}ao(y,"");let ze=y.querySelector('[data-ask-free-text-input="true"]');if(ze&&(ze.value=""),Pe){let xe=ni(y,Te),Lt=_r(xe);Zn(y,Lt||"(skipped)",{source:"submit-all",structured:xe});return}ri(y,Te,r,E+1),_n(y);return}}),Yn.addEventListener("keydown",c=>{var N;if(c.key!=="Enter")return;let b=c.target;if(!((N=b.matches)!=null&&N.call(b,'[data-ask-free-text-input="true"]')))return;let y=b.closest("[data-persona-ask-sheet-for]");if(!y)return;c.preventDefault();let k=b.value;if(k.trim()){if(so(y)){ao(y,k.trim()),_n(y),Mr(y);return}Zn(y,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 b=Yn.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let y=Number(c.key),N=b.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];N&&(c.preventDefault(),N.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"),b=((O=e.ownerDocument.defaultView)!=null?O:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||b){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 y=$n.firstElementChild;if(!y||y===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 N=y.offsetWidth-k/2;Wt.style.left=`${Math.max(0,N)}px`},vr=()=>{},jn=()=>{var b,y,k,N,O;if(!xt||!ir(r))return;si(e,r),ai(e,r),vr();let c=(N=(k=(y=(b=r.features)==null?void 0:b.artifacts)==null?void 0:y.layout)==null?void 0:k.narrowHostMaxWidth)!=null?N: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=Bu(r,{onSelect:b=>{var y;return(y=Pt.current)==null?void 0:y.selectArtifact(b)},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 y,k,N,O;if(!$n||!xt)return;if(!(((N=(k=(y=r.features)==null?void 0:y.artifacts)==null?void 0:k.layout)==null?void 0:N.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 H=e.ownerDocument,we=(O=H.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=Ee=>{let Te=$n.getBoundingClientRect().width,je=e.classList.contains("persona-artifact-appearance-seamless"),E=je?0:Fu($n,we),Se=je?0:U.getBoundingClientRect().width||6,Pe=Ae-(Ee.clientX-he),ze=_u(Pe,Te,E,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=()=>{H.removeEventListener("pointermove",tt),H.removeEventListener("pointerup",Je),H.removeEventListener("pointercancel",Je),er=null;try{U.releasePointerCapture(ee.pointerId)}catch{}};er=Je,H.addEventListener("pointermove",tt),H.addEventListener("pointerup",Je),H.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,Ee,Te,je,E;if(!A||!xt||((le=(we=r.launcher)==null?void 0:we.sidebarMode)!=null?le:!1)||an(r)&&br(r).reveal==="emerge")return;let y=(ee=e.ownerDocument.defaultView)!=null?ee:window,k=(Ae=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?Ae:!0,N=(tt=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?tt:640;if(k&&y.innerWidth<=N||!Ou(r,A))return;let O=(lt=(it=(Je=r.launcher)==null?void 0:Je.width)!=null?it:r.launcherWidth)!=null?lt:sr,U=(E=(je=(Te=(Ee=r.features)==null?void 0:Ee.artifacts)==null?void 0:Te.layout)==null?void 0:je.expandedPanelWidth)!=null?E:"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,bo,yo,Fo,_o,zt,xo,Yr,bt,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,ba)=>{var Cs;return vo==null||vo===""?ba:(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,b=c||g||((pn=(Cn=r.launcher)==null?void 0:Cn.fullHeight)!=null?pn:!1),y=((Ze=r.launcher)==null?void 0:Ze.enabled)===!1,k=(An=(ct=r.theme)==null?void 0:ct.components)==null?void 0:An.panel,N=Hs(r),O=(Bt,Vt)=>{var Wn;return Bt==null||Bt===""?Vt:(Wn=Jo(N,Bt))!=null?Wn:Bt},U=(mn=e.ownerDocument.defaultView)!=null?mn:window,H=(bo=(ho=r.launcher)==null?void 0:ho.mobileFullscreen)!=null?bo:!0,we=(Fo=(yo=r.launcher)==null?void 0:yo.mobileBreakpoint)!=null?Fo:640,le=U.innerWidth<=we,ee=H&&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),Ee=O(k==null?void 0:k.shadow,Je),Te=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 E=()=>{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;
@@ -63,7 +63,7 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
63
63
  overflow: hidden !important;
64
64
  border-radius: 0 !important;
65
65
  border: none !important;
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=`
66
+ `,X.style.flex="1 1 0%",X.style.minHeight="0",X.style.overflowY="auto",_e.style.flexShrink="0",R=!0,E();return}let Se=(Pn=(bt=r==null?void 0:r.launcher)==null?void 0:bt.width)!=null?Pn:r==null?void 0:r.launcherWidth,Pe=Se!=null?Se:sr;if(!g&&!c)y&&b?(ae.style.width="100%",ae.style.maxWidth="100%"):(ae.style.width=Pe,ae.style.maxWidth=Pe);else if(c)if(br(r).reveal==="emerge"){let Vt=br(r).width;ae.style.width=Vt,ae.style.maxWidth=Vt}else ae.style.width="100%",ae.style.maxWidth="100%";if(vr(),ae.style.boxShadow=Ee,ae.style.borderRadius=Te,de.style.border=lt,de.style.borderRadius=Te,c&&!ee&&(k==null?void 0:k.border)===void 0&&(de.style.border="none",br(r).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),b&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(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%",y&&(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&&!y&&!c&&((Br=yr[he])!=null?Br:yr["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;
@@ -87,8 +87,8 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
87
87
  min-height: 0 !important;
88
88
  margin: 0 !important;
89
89
  padding: 0 !important;
90
- box-shadow: ${Te} !important;
91
- border-radius: ${Ee} !important;
90
+ box-shadow: ${Ee} !important;
91
+ border-radius: ${Te} !important;
92
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;
@@ -98,19 +98,19 @@ _Details: ${n.message}_`:r}var Is=class e{constructor(t={},n){this.config=t;this
98
98
  min-height: 0 !important;
99
99
  max-height: 100% !important;
100
100
  overflow: hidden !important;
101
- border-radius: ${Ee} !important;
101
+ border-radius: ${Te} !important;
102
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 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:
107
+ `}if(!y&&!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}E()};lr(),To(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(()=>{To(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(()=>tu(e)))}let cr=ku(Ct),qn=null,S,zn=!1,dr=Gp(),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 y,k;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let c=dl(d.voiceState),g=!!c.active,b=Number((k=c.timestamp)!=null?k:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-b<Cy&&setTimeout(()=>{var N,O;mt.active||(mt.manuallyDeactivated=!1,((O=(N=r.voiceRecognition)==null?void 0:N.provider)==null?void 0:O.type)==="runtype"?S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("restore"),S.isVoiceActive()&&M()}):fo("restore"))},1e3)},ta=()=>S?zu(S.getMessages()).filter(c=>!c.__skipPersist):[];function Wo(c){if(!(i!=null&&i.save))return;let b={messages:c?zu(c):S?ta():[],metadata:d,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let y=i.save(b);y instanceof Promise&&y.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}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(!bn()||me){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==de&&de.appendChild(Et),yt();let c=Bs(X)>0;Et.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 b=c.scrollTop,y=Bs(c),k=y-b;if(Math.abs(k)<1){ur=c.scrollTop;return}if(Math.abs(k)>=Zs){uo(),Pr=!0,c.scrollTop=y,ur=c.scrollTop,Pr=!1;return}uo();let N=performance.now();Pr=!0;let O=H=>1-Math.pow(1-H,3),U=H=>{if(!pr.isFollowing()){uo();return}let we=Bs(c);we!==y&&(y=we,k=y-b);let le=H-N,ee=Math.min(le/g,1),he=O(ee),Ae=b+k*he;c.scrollTop=Ae,ur=c.scrollTop,ee<1?Ir=requestAnimationFrame(U):(c.scrollTop=y,ur=c.scrollTop,Ir=null,Pr=!1)};Ir=requestAnimationFrame(U)},oa=c=>{let g=new Map;c.forEach(b=>{let y=Io.get(b.id);g.set(b.id,{streaming:b.streaming,role:b.role}),!y&&b.role==="assistant"&&o.emit("assistant:message",b),b.role==="assistant"&&(y!=null&&y.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(y?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),Io.clear(),g.forEach((b,y)=>{Io.set(y,b)})},mo=(c,g,b)=>{var Je,it,lt,Ee,Te,je;let y=document.createElement("div"),N=(()=>{var Se;let E=s.find(Pe=>Pe.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((Se=r.loadingIndicator)!=null&&Se.render)return r.loadingIndicator.render})(),O=(E,Se)=>Se==null?!1:typeof Se=="string"?(E.textContent=Se,!0):(E.appendChild(Se),!0),U=new Set,H=new Set,we=s.some(E=>E.renderAskUserQuestion),le=[],ee=[],he=r.enableComponentStreaming!==!1;if(g.forEach(E=>{var Cn,pn,Ze,ct,An,mn,ho,bo,yo,Fo,_o,zt,xo,Yr;U.add(E.id);let Se=we&&ro(E),Pe=!Se&&E.role==="assistant"&&!E.variant&&he&&al(E);if(!Pe&&wr.has(E.id)){let bt=c.querySelector(`#wrapper-${E.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),wr.delete(E.id)}let ze=ro(E)?`:${(Cn=E.agentMetadata)!=null&&Cn.askUserQuestionAnswered?"a":"u"}:${(pn=E.agentMetadata)!=null&&pn.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",xe=Jp(E,ss)+ze,Lt=Se||Pe?null:Xp(dr,E.id,xe);if(Lt){y.appendChild(Lt.cloneNode(!0)),ro(E)&&((Ze=E.toolCall)!=null&&Ze.id)&&((ct=E.agentMetadata)==null?void 0:ct.awaitingLocalTool)===!0&&!((An=E.agentMetadata)!=null&&An.askUserQuestionAnswered)&&(H.add(E.toolCall.id),Js(E,r,Ce.composerOverlay));return}let st=null,Qt=s.find(bt=>!!(E.variant==="reasoning"&&bt.renderReasoning||E.variant==="tool"&&bt.renderToolCall||E.variant==="approval"&&bt.renderApproval||!E.variant&&bt.renderMessage)),dn=(mn=r.layout)==null?void 0:mn.messages;if(ro(E)&&((ho=E.agentMetadata)==null?void 0:ho.askUserQuestionAnswered)===!0){Lr.delete(E.id);let bt=c.querySelector(`#wrapper-${E.id}`);bt==null||bt.removeAttribute("data-preserve-runtime");return}if(ro(E)&&((yo=(bo=r.features)==null?void 0:bo.askUserQuestion)==null?void 0:yo.enabled)!==!1){let bt=s.find(Pn=>typeof Pn.renderAskUserQuestion=="function");if(bt&&Pt.current){let Pn=Lr.get(E.id),Br=Pn!==xe,Sn=null;if(Br){let{payload:$t,complete:Bt}=oo(E),Vt=E.id,Wn=()=>{var Kn;return(Kn=Pt.current)==null?void 0:Kn.getMessages().find(nn=>nn.id===Vt)};Sn=bt.renderAskUserQuestion({message:E,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=E.agentMetadata)==null?void 0:Fo.awaitingLocalTool)===!0&&!((_o=E.agentMetadata)!=null&&_o.askUserQuestionAnswered)&&(H.add(E.toolCall.id),Js(E,r,Ce.composerOverlay));return}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${E.id}`,Ht.setAttribute("data-wrapper-id",E.id),Ht.setAttribute("data-ask-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),y.appendChild(Ht),le.push({messageId:E.id,fingerprint:xe,bubble:Sn});return}else{((zt=E.agentMetadata)==null?void 0:zt.awaitingLocalTool)===!0&&!((xo=E.agentMetadata)!=null&&xo.askUserQuestionAnswered)&&(H.add(E.toolCall.id),Js(E,r,Ce.composerOverlay));return}}else if(Qt)if(E.variant==="reasoning"&&E.reasoning&&Qt.renderReasoning){if(!Re)return;st=Qt.renderReasoning({message:E,defaultRenderer:()=>ji(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Qt.renderToolCall){if(!Ne)return;st=Qt.renderToolCall({message:E,defaultRenderer:()=>Ui(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Qt.renderApproval){if(r.approval===!1)return;st=Qt.renderApproval({message:E,defaultRenderer:()=>Xi(E,r),config:r})}else Qt.renderMessage&&(st=Qt.renderMessage({message:E,defaultRenderer:()=>{let bt=Vs(E,b,dn,r.messageActions,z,{loadingIndicatorRenderer:N,widgetConfig:r});return E.role!=="user"&&el(bt,E,r,S),bt},config:r}));if(!st&&Pe){let bt=il(E);if(bt){let Pn=wr.get(E.id),Br=Pn!==xe,Sn=r.wrapComponentDirectiveInBubble!==!1,In=null;if(Br){let Ht=sl(bt,{config:r,message:E,transform:b});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-${E.id}`,$t.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let Bt=document.createElement("div");Bt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Bt.innerHTML=b({text:E.content,message:E,streaming:!!E.streaming,raw:E.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-${E.id}`,$t.setAttribute("data-message-id",E.id),$t.setAttribute("data-persona-component-directive","true"),E.content&&E.content.trim()){let Bt=document.createElement("div");Bt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Bt.innerHTML=b({text:E.content,message:E,streaming:!!E.streaming,raw:E.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-${E.id}`,Ht.setAttribute("data-wrapper-id",E.id),Ht.setAttribute("data-component-directive-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),Sn||Ht.classList.add("persona-w-full"),y.appendChild(Ht),ee.push({messageId:E.id,fingerprint:xe,bubble:In});return}}}if(!st)if(E.variant==="reasoning"&&E.reasoning){if(!Re)return;st=ji(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Ne)return;st=Ui(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;st=Xi(E,r)}else{let bt=(Yr=r.layout)==null?void 0:Yr.messages;bt!=null&&bt.renderUserMessage&&E.role==="user"?st=bt.renderUserMessage({message:E,config:r,streaming:!!E.streaming}):bt!=null&&bt.renderAssistantMessage&&E.role==="assistant"?st=bt.renderAssistantMessage({message:E,config:r,streaming:!!E.streaming}):st=Vs(E,b,bt,r.messageActions,z,{loadingIndicatorRenderer:N,widgetConfig:r}),E.role!=="user"&&st&&el(st,E,r,S)}let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-${E.id}`,It.setAttribute("data-wrapper-id",E.id),E.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),Qp(dr,E.id,xe,It),y.appendChild(It)}),Ce.composerOverlay&&Ce.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Se=>{let Pe=Se.getAttribute("data-persona-ask-sheet-for");Pe&&!H.has(Pe)&&ko(Ce.composerOverlay,Pe)}),(it=(Je=r.features)==null?void 0:Je.toolCallDisplay)!=null&&it.grouped){let E=[],Se=[];g.forEach(Pe=>{if(Pe.variant==="tool"&&Pe.toolCall&&Ne){Se.push(Pe);return}Se.length>1&&E.push(Se),Se=[]}),Se.length>1&&E.push(Se),E.forEach((Pe,ze)=>{var pn,Ze;let xe=Pe.map(ct=>Array.from(y.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)})})}Yp(dr,U);let Ae=g.some(E=>E.role==="assistant"&&E.streaming),He=g[g.length-1],tt=(He==null?void 0:He.role)==="assistant"&&!He.streaming&&He.variant!=="approval";if(zn&&g.some(E=>E.role==="user")&&!Ae&&!tt){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:Xo},Se=s.find(ze=>ze.renderLoadingIndicator),Pe=null;if(Se!=null&&Se.renderLoadingIndicator&&(Pe=Se.renderLoadingIndicator(E)),Pe===null&&((lt=r.loadingIndicator)!=null&&lt.render)&&(Pe=r.loadingIndicator.render(E)),Pe===null&&(Pe=Xo()),Pe){let ze=document.createElement("div"),xe=((Ee=r.loadingIndicator)==null?void 0:Ee.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),y.appendChild(Lt)}}if(!zn&&g.length>0){let E=g[g.length-1],Se={config:r,lastMessage:E,messageCount:g.length},Pe=s.find(xe=>xe.renderIdleIndicator),ze=null;if(Pe!=null&&Pe.renderIdleIndicator&&(ze=Pe.renderIdleIndicator(Se)),ze===null&&((Te=r.loadingIndicator)!=null&&Te.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),y.appendChild(st)}}if(Da(c,y),le.length>0)for(let{messageId:E,fingerprint:Se,bubble:Pe}of le){let ze=c.querySelector(`#wrapper-${E}`);ze&&Pe!==null&&(ze.replaceChildren(Pe),ze.setAttribute("data-bubble-fp",Se),Lr.set(E,Se))}if(Lr.size>0)for(let E of Lr.keys())U.has(E)||Lr.delete(E);if(ee.length>0)for(let{messageId:E,fingerprint:Se,bubble:Pe}of ee){let ze=c.querySelector(`#wrapper-${E}`);ze&&Pe!==null&&(ze.replaceChildren(Pe),ze.setAttribute("data-bubble-fp",Se),wr.set(E,Se))}if(wr.size>0)for(let E of wr.keys())U.has(E)||wr.delete(E)},Kr=null,sa=()=>{var b;if(Kr)return;let c=y=>{let k=y.composedPath();k.includes(ie)||Qe&&k.includes(Qe)||Rt(!1,"user")};Kr=c,((b=e.ownerDocument)!=null?b: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 b;if(Jr)return;let c=y=>{y.key==="Escape"&&(y.isComposing||Rt(!1,"user"))};Jr=c,((b=e.ownerDocument)!=null?b: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,b,y,k;let c=(y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.peek)==null?void 0:y.streamAnimation;return c||((k=r.features)==null?void 0:k.streamAnimation)},Rr=()=>{var it,lt,Ee,Te;if(!F())return;let c=Ce.peekBanner,g=Ce.peekTextNode;if(!c||!g)return;if(D){c.classList.remove("persona-pill-peek--visible");return}let b=(it=S==null?void 0:S.getMessages())!=null?it:[],y;for(let je=b.length-1;je>=0;je--){let E=b[je];if(E.role==="assistant"&&E.content){y=E;break}}if(!y){c.classList.remove("persona-pill-peek--visible");return}let k=y.content,N=!!y.streaming,O=ia(),U=$a(O),H=U.type!=="none"?Fs(U.type,O==null?void 0:O.plugins):null,we=((lt=H==null?void 0:H.isAnimating)==null?void 0:lt.call(H,y))===!0,le=H!==null&&(N||we);le&&H&&!us.has(H.name)&&(Bi(H,e),us.add(H.name));let ee=le&&(H!=null&&H.containerClass)?H.containerClass:null,he=(Ee=g.dataset.personaPeekStreamClass)!=null?Ee: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,H,y,N):k;if(le&&U.placeholder==="skeleton"&&N&&(!Ae||!Ae.trim())){let je=document.createElement("div"),E=$s();E.classList.add("persona-pill-peek__skeleton"),je.appendChild(E),Da(g,je)}else{let je=Math.max(0,Ae.length-100),E=Ae.length>100?Ae.slice(-100):Ae,Se=jo(E);if(!le||!H){let Pe=Ae.length>100?`\u2026${E}`:E;g.textContent!==Pe&&(g.textContent=Pe)}else{let Pe=Se;(H.wrap==="char"||H.wrap==="word")&&(Pe=_s(Se,H.wrap,`peek-${y.id}`,{skipTags:H.skipTags,startIndex:je}));let ze=document.createElement("div");if(ze.innerHTML=Pe,H.useCaret&&E.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),(Te=H.onAfterRender)==null||Te.call(H,{container:g,bubble:c,messageId:y.id,message:y,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 y=k=>{k.preventDefault(),k.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",y),ft.push(()=>{c.removeEventListener("pointerdown",y)})}let g=()=>{Gr||(Gr=!0,Rr())},b=()=>{Gr&&(Gr=!1,Rr())};ae.addEventListener("pointerenter",g),ae.addEventListener("pointerleave",b),ft.push(()=>{ae.removeEventListener("pointerenter",g),ae.removeEventListener("pointerleave",b)}),Qe&&(Qe.addEventListener("pointerenter",g),Qe.addEventListener("pointerleave",b),ft.push(()=>{Qe.removeEventListener("pointerenter",g),Qe.removeEventListener("pointerleave",b)}))}let la=c=>{var he,Ae,He,tt,Je,it,lt,Ee;let g=(Ae=(he=r.launcher)==null?void 0:he.composerBar)!=null?Ae:{},b=(He=g.expandedSize)!=null?He:"anchored",y=(tt=g.bottomOffset)!=null?tt:"16px",k=g.collapsedMaxWidth,N=(Je=g.expandedMaxWidth)!=null?Je:"880px",O=(it=g.expandedTopOffset)!=null?it:"5vh",U=(lt=g.modalMaxWidth)!=null?lt:"880px",H=(Ee=g.modalMaxHeight)!=null?Ee:"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 Te=Qe.style;Te.bottom=y,Te.width=k!=null?k:""}if(c&&b!=="fullscreen"){if(b==="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=H,ee.height=H;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${y} + ${le})`,ee.top=O,ee.width=N,ee.maxWidth=we}},Xr=()=>{var H,we,le,ee,he,Ae,He,tt;if(!_())return;if(F()){let it=(le=((we=(H=r.launcher)==null?void 0:H.composerBar)!=null?we:{}).expandedSize)!=null?le:"anchored",lt=D?"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(D),de.style.display=D?"flex":"none",lr(),D?(sa(),aa()):(ds(),ps()),Rr();return}let c=an(r),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,b=(Ae=(he=r.launcher)==null?void 0:he.mobileBreakpoint)!=null?Ae:640,y=(tt=(He=r.launcher)==null?void 0:He.mobileFullscreen)!=null?tt:!0,k=g.innerWidth<=b,N=y&&k&&A,O=br(r).reveal;D?(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")&&!N?(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 N,O;if(!_()||D===c)return;let b=D;D=c,Xr();let y=(()=>{var He,tt,Je,it,lt,Ee,Te,je,E,Se;let U=(tt=(He=r.launcher)==null?void 0:He.sidebarMode)!=null?tt:!1,H=(Je=e.ownerDocument.defaultView)!=null?Je:window,we=(lt=(it=r.launcher)==null?void 0:it.mobileFullscreen)!=null?lt:!0,le=(Te=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?Te:640,ee=H.innerWidth<=le,he=an(r)&&we&&ee,Ae=F()&&((Se=(E=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:E.expandedSize)!=null?Se:"fullscreen")==="fullscreen";return U||we&&ee&&A||he||Ae})();if(D&&y){if(!Jt){let U=e.getRootNode(),H=U instanceof ShadowRoot?U.host:e.closest(".persona-host");H&&(Jt=Di(H,(O=(N=r.launcher)==null?void 0:N.zIndex)!=null?O:hn))}Gt||(Gt=Ni(e.ownerDocument))}else D||(Jt==null||Jt(),Jt=null,Gt==null||Gt(),Gt=null);D&&(Xt(),Vr(!0));let k={open:D,source:g,timestamp:Date.now()};D&&!b?o.emit("widget:opened",k):!D&&b&&o.emit("widget:closed",k),o.emit("widget:state",{open:D,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 b,y,k,N,O,U,H,we,le,ee,he;Hn.textContent=(y=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?y:"Hello \u{1F44B}",Xn.textContent=(N=(k=r.copy)==null?void 0:k.welcomeSubtitle)!=null?N:"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=((H=r.copy)==null?void 0:H.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(b=>{let y=Number(b.getAttribute("data-tool-elapsed"));y&&(b.textContent=Aa(g-y))})},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(y=>y.role==="user"),b=mt.lastUserMessageId;g&&g.id!==b&&(mt.lastUserMessageId=g.id,o.emit("user:message",g)),mt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Wo(c),Rr()},onStatusChanged(c){var y;let g=(y=r.statusIndicator)!=null?y:{};ge(ln,(k=>{var N,O,U,H;return k==="idle"?(N=g.idleText)!=null?N:fn.idle:k==="connecting"?(O=g.connectingText)!=null?O:fn.connecting:k==="connected"?(U=g.connectedText)!=null?U:fn.connected:k==="error"?(H=g.errorText)!=null?H: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,b;if(((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.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 b;(b=r.onSSEEvent)==null||b.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,b,y;c&&(c.metadata&&(d=dl(c.metadata),T.syncFromMetadata()),(g=c.messages)!=null&&g.length&&S.hydrateMessages(c.messages),(b=c.artifacts)!=null&&b.length&&S.hydrateArtifacts(c.artifacts,(y=c.selectedArtifactId)!=null?y:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let gs=()=>{var g,b,y;!F()||D||!((y=(b=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:b.expandOnSubmit)==null||y)||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(),b=(k=et==null?void 0:et.hasAttachments())!=null?k:!1;if(!g&&!b)return;gs();let y;b&&(y=[],y.push(...et.getContentParts()),g&&y.push(La(g))),G.value="",G.style.height="auto",go(),S.sendMessage(g,{contentParts:y}),b&&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()},bs=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,b=Kp({direction:c.key==="ArrowUp"?"up":"down",history:pa(),currentValue:G.value,atStart:g,state:Bo});if(Bo=b.state,b.handled){c.preventDefault(),b.value!==void 0&&ua(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(S.isStreaming()){c.preventDefault();return}go(),c.preventDefault(),Oe.click()}}},ys=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 b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!et)return;let g=Sy(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 N,O,U,H,we,le,ee;if(Vn||S.isStreaming())return;let g=vs();if(!g)return;wn=new g;let y=(O=((N=r.voiceRecognition)!=null?N:{}).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}))},y))},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:(H=he.iconName)!=null?H:"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,Ee,Te,je,E,Se,Pe;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((it=c==null?void 0:c.provider)==null?void 0:it.type)==="runtype";if(!(b||y))return null;let N=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",H=(Ee=g==null?void 0:g.size)!=null?Ee:"40px",we=(Te=c==null?void 0:c.iconSize)!=null?Te:H,le=parseFloat(we)||24,ee=(je=c==null?void 0:c.backgroundColor)!=null?je:g==null?void 0:g.backgroundColor,he=(E=c==null?void 0:c.iconColor)!=null?E: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=ye(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),N.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,N.appendChild(ze)}return{micButton:O,micButtonWrapper:N}},Ue=()=>{var g,b,y,k,N;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:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((N=(k=c.iconSize)!=null?k:(y=r.sendButton)==null?void 0:y.size)!=null?N:"40")||24}},C=(c,g)=>{var N,O,U,H,we;if(!K)return;let b=K.querySelector("svg");b&&b.remove();let y=(we=ot==null?void 0:ot.iconSize)!=null?we:parseFloat((H=(U=(N=r.voiceRecognition)==null?void 0:N.iconSize)!=null?U:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,k=ye(c,y,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,b=c.recordingIconColor,y=c.recordingBorderColor;if($(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let N=K.querySelector("svg");N&&N.setAttribute("stroke",b)}y&&(K.style.borderColor=y),K.setAttribute("aria-label","Stop voice recognition")},Y=()=>{var U,H,we,le,ee,he,Ae,He;if(!K)return;Ue();let c=(U=r.voiceRecognition)!=null?U:{},g=S.getVoiceInterruptionMode(),b=(H=c.processingIconName)!=null?H:"loader",y=(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:"",N=(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=N;let O=y||"currentColor";K.style.color=O,C(b,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,Ee,Te;if(!K)return;Ue();let c=(we=r.voiceRecognition)!=null?we:{},g=S.getVoiceInterruptionMode(),b=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=(le=c.speakingIconName)!=null?le:b,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:"",N=(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=(Te=c.speakingBorderColor)!=null?Te:g==="barge-in"?(lt=c.recordingBorderColor)!=null?lt:"":(Ee=ot==null?void 0:ot.borderColor)!=null?Ee:"";$(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=N,K.style.borderColor=O;let U=k||"currentColor";K.style.color=U,C(y,U);let H=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",H),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},J=()=>{var c,g,b;K&&($(),ot&&(K.style.backgroundColor=(c=ot.backgroundColor)!=null?c:"",K.style.color=(g=ot.color)!=null?g:"",K.style.borderColor=(b=ot.borderColor)!=null?b:"",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 b=S.getVoiceStatus(),y=S.getVoiceInterruptionMode();if(y==="none"&&(b==="processing"||b==="speaking"))return;if(y==="cancel"&&(b==="processing"||b==="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 b=G.value.trim();mt.manuallyDeactivated=!0,Ln(),gr("user"),b&&(G.value="",G.style.height="auto",S.sendMessage(b))}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(!D,"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):D&&setTimeout(()=>Ho(),200));let Xt=()=>{var H,we,le,ee,he,Ae,He,tt,Je,it,lt,Ee,Te,je,E,Se,Pe,ze,xe,Lt,st,Qt;if(F()){yt(),Xr();return}let c=an(r),g=(we=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?we:!1,b=c||g||((ee=(le=r.launcher)==null?void 0:le.fullHeight)!=null?ee:!1),y=(he=e.ownerDocument.defaultView)!=null?he:window,k=(He=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?He:!0,N=(Je=(tt=r.launcher)==null?void 0:tt.mobileBreakpoint)!=null?Je:640,O=y.innerWidth<=N,U=k&&O&&A;try{if(U){lr(),To(e,r);return}if(R&&(R=!1,lr(),To(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(),!b){let dn=y.innerHeight,It=64,Cn=(Te=(Ee=r.launcher)==null?void 0:Ee.heightOffset)!=null?Te: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(yt(),Xr(),D&&A){let It=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((Se=(E=r.launcher)==null?void 0:E.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 Tt=(fc=e.ownerDocument.defaultView)!=null?fc:window;if(Tt.addEventListener("resize",Xt),ft.push(()=>Tt.removeEventListener("resize",Xt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yt()});c.observe(_e),ft.push(()=>c.disconnect())}ur=X.scrollTop;let kt=X.scrollHeight,rn=()=>{let c=X.scrollTop,g=X.scrollHeight,b=g<kt;kt=g;let{action:y,nextLastScrollTop:k}=Fa({following:pr.isFollowing(),currentScrollTop:c,lastScrollTop:ur,nearBottom:Ds(X,as),userScrollThreshold:Ys,isAutoScrolling:Pr||po||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ur=k,y==="resume"){zr();return}y==="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)),Et.addEventListener("click",()=>{X.scrollTop=X.scrollHeight,ur=X.scrollTop,zr(),Vr(!0)}),ft.push(()=>Et.remove()),ft.push(()=>{ls()});let cn=()=>{B&&(qn&&(B.removeEventListener("click",qn),qn=null),_()?(B.style.display="",qn=()=>{Rt(!1,"user")},B.addEventListener("click",qn)):B.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(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==rs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},T.syncFromMetadata(),V==null||V.clear(),pe==null||pe.reset(),fe==null||fe.update()})})(),Dt&&Dt.addEventListener("submit",fs),G==null||G.addEventListener("keydown",bs),G==null||G.addEventListener("input",hs),G==null||G.addEventListener("paste",xs);let rr=(hc=e.ownerDocument)!=null?hc:document;rr.addEventListener("keydown",ys,!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())},Tl=c=>{!di(c.dataTransfer)||!Oo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},El=c=>{var b;if(!di(c.dataTransfer)||!Oo())return;c.preventDefault(),c.stopPropagation(),vi();let g=Array.from((b=c.dataTransfer.files)!=null?b:[]);g.length!==0&&et.handleFiles(g)},Qr=!0;de.addEventListener("dragenter",Al,Qr),de.addEventListener("dragleave",Sl,Qr),e.addEventListener("dragover",Tl,Qr),e.addEventListener("drop",El,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",bs),G==null||G.removeEventListener("input",hs),G==null||G.removeEventListener("paste",xs),rr.removeEventListener("keydown",ys,!0)}),ft.push(()=>{de.removeEventListener("dragenter",Al,Qr),de.removeEventListener("dragleave",Sl,Qr),e.removeEventListener("dragover",Tl,Qr),e.removeEventListener("drop",El,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,ba,Cs,Ac,Sc,Tc,Ec,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,bd,yd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,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,bp,yp;let g=r.toolCall,b=r.messageActions,y=(nn=r.layout)==null?void 0:nn.messages,k=r.colorScheme,N=r.loadingIndicator,O=r.iterationDisplay,U=(Ar=r.features)==null?void 0:Ar.showReasoning,H=(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(),To(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,W=(Cs=(ba=r.launcher)==null?void 0:ba.autoExpand)!=null?Cs:!1,Re=(Sc=(Ac=r.features)==null?void 0:Ac.showReasoning)!=null?Sc:!0,Ne=(Ec=(Tc=r.features)==null?void 0:Tc.showToolCalls)!=null?Ec:!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=En.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Nt=ye("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():yn()})}}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,B=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":""),B&&(B.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"),yt(),Wr(),A!==L?A?Rt(W,"auto"):(D=!0,Xr()):W!==I&&Rt(W,"auto"),I=W,L=A,Xt(),cn();let Ee=JSON.stringify(c.toolCall)!==JSON.stringify(g),Te=JSON.stringify(r.messageActions)!==JSON.stringify(b),je=JSON.stringify(($c=r.layout)==null?void 0:$c.messages)!==JSON.stringify(y),E=((jc=r.loadingIndicator)==null?void 0:jc.render)!==(N==null?void 0:N.render)||((Uc=r.loadingIndicator)==null?void 0:Uc.renderIdle)!==(N==null?void 0:N.renderIdle)||((qc=r.loadingIndicator)==null?void 0:qc.showBubble)!==(N==null?void 0:N.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)!==(H!=null?H:!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);(Ee||Te||je||E||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=ye(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":""),B){((cd=(ld=r.layout)==null?void 0:ld.header)==null?void 0:cd.showCloseButton)===!1?B.style.display="none":B.style.display="";let vt=(dd=xe.closeButtonSize)!=null?dd:"32px",Nt=(pd=xe.closeButtonPlacement)!=null?pd:"inline";B.style.height=vt,B.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(B.style.color=xe.closeButtonColor||En.actionIconColor,xe.closeButtonBackgroundColor?(B.style.backgroundColor=xe.closeButtonBackgroundColor,B.classList.remove("hover:persona-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let pt=xe.closeButtonBorderWidth||"0px",sn=xe.closeButtonBorderColor||"transparent";B.style.border=`${pt} solid ${sn}`,B.classList.remove("persona-border-none")}else B.style.border="",B.classList.add("persona-border-none");xe.closeButtonBorderRadius?(B.style.borderRadius=xe.closeButtonBorderRadius,B.classList.remove("persona-rounded-full")):(B.style.borderRadius="",B.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(B.style.paddingLeft=xe.closeButtonPaddingX,B.style.paddingRight=xe.closeButtonPaddingX):(B.style.paddingLeft="",B.style.paddingRight=""),xe.closeButtonPaddingY?(B.style.paddingTop=xe.closeButtonPaddingY,B.style.paddingBottom=xe.closeButtonPaddingY):(B.style.paddingTop="",B.style.paddingBottom="");let gn=(hd=xe.closeButtonIconName)!=null?hd:"x",fr=(bd=xe.closeButtonIconText)!=null?bd:"\xD7";B.innerHTML="";let Tn=ye(gn,"28px","currentColor",1);Tn?B.appendChild(Tn):B.textContent=fr;let Yt=(yd=xe.closeButtonTooltipText)!=null?yd:"Close chat",Jn=(xd=xe.closeButtonShowTooltip)!=null?xd:!0;if(B.setAttribute("aria-label",Yt),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),Jn&&Yt)){let pt=null,sn=()=>{if(pt||!B)return;let wo=B.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=B.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),B.addEventListener("focus",sn),B.addEventListener("blur",Rn),dt._cleanupTooltip=()=>{Rn(),dt&&(dt.removeEventListener("mouseenter",sn),dt.removeEventListener("mouseleave",Rn)),B&&(B.removeEventListener("focus",sn),B.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 Tn=Ce.closeButtonWrapper;Tn&&!Tn.classList.contains("persona-absolute")&&(gn?Tn.classList.add("persona-ml-auto"):Tn.classList.remove("persona-ml-auto"))}}if(dt){if(!F()){let pt=(Td=Q.size)!=null?Td:"32px";Ze.style.height=pt,Ze.style.width=pt}let on=(Ed=Q.iconName)!=null?Ed:"refresh-cw",gn=(Md=Q.iconColor)!=null?Md:"";Ze.style.color=gn||En.actionIconColor,Ze.innerHTML="";let fr=F()?"14px":"20px",Tn=ye(on,fr,"currentColor",2);if(Tn&&Ze.appendChild(Tn),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];T=ci({parsers:An,handlers:mn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Vu(r,T,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,bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),yo=((Wd=(Id=r.voiceRecognition)==null?void 0:Id.provider)==null?void 0:Wd.type)==="runtype";if(ho&&(bo||yo))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=ye(Nt,on,gn,2);fr?K.appendChild(fr):K.textContent="\u{1F3A4}";let Tn=(_d=Q.backgroundColor)!=null?_d:vt.backgroundColor;Tn?K.style.backgroundColor=Tn: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";be||(be=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),be.style.display="none",Dt.insertBefore(be,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=ye(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 Tn=(Zd=Q.buttonTooltipText)!=null?Zd:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=Tn,Ut.appendChild(Yt),At.append(Ut),!et&&se&&be&&(et=Ko.fromConfig(Q),et.setPreviewsContainer(be),se.addEventListener("change",async()=>{et&&(se!=null&&se.files)&&(await et.handleFileSelect(se.files),se.value="")})),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(Ku(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",bt=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)",bt){let Q=parseFloat(Sn)||24,vt=(Ht==null?void 0:Ht.trim())||"currentColor",Nt=ye(bt,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=(bp=r.statusIndicator)!=null?bp:{},Wn=(yp=Vt.visible)!=null?yp:!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(!D,"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(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},T.syncFromMetadata(),V==null||V.clear(),pe==null||pe.reset(),fe==null||fe.update()},setMessage(c){return!G||S.isStreaming()?!1:(!D&&_()&&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?(!D&&_()&&Rt(!0,"system"),G.value="",G.style.height="auto",S.sendMessage(g),!0):!1},startVoiceRecognition(){var g,b;return S.isStreaming()?!1:((b=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:b.type)==="runtype"?(S.isVoiceActive()||(!D&&_()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,Ln(),S.toggleVoice().then(()=>{mt.active=S.isVoiceActive(),nr("user"),S.isVoiceActive()&&M()})),!0):Vn?!0:vs()?(!D&&_()&&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!D&&_()&&Rt(!0,"system"),S.injectMessage(c)},injectAssistantMessage(c){!D&&_()&&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!D&&_()&&Rt(!0,"system"),S.injectUserMessage(c)},injectSystemMessage(c){return!D&&_()&&Rt(!0,"system"),S.injectSystemMessage(c)},injectMessageBatch(c){return!D&&_()&&Rt(!0,"system"),S.injectMessageBatch(c)},injectComponentDirective(c){return!D&&_()&&Rt(!0,"system"),S.injectComponentDirective(c)},injectTestMessage(c){!D&&_()&&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||yn()},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&&!D&&!F()||!G?!1:(G.focus(),!0)},async resolveApproval(c,g){let y=S.getMessages().find(k=>{var N;return k.variant==="approval"&&((N=k.approval)==null?void 0:N.id)===c});if(!(y!=null&&y.approval))throw new Error(`Approval not found: ${c}`);if(y.approval.toolType==="webmcp"){S.resolveWebMcpApproval(y.id,g);return}return S.resolveApproval(y.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 _()&&D},isVoiceActive(){return mt.active},getState(){return{open:_()&&D,launcherEnabled:A,voiceActive:mt.active,streaming:S.isStreaming()}},showCSATFeedback(c){!D&&_()&&Rt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let b=ll({onSubmit:async(y,k)=>{var N;S.isClientTokenMode()&&await S.submitCSATFeedback(y,k),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,k)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!D&&_()&&Rt(!0,"system");let g=$e.querySelector(".persona-feedback-container");g&&g.remove();let b=cl({onSubmit:async(y,k)=>{var N;S.isClientTokenMode()&&await S.submitNPSFeedback(y,k),(N=c==null?void 0:c.onSubmit)==null||N.call(c,y,k)},onDismiss:c==null?void 0:c.onDismiss,...c});$e.appendChild(b),b.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&&B.removeEventListener("click",qn)}};if((((bc=t==null?void 0:t.debugTools)!=null?bc:!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:b=>b?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 H=U.detail;(!(H!=null&&H.instanceId)||H.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()},H=we=>{let le=we.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",H),ft.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",H)})}let b=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.showArtifacts()},y=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.hideArtifacts()},k=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&tn.upsertArtifact(H.artifact)},N=U=>{let H=U.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&tn.selectArtifact(H.id)},O=U=>{let H=U.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",N),window.addEventListener("persona:clearArtifacts",O),ft.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",N),window.removeEventListener("persona:clearArtifacts",O)})}let or=Ty(r.persistState);if(or&&_()){let c=Ey(or.storage),g=`${or.keyPrefix}widget-open`,b=`${or.keyPrefix}widget-voice`,y=`${or.keyPrefix}widget-voice-mode`;if(c){let k=((yc=or.persist)==null?void 0:yc.openState)&&c.getItem(g)==="true",N=((xc=or.persist)==null?void 0:xc.voiceState)&&c.getItem(b)==="true",O=((vc=or.persist)==null?void 0:vc.voiceState)&&c.getItem(y)==="true";if(k&&setTimeout(()=>{tn.open(),setTimeout(()=>{var U;if(N||O)tn.startVoiceRecognition();else if((U=or.persist)!=null&&U.focusInput){let H=e.querySelector("textarea");H&&H.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(b,U.active?"true":"false")}),o.on("user:message",U=>{c.setItem(y,U.viaVoice?"true":"false")})),or.clearOnChatClear){let U=()=>{c.removeItem(g),c.removeItem(b),c.removeItem(y)},H=()=>U();window.addEventListener("persona:clear-chat",H),ft.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return u&&_()&&setTimeout(()=>{tn.open()},0),Rr(),tn};var My=(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},Ju=(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"},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=""},Gu=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,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},ky=(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))},Ly=(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)},Xu=(e,n,t,r,s,o,a)=>{var x,v,T,A,W,P;let i=br(o),d=i.reveal==="push";ky(e,n,t,r,d),Ly(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=(v=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,p=(A=(T=o==null?void 0:o.launcher)==null?void 0:T.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(n),ul(r),Gu(r),gl(t),pi(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((P=(W=o==null?void 0:o.launcher)==null?void 0:W.zIndex)!=null?P:hn),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"),Gu(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(n),ul(r),gl(t),pi(s,r);let I=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=I,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 I=My(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",R=i.side==="right"?a?`translateX(-${I}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${I}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+I}px`,n.style.transition=w,n.style.transform=R,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="",ml(n),fl(r),gl(t),pi(s,r);let I=i.reveal==="emerge";I?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",R=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",r.style.position="relative",r.style.overflow=I||R?"hidden":"visible",r.style.transition=w,I&&(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")}},Py=(e,n)=>{let t=e.ownerDocument.createElement("div");return Ju(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Ju(t,r)},destroy(){t.remove()}}},Iy=(e,n)=>{var W,P,I,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=(P=(W=n==null?void 0:n.launcher)==null?void 0:W.enabled)==null||P?(L=(I=n==null?void 0:n.launcher)==null?void 0:I.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},x=()=>{m(),br(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Xu(a,i,d,l,u,n,p)}),f.observe(a))},v=()=>{Xu(a,i,d,l,u,n,p),x()},T=a.ownerDocument.defaultView,A=()=>{v()};return T==null||T.addEventListener("resize",A),br(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),v(),{mode:"docked",host:u,shell:a,syncWidgetState(w){let R=w.launcherEnabled?w.open:!0;p!==R&&(p=R,v())},updateConfig(w){var R,F;n=w,((F=(R=n==null?void 0:n.launcher)==null?void 0:R.enabled)!=null?F:!0)===!1&&(p=!0),v()},destroy(){T==null||T.removeEventListener("resize",A),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},ui=(e,n)=>an(n)?Iy(e,n):Py(e,n);var hl={},Wy=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},Ry=()=>{try{if(typeof hl!="undefined"&&hl.url)return new URL("../widget.css",hl.url).href}catch{}return null},Qu=(e,n)=>{let t=Ry(),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)}},Yu=e=>{var T;let n=Wy(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=ui(n,s),a,i=[],d=(A,W)=>{var w,R;let I=!((R=(w=W==null?void 0:W.launcher)==null?void 0:w.enabled)!=null?R:!0)||an(W),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),I&&(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),Qu(F,r)}else A.appendChild(L),Qu(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=pl(A,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(A=>A()),i=[],a.destroy()};p(),(T=e.onReady)==null||T.call(e);let m=A=>{f(),o.destroy(),o=ui(n,A),s=A,p()},x={update(A){var R,F,_,D,j,q;let W={...s,...A,launcher:{...(R=s==null?void 0:s.launcher)!=null?R:{},...(F=A==null?void 0:A.launcher)!=null?F:{},dock:{...(D=(_=s==null?void 0:s.launcher)==null?void 0:_.dock)!=null?D:{},...(q=(j=A==null?void 0:A.launcher)==null?void 0:j.dock)!=null?q:{}}}},P=an(s),I=an(W),L=to(s),w=to(W);if(P!==I||L!==w){m(W);return}s=W,o.updateConfig(s),a.update(A),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(x,{get(A,W,P){if(W==="host")return o.host;if(W in A)return Reflect.get(A,W,P);let I=a[W];return typeof I=="function"?I.bind(a):I}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var rm=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Hy=new Set(["button","a","input","select","textarea","details","summary"]),By=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),bl=/\b(product|card|item|listing|result)\b/i,xl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Dy=3e3,Ny=100;function om(e){let n=typeof e.className=="string"?e.className:"";if(bl.test(n)||e.id&&bl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&bl.test(r.value))return!0}return!1}function sm(e){var n;return xl.test(((n=e.textContent)!=null?n:"").trim())}function am(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 Oy(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Zu(e){let n=e.match(xl);return n?n[0]:null}function em(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 Fy(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 _y="commerce-card",$y="result-card";function tm(e){return!om(e)||!sm(e)||!am(e)&&!Oy(e)?0:5200}function nm(e){var r;return!om(e)||sm(e)||!am(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 im=[{id:_y,scoreElement(e){return tm(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||xl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(tm(e)===0)return null;let{title:t,href:r}=em(e),s=(u=(l=Zu(((d=e.textContent)!=null?d:"").trim()))!=null?l:Zu(n.text))!=null?u:"",o=Fy(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:$y,scoreElement(e){return nm(e)},formatSummary(e,n){if(nm(e)===0)return null;let{title:t,href:r}=em(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
109
+ `)}}];function jy(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Uy(e){var u,p,f,m,x,v,T,A,W,P,I,L,w;let n=(u=e.options)!=null?u:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(x=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",s=(T=(v=n.maxTextLength)!=null?v:e.maxTextLength)!=null?T:200,o=(W=(A=n.visibleOnly)!=null?A:e.visibleOnly)!=null?W:!0,a=(P=n.root)!=null?P:e.root,i=(I=n.mode)!=null?I:"structured",d=(L=n.maxCandidates)!=null?L:Math.max(500,t*10),l=(w=e.rules)!=null?w:im;return i==="simple"&&e.rules&&e.rules.length>0?(jy(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function yl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var qy=["data-testid","data-product","data-action","data-id","data-name","data-type"];function zy(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"||Hy.has(n)||t&&By.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function lm(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 Vy(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 cm(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${yl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of qy){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${yl(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=>yl(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 Ky(e){return e==="static"?Ny:Dy}function dm(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:cm(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:zy(e),attributes:Vy(e)}}function Jy(e,n,t,r){let s=Ky(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 Gy(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 Xy(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(rm.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!lm(l)){i=a.nextNode();continue}let p=dm(l,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(T=>T==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:x,formattingRule:v}=Jy(l,p,e.rules,t);s.push({el:l,domIndex:o,enriched:p,score:x,formattingRule:v}),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;Gy(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 Qy(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(rm.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!lm(d)){o=s.nextNode();continue}let u=dm(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 Yy(e={}){var r;let n=Uy(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?Qy(n,t):Xy(n,t):[]}var mi=100;function Zy(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:
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)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:
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,mi)}" (clickable)`);r.push(`Interactive elements:
114
114
  ${a.join(`
115
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(`
@@ -120,7 +120,7 @@ ${a.join(`
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
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) => {
123
+ `)}var pm={name:"@runtypelabs/persona",version:"3.24.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=pm.version;function Or(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function tx(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 um=`({ 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
- }`,pm=`function(ctx) {
136
+ }`,mm=`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
- }`,um=`(action: any, context: any) => {
149
+ }`,gm=`(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
- }`,mm=`function(action, context) {
166
+ }`,fm=`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
- }`,Zb=`(parsed: any) => {
183
+ }`,nx=`(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
- }`,ex=`function(parsed) {
189
+ }`,rx=`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 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(`
195
+ }`;function ox(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 gi(e){var n,t;return(t=(n=e.parserType)!=null?n:ox(e.streamParser))!=null?t:"plain"}function fi(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 hi(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 bi(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 yi(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 vl(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 hm(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}: {`),hm(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function lo(e,n,t,r){t&&(e.push(`${r}${n}: {`),hm(e,t,`${r} `),e.push(`${r}},`))}function sx(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:tx(t.hooks)}:void 0;return n==="esm"?ax(r,s):n==="script-installer"?cx(r,s):n==="script-advanced"?px(r,s):n==="react-component"?ix(r,s):n==="react-advanced"?lx(r,s):dx(r,s)}function ax(e,n){let t=n==null?void 0:n.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," ",t)),o.push(...bi(e," ")),o.push(...yi(e," ")),o.push(...vl(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 ix(e,n){let t=n==null?void 0:n.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," ",t)),o.push(...bi(e," ")),o.push(...yi(e," ")),o.push(...vl(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 lx(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&&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," ",t)),r.push(...bi(e," ")),r.push(...yi(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(${nx}),`)),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(` ${um}`),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(` ${um}`),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(` ${gm}`),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(` ${gm}`),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 bm(e){var s;let n=gi(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 cx(e,n){let t=bm(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@${os}/dist/install.global.js" data-config='${s}'></script>`}function dx(e,n){let t=n==null?void 0:n.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',",...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&&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," ",t)),o.push(...bi(e," ")),o.push(...yi(e," ")),o.push(...vl(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 px(e,n){let t=n==null?void 0:n.hooks,r=bm(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@${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=`
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 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(${rx});`),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(` ${mm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${mm}`),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(` ${fm}`),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(` ${fm}`),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 ym={desktop:{w:1280,h:800},mobile:{w:390,h:844}},xm=.1,vm=.15,wm=1.5,wl=24,Cm=40,ux=`
203
203
  /* \u2500\u2500 Root \u2500\u2500 */
204
204
  .persona-dc-root {
205
205
  display: flex;
@@ -440,5 +440,5 @@ ${a.join(`
440
440
  min-height: 300px;
441
441
  }
442
442
  }
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};
443
+ `;function mx(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=ux,document.head.appendChild(e)}function gx(e,n){let t=e.clientWidth-wl*2-Cm,r=e.clientHeight-wl*2-Cm;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function fx(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 hx(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");mx();let u=Math.max(0,Math.min(r,t.length-1)),p=s,f=o,m=null,x=1,v=!1,T=h("div","persona-dc-root"),A=h("div","persona-dc-toolbar"),W=h("div","persona-dc-toolbar-lead"),P=h("div","persona-dc-toolbar-trail"),I=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 R=h("span","persona-dc-title-text"),F=h("span","persona-dc-title-chevron"),_=ye("chevron-down",12,"currentColor",2);_&&F.appendChild(_),w.append(R,F);let D=h("div","persona-dc-dropdown");D.setAttribute("role","listbox"),D.style.display="none";let j=!1;function q(){D.innerHTML="";for(let ge=0;ge<t.length;ge++){let ie=t[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)}),D.appendChild(ae)}}function re(){j=!j,D.style.display=j?"":"none",w.setAttribute("aria-expanded",j?"true":"false"),j&&q()}function Ie(){j&&(j=!1,D.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,D);let Ne=jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ue(1)}),ce=h("span","persona-dc-counter");W.append(I,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:x;m=Math.max(vm,Ce-xm),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:x;m=Math.min(wm,Ce+xm),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(t[u].url,"_blank")}});P.appendChild(ne),A.append(W,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=t[u].title,V.appendChild(pe),ke.appendChild(V),T.append(A,ke),e.appendChild(T);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=t[u];R.textContent=ge.title,ce.textContent=`${u+1} / ${t.length}`,pe.title=ge.title}function ue(ge){let ie=((u+ge)%t.length+t.length)%t.length;Ge(ie)}function Ge(ge){ge<0||ge>=t.length||(u=ge,pe.src=t[u].url,me(),l==null||l(u,t[u]))}function z(){var ae;if(v)return;let ge=(ae=ym[p])!=null?ae:ym.desktop;x=gx(ke,ge);let ie=Math.max(vm,Math.min(wm,m!=null?m:x));fx(V,pe,ge,ie,p),Me&&(Me.textContent=`${Math.round(ie*100)}%`)}let te=new ResizeObserver(()=>z());te.observe(ke),me(),pe.src=t[u].url,requestAnimationFrame(()=>z());function We(){v||(v=!0,te.disconnect(),document.removeEventListener("click",Re),T.remove())}return{element:T,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 bx(){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 yx(){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 xx(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:Tr(e.colors.primary,.95),100:Tr(e.colors.primary,.9),200:Tr(e.colors.primary,.8),300:Tr(e.colors.primary,.7),400:Tr(e.colors.primary,.6),500:e.colors.primary,600:Tr(e.colors.primary,.8),700:Tr(e.colors.primary,.7),800:Tr(e.colors.primary,.6),900:Tr(e.colors.primary,.5),950:Tr(e.colors.primary,.45)}}),{...n,palette:t}}}}function vx(){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 wx(){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 Tr(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 Cx(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Ax={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"}}},Am={components:{panel:{borderRadius:"0",shadow:"none"}}},Sm={id:"shop",label:"Shopping Assistant",config:{theme:Ax,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?"]}},Tm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Am}},Em={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Am}},Mm={shop:Sm,minimal:Tm,fullscreen:Em};function Sx(e){return Mm[e]}var YA=Yu;export{hu as ASK_USER_QUESTION_TOOL_NAME,qo as AgentWidgetClient,Is as AgentWidgetSession,Ko as AttachmentManager,jp as DEFAULT_COMPONENTS,ki as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,_p as DEFAULT_PALETTE,$p as DEFAULT_SEMANTIC,Ot as DEFAULT_WIDGET_CONFIG,Mm as PRESETS,Em as PRESET_FULLSCREEN,Tm as PRESET_MINIMAL,Sm as PRESET_SHOP,vh as THEME_ZONES,os as VERSION,va as WEBMCP_TOOL_PREFIX,Es as WebMcpBridge,bx as accessibilityPlugin,yx as animationsPlugin,To as applyThemeVariables,Go as attachHeaderToContainer,xx as brandPlugin,zs as buildComposer,nu as buildDefaultHeader,no as buildHeader,qs as buildHeaderWithLayout,ru as buildMinimalHeader,Yy as collectEnrichedPageContext,io as componentRegistry,ci as createActionManager,pl as createAgentExperience,Rb as createAskUserQuestionBubble,Mi as createBestAvailableVoiceProvider,nb as createBubbleWithLayout,ll as createCSATFeedback,Oi as createComboButton,vy as createComponentMiddleware,ol as createComponentStreamParser,Ap as createDefaultSanitizer,hx as createDemoCarousel,Im as createDirectivePostprocessor,Eo as createDropdownMenu,Km as createFlexibleJsonStreamParser,jt as createIconButton,rg as createImagePart,Si as createJsonStreamParser,Ka as createLabelButton,rl as createLocalStorageAdapter,ya as createMarkdownProcessor,$o as createMarkdownProcessorFromConfig,uu as createMessageActions,cl as createNPSFeedback,Ci as createPlainTextParser,Cx 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,Ti as createXmlParser,YA as default,ns as defaultActionHandlers,li as defaultJsonActionParser,im as defaultParseRules,Ba as detectColorScheme,Wm as directivePostprocessor,Js as ensureAskUserQuestionSheet,jo as escapeHtml,il as extractComponentDirectiveFromMessage,og as fileToImagePart,Zy as formatEnrichedContext,zo as generateAssistantMessageId,sx as generateCodeSnippet,Ym as generateMessageId,cm as generateStableSelector,Ls as generateUserMessageId,Hs as getActiveTheme,Vp as getColorScheme,eg as getDisplayText,ou as getHeaderLayout,ng as getImageParts,Sx as getPreset,al as hasComponentDirective,tg as hasImages,Fi as headerLayouts,wx as highContrastPlugin,Yu as initAgentWidget,ro as isAskUserQuestionMessage,xy as isComponentDirectiveType,an as isDockedMountMode,Ra as isVoiceSupported,wa as isWebMcpToolName,Ph as listRegisteredStreamAnimations,vp as markdownPostprocessor,Li as mergeWithDefaults,Zm as normalizeContent,oo as parseAskUserQuestionPayload,ii as pluginRegistry,vx as reducedMotionPlugin,kh as registerStreamAnimationPlugin,ko as removeAskUserQuestionSheet,sl as renderComponentDirective,pu as renderLoadingIndicatorWithFallback,ye as renderLucideIcon,br as resolveDockConfig,Ts as resolveSanitizer,Pi as resolveTokens,Ep as stripWebMcpPrefix,Ii as themeToCssVariables,Lh as unregisterStreamAnimationPlugin,sg as validateImageFile,Up as validateTheme};
444
444
  //# sourceMappingURL=index.js.map