@runtypelabs/persona 3.11.0 → 3.13.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.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var Bp=Object.create;var bs=Object.defineProperty;var Dp=Object.getOwnPropertyDescriptor;var Np=Object.getOwnPropertyNames;var Fp=Object.getPrototypeOf,Op=Object.prototype.hasOwnProperty;var $p=(e,r)=>{for(var t in r)bs(e,t,{get:r[t],enumerable:!0})},_c=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Np(r))!Op.call(e,s)&&s!==t&&bs(e,s,{get:()=>r[s],enumerable:!(n=Dp(r,s))||n.enumerable});return e};var jc=(e,r,t)=>(t=e!=null?Bp(Fp(e)):{},_c(r||!e||!e.__esModule?bs(t,"default",{value:e,enumerable:!0}):t,e)),_p=e=>_c(bs({},"__esModule",{value:!0}),e);var _m={};$p(_m,{AgentWidgetClient:()=>zr,AgentWidgetSession:()=>lo,AttachmentManager:()=>Jr,DEFAULT_COMPONENTS:()=>ha,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Is,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Wn,DEFAULT_PALETTE:()=>ga,DEFAULT_SEMANTIC:()=>fa,DEFAULT_WIDGET_CONFIG:()=>Mt,PRESETS:()=>Ka,PRESET_FULLSCREEN:()=>Xa,PRESET_MINIMAL:()=>Ga,PRESET_SHOP:()=>Ya,THEME_ZONES:()=>hd,VERSION:()=>Kr,accessibilityPlugin:()=>Ep,animationsPlugin:()=>Tp,applyThemeVariables:()=>Er,attachHeaderToContainer:()=>Yr,brandPlugin:()=>Mp,buildComposer:()=>uo,buildDefaultHeader:()=>Ca,buildHeader:()=>ur,buildHeaderWithLayout:()=>po,buildMinimalHeader:()=>wa,collectEnrichedPageContext:()=>cp,componentRegistry:()=>mr,createActionManager:()=>es,createAgentExperience:()=>Ks,createBestAvailableVoiceProvider:()=>ks,createBubbleWithLayout:()=>kd,createCSATFeedback:()=>Ys,createComboButton:()=>Os,createComponentMiddleware:()=>Ud,createComponentStreamParser:()=>qs,createDefaultSanitizer:()=>ca,createDemoCarousel:()=>Ap,createDirectivePostprocessor:()=>Jc,createDropdownMenu:()=>kr,createFlexibleJsonStreamParser:()=>Qc,createIconButton:()=>Lt,createImagePart:()=>ad,createJsonStreamParser:()=>ws,createLabelButton:()=>Yo,createLocalStorageAdapter:()=>zs,createMarkdownProcessor:()=>Ho,createMarkdownProcessorFromConfig:()=>_r,createMessageActions:()=>Ea,createNPSFeedback:()=>Gs,createPlainTextParser:()=>vs,createPlugin:()=>Ip,createRegexJsonParser:()=>Cs,createStandardBubble:()=>mo,createTextPart:()=>No,createTheme:()=>co,createThemeObserver:()=>Hs,createToggleGroup:()=>Go,createTypingIndicator:()=>Gr,createVoiceProvider:()=>Vr,createWidgetHostLayout:()=>ts,createXmlParser:()=>Ss,default:()=>$m,defaultActionHandlers:()=>Xr,defaultJsonActionParser:()=>Qo,defaultParseRules:()=>qa,detectColorScheme:()=>jo,directivePostprocessor:()=>Yc,escapeHtml:()=>oo,extractComponentDirectiveFromMessage:()=>Js,fileToImagePart:()=>id,formatEnrichedContext:()=>dp,generateAssistantMessageId:()=>qr,generateCodeSnippet:()=>yp,generateMessageId:()=>td,generateStableSelector:()=>Ua,generateUserMessageId:()=>io,getActiveTheme:()=>zo,getColorScheme:()=>ba,getDisplayText:()=>rd,getHeaderLayout:()=>Sa,getImageParts:()=>sd,getPreset:()=>Wp,hasComponentDirective:()=>Vs,hasImages:()=>od,headerLayouts:()=>$s,highContrastPlugin:()=>Lp,initAgentWidget:()=>$a,isComponentDirectiveType:()=>qd,isDockedMountMode:()=>Gt,isVoiceSupported:()=>Oo,markdownPostprocessor:()=>la,mergeWithDefaults:()=>Ps,normalizeContent:()=>nd,pluginRegistry:()=>Zo,reducedMotionPlugin:()=>kp,renderComponentDirective:()=>Us,renderLoadingIndicatorWithFallback:()=>Aa,resolveDockConfig:()=>On,resolveSanitizer:()=>so,resolveTokens:()=>Ws,themeToCssVariables:()=>Rs,validateImageFile:()=>ld,validateTheme:()=>ya});module.exports=_p(_m);var qc=require("marked"),jp=e=>{if(e)return e},Ho=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new qc.Marked({gfm:(s=r==null?void 0:r.gfm)!=null?s:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=jp(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},_r=e=>e?Ho({markedOptions:e.options,renderer:e.renderer}):Ho(),zp=Ho(),la=e=>zp(e),oo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Uc=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),zc=e=>`%%FORM_PLACEHOLDER_${e}%%`,Vc=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=zc(r.length);return r.push({token:a,type:String(o.type)}),a}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,s)=>{let o=zc(r.length);return r.push({token:o,type:s}),o}),t},Jc=e=>{let r=_r(e);return t=>{let n=[],s=Vc(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Uc(i)}"></div>`;o=o.replace(u,d)}),o}},Yc=e=>{let r=[],t=Vc(e,r),n=la(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Uc(o)}"></div>`;n=n.replace(a,u)}),n};var Gc=jc(require("dompurify"),1),qp={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"]},Up=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ca=()=>{let e=(0,Gc.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!Up.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,qp)},so=e=>e===!1?null:typeof e=="function"?e:ca();var dr=require("partial-json"),xs=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ao=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)}},Vp=e=>{var a,i;let r=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:r,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Xc=e=>e.status==="complete"?Vp(e):e.status==="pending"?"Waiting":"",Jp=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 Kc=e=>e.status==="complete"?Jp(e):"Using tool...",da=e=>{let r=e/1e3;return r<.1?"<0.1s":r>=10?`${Math.round(r)}s`:`${r.toFixed(1).replace(/\.0$/,"")}s`},Do=e=>{var t,n,s;let r=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(n=e.startedAt)!=null?n:e.completedAt)!=null?s:Date.now()));return da(r)},pa=(e,r,t)=>{var o;if(!r)return t;let n=((o=e.name)==null?void 0:o.trim())||"tool",s=Do(e);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,s)},Zc=(e,r)=>{let t=e.replace(/\{toolName\}/g,r),n=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Bo(n,t.slice(o,a.index),[]),a[1]!==void 0?Bo(n,a[1],["bold"]):a[2]!==void 0?Bo(n,a[2],["italic"]):a[3]!==void 0&&Bo(n,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Bo(n,t.slice(o),[]),n},Bo=(e,r,t)=>{let n=r.split("{duration}");for(let s=0;s<n.length;s++)n[s]&&e.push({text:n[s],styles:t}),s<n.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},Yp=()=>{let e=null,r=0,t=n=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
1
+ "use strict";var Dp=Object.create;var bs=Object.defineProperty;var Fp=Object.getOwnPropertyDescriptor;var Np=Object.getOwnPropertyNames;var Op=Object.getPrototypeOf,$p=Object.prototype.hasOwnProperty;var _p=(e,r)=>{for(var t in r)bs(e,t,{get:r[t],enumerable:!0})},zc=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Np(r))!$p.call(e,s)&&s!==t&&bs(e,s,{get:()=>r[s],enumerable:!(n=Fp(r,s))||n.enumerable});return e};var qc=(e,r,t)=>(t=e!=null?Dp(Op(e)):{},zc(r||!e||!e.__esModule?bs(t,"default",{value:e,enumerable:!0}):t,e)),jp=e=>zc(bs({},"__esModule",{value:!0}),e);var jm={};_p(jm,{AgentWidgetClient:()=>zr,AgentWidgetSession:()=>lo,AttachmentManager:()=>Jr,DEFAULT_COMPONENTS:()=>ba,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Rs,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Wn,DEFAULT_PALETTE:()=>ha,DEFAULT_SEMANTIC:()=>ya,DEFAULT_WIDGET_CONFIG:()=>Mt,PRESETS:()=>Qa,PRESET_FULLSCREEN:()=>Za,PRESET_MINIMAL:()=>Xa,PRESET_SHOP:()=>Ka,THEME_ZONES:()=>yd,VERSION:()=>Xr,accessibilityPlugin:()=>Tp,animationsPlugin:()=>Mp,applyThemeVariables:()=>Er,attachHeaderToContainer:()=>Yr,brandPlugin:()=>kp,buildComposer:()=>uo,buildDefaultHeader:()=>Sa,buildHeader:()=>ur,buildHeaderWithLayout:()=>po,buildMinimalHeader:()=>Aa,collectEnrichedPageContext:()=>dp,componentRegistry:()=>mr,createActionManager:()=>es,createAgentExperience:()=>ea,createBestAvailableVoiceProvider:()=>Ps,createBubbleWithLayout:()=>Ld,createCSATFeedback:()=>Xs,createComboButton:()=>js,createComponentMiddleware:()=>Vd,createComponentStreamParser:()=>Js,createDefaultSanitizer:()=>ua,createDemoCarousel:()=>Ep,createDirectivePostprocessor:()=>Gc,createDropdownMenu:()=>kr,createFlexibleJsonStreamParser:()=>ed,createIconButton:()=>Lt,createImagePart:()=>id,createJsonStreamParser:()=>Es,createLabelButton:()=>Yo,createLocalStorageAdapter:()=>Vs,createMarkdownProcessor:()=>Ho,createMarkdownProcessorFromConfig:()=>_r,createMessageActions:()=>Ma,createNPSFeedback:()=>Zs,createPlainTextParser:()=>Ss,createPlugin:()=>Pp,createRegexJsonParser:()=>As,createStandardBubble:()=>mo,createTextPart:()=>Fo,createTheme:()=>co,createThemeObserver:()=>Fs,createToggleGroup:()=>Go,createTypingIndicator:()=>Gr,createVoiceProvider:()=>Vr,createWidgetHostLayout:()=>ts,createXmlParser:()=>Ts,default:()=>_m,defaultActionHandlers:()=>Kr,defaultJsonActionParser:()=>Qo,defaultParseRules:()=>Va,detectColorScheme:()=>jo,directivePostprocessor:()=>Kc,escapeHtml:()=>oo,extractComponentDirectiveFromMessage:()=>Ks,fileToImagePart:()=>ld,formatEnrichedContext:()=>pp,generateAssistantMessageId:()=>qr,generateCodeSnippet:()=>bp,generateMessageId:()=>nd,generateStableSelector:()=>Ja,generateUserMessageId:()=>io,getActiveTheme:()=>zo,getColorScheme:()=>va,getDisplayText:()=>od,getHeaderLayout:()=>Ea,getImageParts:()=>ad,getPreset:()=>Rp,hasComponentDirective:()=>Gs,hasImages:()=>sd,headerLayouts:()=>zs,highContrastPlugin:()=>Ip,initAgentWidget:()=>ja,isComponentDirectiveType:()=>Ud,isDockedMountMode:()=>Gt,isVoiceSupported:()=>Oo,markdownPostprocessor:()=>pa,mergeWithDefaults:()=>Hs,normalizeContent:()=>rd,pluginRegistry:()=>Zo,reducedMotionPlugin:()=>Lp,renderComponentDirective:()=>Ys,renderLoadingIndicatorWithFallback:()=>Ta,resolveDockConfig:()=>On,resolveSanitizer:()=>so,resolveTokens:()=>Bs,themeToCssVariables:()=>Ds,validateImageFile:()=>cd,validateTheme:()=>xa});module.exports=jp(jm);var Vc=require("marked"),zp=e=>{if(e)return e},Ho=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new Vc.Marked({gfm:(s=r==null?void 0:r.gfm)!=null?s:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=zp(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},_r=e=>e?Ho({markedOptions:e.options,renderer:e.renderer}):Ho(),qp=Ho(),pa=e=>qp(e),oo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Jc=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Uc=e=>`%%FORM_PLACEHOLDER_${e}%%`,Yc=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Uc(r.length);return r.push({token:a,type:String(o.type)}),a}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,s)=>{let o=Uc(r.length);return r.push({token:o,type:s}),o}),t},Gc=e=>{let r=_r(e);return t=>{let n=[],s=Yc(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Jc(i)}"></div>`;o=o.replace(u,p)}),o}},Kc=e=>{let r=[],t=Yc(e,r),n=pa(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Jc(o)}"></div>`;n=n.replace(a,u)}),n};var Xc=qc(require("dompurify"),1),Up={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"]},Vp=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ua=()=>{let e=(0,Xc.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!Vp.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Up)},so=e=>e===!1?null:typeof e=="function"?e:ua();var dr=require("partial-json"),xs=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ao=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)}},Jp=e=>{var a,i;let r=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:r,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Zc=e=>e.status==="complete"?Jp(e):e.status==="pending"?"Waiting":"",Yp=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 Qc=e=>e.status==="complete"?Yp(e):"Using tool...",vs=e=>{let r=e/1e3;return r<.1?"<0.1s":r>=10?`${Math.round(r)}s`:`${r.toFixed(1).replace(/\.0$/,"")}s`},Do=e=>{var t,n,s;let r=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(n=e.startedAt)!=null?n:e.completedAt)!=null?s:Date.now()));return vs(r)},Cs=e=>{var t,n,s;let r=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(n=e.startedAt)!=null?n:e.completedAt)!=null?s:Date.now()));return vs(r)},ma=(e,r,t)=>{var o;if(!r)return t;let n=((o=e.name)==null?void 0:o.trim())||"tool",s=Do(e);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,s)},ws=(e,r)=>{let t=e.replace(/\{toolName\}/g,r),n=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Bo(n,t.slice(o,a.index),[]),a[1]!==void 0?Bo(n,a[1],["bold"]):a[2]!==void 0?Bo(n,a[2],["italic"]):a[3]!==void 0&&Bo(n,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Bo(n,t.slice(o),[]),n},Bo=(e,r,t)=>{let n=r.split("{duration}");for(let s=0;s<n.length;s++)n[s]&&e.push({text:n[s],styles:t}),s<n.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},Gp=()=>{let e=null,r=0,t=n=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},jr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},vs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Cs=()=>{var r;let e=Yp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},ws=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,dr.parse)(t,dr.STR|dr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?xs(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=xs(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Qc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?xs(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xs(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:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,dr.parse)(o,dr.STR|dr.OBJ),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Ss=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var Gp="https://api.runtype.com/v1/dispatch",ua="https://api.runtype.com",ma=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 Xp(e){switch(e){case"json":return ws;case"regex-json":return Cs;case"xml":return Ss;default:return vs}}var ed=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Kp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=ed(t);if(!ed(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=jr(e);return jr(r)!==null&&a===null?r:e}var zr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:Gp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Xp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ua;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,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 n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ua}/v1/client/feedback`}async sendFeedback(r){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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(r.messages),d=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,p={sessionId:u.sessionId,messages:r.messages.filter(ma).map(g=>{var v,T,C;return{id:g.id,role:g.role,content:(C=(T=(v=g.contentParts)!=null?v:g.llmContent)!=null?T:g.rawContent)!=null?C:g.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};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:n.signal});if(!f.ok){let g=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 T=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:T}),T}if(f.status===429){let T=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:T}),T}let v=new Error(g.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ua}/v1/agents/${r.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:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(ma).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(ma).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=d=>{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(),...d!==void 0&&{partId:d}};return n.current=p,s(p),p},c=d=>n.current?n.current:u(d);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(i.partId)),i.partId!==void 0&&(a.current=i.partId);let d=c(i.partId);i.partId!==void 0&&!d.partId&&(d.partId=i.partId),d.content+=i.text,s(d)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.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(r,t,n){var J,ie,$e,Q,se,kt,ct,Bt,Xt,_e,de,Ne,It,Pt,st,at,tn,en,nn,z,We,ge,ht,Oe,ae,ve,Fe,wt,jt,dt,zt,yt,Ze,bt,He,qt,Gn,nr,_n,et,Ir,Xn,Pr,Rn,Zr,fr,rr,it,Sn,jn,cn,hr,An,Et,dn,Hn,yr,or,br,Kn,En,Zn,St,Nt,Ft,Tn,xr,zn,Mn,N,qn,Bn,vr,gn,fn,re,kn,sr,ns,xo,rs,Qr,Qe,vo,Dn,hn,os,ss,Co,ar,as,Wr,wo,ir,So,Cr,wr,is,ls,sa,Rr,Hr,Wt,eo,to,Ao,Qn,cs,Eo,To,Mo,pn,Ln,lr,qe,ko,Br,Un,ds,no;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,d=X=>{let je=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,Ve=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,Rt=X.tools?X.tools.map(xt=>({...xt,chunks:xt.chunks?[...xt.chunks]:void 0})):void 0;return{...X,reasoning:je,toolCall:Ve,tools:Rt}},p=X=>{t({type:"message",message:d(X)})},f=null,g={current:null},v={current:null},T=!1,C=new Map,S=new Map,M={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},k=X=>{var je,Ve,Rt,xt,rt;return w((rt=(xt=(Rt=(Ve=(je=X.stepId)!=null?je:X.step_id)!=null?Ve:X.step)!=null?Rt:X.parentId)!=null?xt:X.flowStepId)!=null?rt:X.flow_step_id)},P=X=>{var je,Ve,Rt,xt,rt,lt,b;return w((b=(lt=(rt=(xt=(Rt=(Ve=(je=X.callId)!=null?je:X.call_id)!=null?Ve:X.requestId)!=null?Rt:X.request_id)!=null?xt:X.toolCallId)!=null?rt:X.tool_call_id)!=null?lt:X.stepId)!=null?b:X.step_id)},E=n,V=!1,te=()=>{if(f)return f;let X;return!V&&E?(X=E,V=!0):E&&v.current?X=`${E}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(f),f},Z=(X,je)=>{M.lastId=je,X&&M.byStep.set(X,je)},O=(X,je)=>{var rt;let Ve=(rt=X.reasoningId)!=null?rt:X.id,Rt=k(X);if(Ve){let lt=String(Ve);return Z(Rt,lt),lt}if(Rt){let lt=M.byStep.get(Rt);if(lt)return M.lastId=lt,lt}if(M.lastId&&!je)return M.lastId;if(!je)return null;let xt=`reason-${c()}`;return Z(Rt,xt),xt},ee=X=>{let je=C.get(X);if(je)return je;let Ve={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return C.set(X,Ve),p(Ve),Ve},xe=(X,je)=>{R.lastId=je,X&&R.byCall.set(X,je)},ne=new Set,we=new Map,De=new Set,me=new Map,ke=X=>{if(!X)return!1;let je=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return je==="emit_artifact_markdown"||je==="emit_artifact_component"},Le=(X,je)=>{var rt;let Ve=(rt=X.toolId)!=null?rt:X.id,Rt=P(X);if(Ve){let lt=String(Ve);return xe(Rt,lt),lt}if(Rt){let lt=R.byCall.get(Rt);if(lt)return R.lastId=lt,lt}if(R.lastId&&!je)return R.lastId;if(!je)return null;let xt=`tool-${c()}`;return xe(Rt,xt),xt},le=X=>{let je=S.get(X);if(je)return je;let Ve={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return S.set(X,Ve),p(Ve),Ve},K=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let je=Number(X);if(!Number.isNaN(je)&&Number.isFinite(je))return je;let Ve=Date.parse(X);if(!Number.isNaN(Ve))return Ve}return Date.now()},pe=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},G=new Map,oe=new Map,ye=new Map,Ie=new Map;function Xe(X,je,Ve,Rt){let xt=X.get(je);xt||(xt=[],X.set(je,xt));let rt=0,lt=xt.length;for(;rt<lt;){let Te=rt+lt>>>1;xt[Te].seq<Ve?rt=Te+1:lt=Te}xt.splice(rt,0,{seq:Ve,text:Rt});let b="";for(let Te=0;Te<xt.length;Te++)b+=xt[Te].text;return b}let ft=null,q=(X,je)=>{let Ve=pe(je),Rt=oe.get(X.id),xt=Kp(Rt,Ve);X.rawContent=xt;let rt=G.get(X.id),lt=$=>{var ue;let B=(ue=X.content)!=null?ue:"";$.trim()!==""&&(B.trim().length===0||$.startsWith(B)||$.trimStart().startsWith(B.trim()))&&(X.content=$)},b=()=>{var $;if(rt){let B=($=rt.close)==null?void 0:$.call(rt);B instanceof Promise&&B.catch(()=>{})}G.delete(X.id),oe.delete(X.id),X.streaming=!1,p(X)};if(!rt){lt(Ve),b();return}let Te=jr(xt);if(Te!==null&&Te.trim()!==""){lt(Te),b();return}let I=$=>{var Ue;let B=typeof $=="string"?$:(Ue=$==null?void 0:$.text)!=null?Ue:null;if(B!==null&&B.trim()!=="")return B;let ue=rt.getExtractedText();return ue!==null&&ue.trim()!==""?ue:Ve},x;try{x=rt.processChunk(xt)}catch{lt(Ve),b();return}if(x instanceof Promise){x.then($=>{lt(I($)),b()}).catch(()=>{lt(Ve),b()});return}lt(I(x)),b()},D=null,ce=new Map,j=(J=this.config.iterationDisplay)!=null?J:"separate";for(;;){let{done:X,value:je}=await s.read();if(X)break;a+=o.decode(je,{stream:!0});let Ve=a.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},jr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},Ss=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},As=()=>{var r;let e=Gp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},Es=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,dr.parse)(t,dr.STR|dr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?xs(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=xs(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},ed=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?xs(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xs(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:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,dr.parse)(o,dr.STR|dr.OBJ),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Ts=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var Kp="https://api.runtype.com/v1/dispatch",ga="https://api.runtype.com",fa=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 Xp(e){switch(e){case"json":return Es;case"regex-json":return As;case"xml":return Ts;default:return Ss}}var td=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Zp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=td(t);if(!td(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=jr(e);return jr(r)!==null&&a===null?r:e}var zr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:Kp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Xp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ga;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,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 n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ga}/v1/client/feedback`}async sendFeedback(r){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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:u.sessionId,messages:r.messages.filter(fa).map(g=>{var v,T,C;return{id:g.id,role:g.role,content:(C=(T=(v=g.contentParts)!=null?v:g.llmContent)!=null?T:g.rawContent)!=null?C:g.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let g=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 T=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:T}),T}if(f.status===429){let T=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:T}),T}let v=new Error(g.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.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:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.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,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ga}/v1/agents/${r.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:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(fa).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(fa).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=p=>{let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=d,s(d),d},c=p=>n.current?n.current:u(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.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(r,t,n){var U,ce,_e,ee,ie,kt,dt,Bt,Kt,je,ue,Ne,It,Pt,at,it,tn,en,nn,q,He,he,ht,$e,le,we,Oe,wt,jt,pt,zt,yt,Qe,bt,De,qt,Gn,nr,_n,tt,Ir,Kn,Pr,Rn,Zr,fr,rr,lt,Sn,jn,cn,hr,An,Et,dn,Hn,yr,or,br,Xn,En,Zn,St,Ft,Nt,Tn,xr,zn,Mn,F,qn,Bn,vr,gn,fn,ae,kn,sr,ns,xo,rs,Qr,et,vo,Dn,hn,os,ss,Co,ar,as,Wr,wo,ir,So,Cr,wr,is,ls,la,Rr,Hr,Wt,eo,to,Ao,Qn,cs,Eo,To,Mo,pn,Ln,lr,Ue,ko,Br,Un,ds,no;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,p=Z=>{let ze=Z.reasoning?{...Z.reasoning,chunks:[...Z.reasoning.chunks]}:void 0,Je=Z.toolCall?{...Z.toolCall,chunks:Z.toolCall.chunks?[...Z.toolCall.chunks]:void 0}:void 0,Rt=Z.tools?Z.tools.map(xt=>({...xt,chunks:xt.chunks?[...xt.chunks]:void 0})):void 0;return{...Z,reasoning:ze,toolCall:Je,tools:Rt}},d=Z=>{t({type:"message",message:p(Z)})},f=null,g={current:null},v={current:null},T=!1,C=new Map,S=new Map,M={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=Z=>{if(Z==null)return null;try{return String(Z)}catch{return null}},k=Z=>{var ze,Je,Rt,xt,ot;return w((ot=(xt=(Rt=(Je=(ze=Z.stepId)!=null?ze:Z.step_id)!=null?Je:Z.step)!=null?Rt:Z.parentId)!=null?xt:Z.flowStepId)!=null?ot:Z.flow_step_id)},P=Z=>{var ze,Je,Rt,xt,ot,ct,b;return w((b=(ct=(ot=(xt=(Rt=(Je=(ze=Z.callId)!=null?ze:Z.call_id)!=null?Je:Z.requestId)!=null?Rt:Z.request_id)!=null?xt:Z.toolCallId)!=null?ot:Z.tool_call_id)!=null?ct:Z.stepId)!=null?b:Z.step_id)},E=n,G=!1,Q=()=>{if(f)return f;let Z;return!G&&E?(Z=E,G=!0):E&&v.current?Z=`${E}_${v.current}`:Z=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:Z,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},K=(Z,ze)=>{M.lastId=ze,Z&&M.byStep.set(Z,ze)},O=(Z,ze)=>{var ot;let Je=(ot=Z.reasoningId)!=null?ot:Z.id,Rt=k(Z);if(Je){let ct=String(Je);return K(Rt,ct),ct}if(Rt){let ct=M.byStep.get(Rt);if(ct)return M.lastId=ct,ct}if(M.lastId&&!ze)return M.lastId;if(!ze)return null;let xt=`reason-${c()}`;return K(Rt,xt),xt},ne=Z=>{let ze=C.get(Z);if(ze)return ze;let Je={id:`reason-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Z,status:"streaming",chunks:[]}};return C.set(Z,Je),d(Je),Je},Ce=(Z,ze)=>{H.lastId=ze,Z&&H.byCall.set(Z,ze)},re=new Set,xe=new Map,We=new Set,me=new Map,Me=Z=>{if(!Z)return!1;let ze=Z.replace(/_+/g,"_").replace(/^_|_$/g,"");return ze==="emit_artifact_markdown"||ze==="emit_artifact_component"},ke=(Z,ze)=>{var ot;let Je=(ot=Z.toolId)!=null?ot:Z.id,Rt=P(Z);if(Je){let ct=String(Je);return Ce(Rt,ct),ct}if(Rt){let ct=H.byCall.get(Rt);if(ct)return H.lastId=ct,ct}if(H.lastId&&!ze)return H.lastId;if(!ze)return null;let xt=`tool-${c()}`;return Ce(Rt,xt),xt},oe=Z=>{let ze=S.get(Z);if(ze)return ze;let Je={id:`tool-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Z,status:"pending"}};return S.set(Z,Je),d(Je),Je},X=Z=>{if(typeof Z=="number"&&Number.isFinite(Z))return Z;if(typeof Z=="string"){let ze=Number(Z);if(!Number.isNaN(ze)&&Number.isFinite(ze))return ze;let Je=Date.parse(Z);if(!Number.isNaN(Je))return Je}return Date.now()},pe=Z=>{if(typeof Z=="string")return Z;if(Z==null)return"";try{return JSON.stringify(Z)}catch{return String(Z)}},V=new Map,te=new Map,ge=new Map,de=new Map;function Re(Z,ze,Je,Rt){let xt=Z.get(ze);xt||(xt=[],Z.set(ze,xt));let ot=0,ct=xt.length;for(;ot<ct;){let Le=ot+ct>>>1;xt[Le].seq<Je?ot=Le+1:ct=Le}xt.splice(ot,0,{seq:Je,text:Rt});let b="";for(let Le=0;Le<xt.length;Le++)b+=xt[Le].text;return b}let Ze=null,z=(Z,ze)=>{let Je=pe(ze),Rt=te.get(Z.id),xt=Zp(Rt,Je);Z.rawContent=xt;let ot=V.get(Z.id),ct=_=>{var fe;let D=(fe=Z.content)!=null?fe:"";_.trim()!==""&&(D.trim().length===0||_.startsWith(D)||_.trimStart().startsWith(D.trim()))&&(Z.content=_)},b=()=>{var _;if(ot){let D=(_=ot.close)==null?void 0:_.call(ot);D instanceof Promise&&D.catch(()=>{})}V.delete(Z.id),te.delete(Z.id),Z.streaming=!1,d(Z)};if(!ot){ct(Je),b();return}let Le=jr(xt);if(Le!==null&&Le.trim()!==""){ct(Le),b();return}let I=_=>{var Ve;let D=typeof _=="string"?_:(Ve=_==null?void 0:_.text)!=null?Ve:null;if(D!==null&&D.trim()!=="")return D;let fe=ot.getExtractedText();return fe!==null&&fe.trim()!==""?fe:Je},x;try{x=ot.processChunk(xt)}catch{ct(Je),b();return}if(x instanceof Promise){x.then(_=>{ct(I(_)),b()}).catch(()=>{ct(Je),b()});return}ct(I(x)),b()},W=null,se=new Map,$=(U=this.config.iterationDisplay)!=null?U:"separate";for(;;){let{done:Z,value:ze}=await s.read();if(Z)break;a+=o.decode(ze,{stream:!0});let Je=a.split(`
5
5
 
6
- `);a=(ie=Ve.pop())!=null?ie:"";for(let Rt of Ve){let xt=Rt.split(`
7
- `),rt="message",lt="";for(let I of xt)I.startsWith("event:")?rt=I.replace("event:","").trim():I.startsWith("data:")&&(lt+=I.replace("data:","").trim());if(!lt)continue;let b;try{b=JSON.parse(lt)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let Te=rt!=="message"?rt:($e=b.type)!=null?$e:"message";if((Q=this.onSSEEvent)==null||Q.call(this,Te,b),this.parseSSEEvent){g.current=f;let I=await this.handleCustomSSEEvent(b,t,g,p,c,v);if(g.current&&g.current!==f&&(f=g.current),I)continue}if(Te==="reason_start"){let I=(se=O(b,!0))!=null?se:`reason-${c()}`,x=ee(I);x.reasoning=(kt=x.reasoning)!=null?kt:{id:I,status:"streaming",chunks:[]},x.reasoning.startedAt=(Bt=x.reasoning.startedAt)!=null?Bt:K((ct=b.startedAt)!=null?ct:b.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",p(x)}else if(Te==="reason_delta"||Te==="reason_chunk"){let I=(_e=(Xt=O(b,!1))!=null?Xt:O(b,!0))!=null?_e:`reason-${c()}`,x=ee(I);x.reasoning=(de=x.reasoning)!=null?de:{id:I,status:"streaming",chunks:[]},x.reasoning.startedAt=(It=x.reasoning.startedAt)!=null?It:K((Ne=b.startedAt)!=null?Ne:b.timestamp);let $=(at=(st=(Pt=b.reasoningText)!=null?Pt:b.text)!=null?st:b.delta)!=null?at:"";if($&&b.hidden!==!0){let B=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(B!==void 0){let ue=Xe(Ie,I,B,String($));x.reasoning.chunks=[ue]}else x.reasoning.chunks.push(String($))}if(x.reasoning.status=b.done?"complete":"streaming",b.done){x.reasoning.completedAt=K((tn=b.completedAt)!=null?tn:b.timestamp);let B=(en=x.reasoning.startedAt)!=null?en:Date.now();x.reasoning.durationMs=Math.max(0,((nn=x.reasoning.completedAt)!=null?nn:Date.now())-B),Ie.delete(I)}x.streaming=x.reasoning.status!=="complete",p(x)}else if(Te==="reason_complete"){let I=(We=(z=O(b,!1))!=null?z:O(b,!0))!=null?We:`reason-${c()}`,x=C.get(I);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=K((ge=b.completedAt)!=null?ge:b.timestamp);let B=(ht=x.reasoning.startedAt)!=null?ht:Date.now();x.reasoning.durationMs=Math.max(0,((Oe=x.reasoning.completedAt)!=null?Oe:Date.now())-B),x.streaming=!1,Ie.delete(I),p(x)}let $=k(b);$&&M.byStep.delete($)}else if(Te==="tool_start"){let I=(ae=Le(b,!0))!=null?ae:`tool-${c()}`,x=(ve=b.toolName)!=null?ve:b.name;if(ke(x)){ne.add(I);continue}let $=le(I),B=(Fe=$.toolCall)!=null?Fe:{id:I,status:"pending"};B.name=x!=null?x:B.name,B.status="running",b.args!==void 0?B.args=b.args:b.parameters!==void 0&&(B.args=b.parameters),B.startedAt=(jt=B.startedAt)!=null?jt:K((wt=b.startedAt)!=null?wt:b.timestamp),B.completedAt=void 0,B.durationMs=void 0,$.toolCall=B,$.streaming=!0;let ue=b.agentContext;(ue||b.executionId)&&($.agentMetadata={executionId:(dt=ue==null?void 0:ue.executionId)!=null?dt:b.executionId,iteration:(zt=ue==null?void 0:ue.iteration)!=null?zt:b.iteration}),p($)}else if(Te==="tool_chunk"||Te==="tool_delta"){let I=(Ze=(yt=Le(b,!1))!=null?yt:Le(b,!0))!=null?Ze:`tool-${c()}`;if(ne.has(I))continue;let x=le(I),$=(bt=x.toolCall)!=null?bt:{id:I,status:"running"};$.startedAt=(qt=$.startedAt)!=null?qt:K((He=b.startedAt)!=null?He:b.timestamp);let B=(_n=(nr=(Gn=b.text)!=null?Gn:b.delta)!=null?nr:b.message)!=null?_n:"";B&&($.chunks=(et=$.chunks)!=null?et:[],$.chunks.push(String(B))),$.status="running",x.toolCall=$,x.streaming=!0;let ue=b.agentContext;(ue||b.executionId)&&(x.agentMetadata=(Pr=x.agentMetadata)!=null?Pr:{executionId:(Ir=ue==null?void 0:ue.executionId)!=null?Ir:b.executionId,iteration:(Xn=ue==null?void 0:ue.iteration)!=null?Xn:b.iteration}),p(x)}else if(Te==="tool_complete"){let I=(Zr=(Rn=Le(b,!1))!=null?Rn:Le(b,!0))!=null?Zr:`tool-${c()}`;if(ne.has(I)){ne.delete(I);continue}let x=le(I),$=(fr=x.toolCall)!=null?fr:{id:I,status:"running"};$.status="complete",b.result!==void 0&&($.result=b.result),typeof b.duration=="number"&&($.duration=b.duration),$.completedAt=K((rr=b.completedAt)!=null?rr:b.timestamp);let B=(it=b.duration)!=null?it:b.executionTime;if(typeof B=="number")$.durationMs=B;else{let tt=(Sn=$.startedAt)!=null?Sn:Date.now();$.durationMs=Math.max(0,((jn=$.completedAt)!=null?jn:Date.now())-tt)}x.toolCall=$,x.streaming=!1;let ue=b.agentContext;(ue||b.executionId)&&(x.agentMetadata=(An=x.agentMetadata)!=null?An:{executionId:(cn=ue==null?void 0:ue.executionId)!=null?cn:b.executionId,iteration:(hr=ue==null?void 0:ue.iteration)!=null?hr:b.iteration}),p(x);let Ue=P(b);Ue&&R.byCall.delete(Ue)}else if(Te==="text_start"){let I=b.partId;if(I!==void 0&&v.current!==null&&I!==v.current){let x=f;x&&(x.streaming=!1,p(x),ft=x,f=null,T=!0)}I!==void 0&&(v.current=I)}else if(Te==="text_end"){let I=f;I&&(I.streaming=!1,p(I),ft=I,f=null,T=!0)}else if(Te==="step_chunk"||Te==="step_delta"){let I=b.stepType,x=b.executionType;if(I==="tool"||x==="context")continue;let $=b.partId;if($!==void 0&&v.current!==null&&$!==v.current){let Ue=f;Ue&&(Ue.streaming=!1,p(Ue),ft=Ue,f=null,T=!0)}$!==void 0&&(v.current=$);let B=te();$!==void 0&&!B.partId&&(B.partId=$);let ue=(yr=(Hn=(dn=(Et=b.text)!=null?Et:b.delta)!=null?dn:b.content)!=null?Hn:b.chunk)!=null?yr:"";if(ue){let Ue=typeof b.seq=="number"?b.seq:void 0,tt;Ue!==void 0?tt=Xe(ye,B.id,Ue,ue):tt=((or=oe.get(B.id))!=null?or:"")+ue,B.rawContent=tt,G.has(B.id)||G.set(B.id,this.createStreamParser());let Ot=G.get(B.id),un=tt.trim().startsWith("{")||tt.trim().startsWith("[");if(un&&oe.set(B.id,tt),Ot.__isPlainTextParser===!0){Ue!==void 0?B.content=tt:B.content+=ue,oe.delete(B.id),G.delete(B.id),B.rawContent=void 0,p(B);continue}let $t=Ot.processChunk(tt);if($t instanceof Promise)$t.then(Ge=>{var Zt;let vt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;if(vt!==null&&vt.trim()!=="")B.content=vt,p(B);else if(!un&&!tt.trim().startsWith("<")){let rn=f;rn&&rn.id===B.id&&(Ue!==void 0?rn.content=tt:rn.content+=ue,oe.delete(rn.id),G.delete(rn.id),rn.rawContent=void 0,p(rn))}}).catch(()=>{Ue!==void 0?B.content=tt:B.content+=ue,oe.delete(B.id),G.delete(B.id),B.rawContent=void 0,p(B)});else{let Ge=typeof $t=="string"?$t:(br=$t==null?void 0:$t.text)!=null?br:null;Ge!==null&&Ge.trim()!==""?(B.content=Ge,p(B)):!un&&!tt.trim().startsWith("<")&&(Ue!==void 0?B.content=tt:B.content+=ue,oe.delete(B.id),G.delete(B.id),B.rawContent=void 0,p(B))}}if(b.isComplete){let Ue=(En=(Kn=b.result)==null?void 0:Kn.response)!=null?En:B.content;if(Ue){let tt=oe.get(B.id),Ot=tt!=null?tt:pe(Ue);B.rawContent=Ot;let un=G.get(B.id),Kt=null,$t=!1;if(un&&(Kt=un.getExtractedText(),Kt===null&&(Kt=jr(Ot)),Kt===null)){let Ge=un.processChunk(Ot);Ge instanceof Promise?($t=!0,Ge.then(vt=>{var rn;let Zt=typeof vt=="string"?vt:(rn=vt==null?void 0:vt.text)!=null?rn:null;if(Zt!==null){let Dt=f;Dt&&Dt.id===B.id&&(Dt.content=Zt,Dt.streaming=!1,G.delete(Dt.id),oe.delete(Dt.id),ye.delete(Dt.id),p(Dt))}})):Kt=typeof Ge=="string"?Ge:(Zn=Ge==null?void 0:Ge.text)!=null?Zn:null}if(!$t){Kt!==null&&Kt.trim()!==""?B.content=Kt:oe.has(B.id)||(B.content=pe(Ue));let Ge=G.get(B.id);if(Ge){let vt=(St=Ge.close)==null?void 0:St.call(Ge);vt instanceof Promise&&vt.catch(()=>{}),G.delete(B.id)}oe.delete(B.id),ye.delete(B.id),B.streaming=!1,p(B)}}}}else if(Te==="step_complete"){let I=b.stepType,x=b.executionType;if(I==="tool"||x==="context")continue;if(T){if(f!==null){let tt=f;G.delete(tt.id),oe.delete(tt.id),ye.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,p(tt))}let ue=(Nt=b.result)==null?void 0:Nt.response,Ue=ft;Ue&&(ue!=null?q(Ue,ue):(G.delete(Ue.id),oe.delete(Ue.id))),ft=null;continue}let $=(Ft=b.result)==null?void 0:Ft.response,B=te();if($!=null){let ue=G.get(B.id),Ue=!1,tt=!1;if(ue){let Ot=ue.getExtractedText(),un=oe.get(B.id),Kt=un!=null?un:pe($);if(B.rawContent=Kt,Ot!==null&&Ot.trim()!=="")B.content=Ot,Ue=!0;else{let $t=jr(Kt);if($t!==null)B.content=$t,Ue=!0;else{let Ge=ue.processChunk(Kt);if(Ge instanceof Promise)tt=!0,Ge.then(vt=>{var rn;let Zt=typeof vt=="string"?vt:(rn=vt==null?void 0:vt.text)!=null?rn:null;if(Zt!==null&&Zt.trim()!==""){let Dt=f;Dt&&Dt.id===B.id&&(Dt.content=Zt,Dt.streaming=!1,G.delete(Dt.id),oe.delete(Dt.id),ye.delete(Dt.id),p(Dt))}else{let Dt=ue.getExtractedText(),In=f;In&&In.id===B.id&&(Dt!==null&&Dt.trim()!==""?In.content=Dt:oe.has(In.id)||(In.content=pe($)),In.streaming=!1,G.delete(In.id),oe.delete(In.id),ye.delete(In.id),p(In))}});else{let vt=typeof Ge=="string"?Ge:(Tn=Ge==null?void 0:Ge.text)!=null?Tn:null;if(vt!==null&&vt.trim()!=="")B.content=vt,Ue=!0;else{let Zt=ue.getExtractedText();Zt!==null&&Zt.trim()!==""&&(B.content=Zt,Ue=!0)}}}}}if(!tt){if(!B.rawContent){let Ot=oe.get(B.id);B.rawContent=Ot!=null?Ot:pe($)}if(!Ue&&!oe.has(B.id)&&(B.content=pe($)),ue){let Ot=(xr=ue.close)==null?void 0:xr.call(ue);Ot instanceof Promise&&Ot.catch(()=>{})}G.delete(B.id),oe.delete(B.id),ye.delete(B.id),B.streaming=!1,p(B)}}else G.delete(B.id),oe.delete(B.id),ye.delete(B.id),B.streaming=!1,p(B)}else if(Te==="flow_complete"){let I=(zn=b.result)==null?void 0:zn.response;if(T){if(f!==null){let x=f;G.delete(x.id),oe.delete(x.id),ye.delete(x.id),x.streaming!==!1&&(x.streaming=!1,p(x))}}else if(I!=null){let x=te(),$=oe.get(x.id),B=$!=null?$:pe(I);x.rawContent=B;let ue=pe(I),Ue=G.get(x.id);if(Ue){let un=jr(B);if(un!==null)ue=un;else{let Kt=Ue.processChunk(B);Kt instanceof Promise&&Kt.then(Ge=>{var Zt;let vt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;vt!==null&&(x.content=vt,x.streaming=!1,p(x))});let $t=Ue.getExtractedText();$t!==null&&(ue=$t)}}G.delete(x.id),oe.delete(x.id),ye.delete(x.id);let tt=ue!==x.content,Ot=x.streaming!==!1;tt&&(x.content=ue),x.streaming=!1,(tt||Ot)&&p(x)}else if(f!==null){let x=f;G.delete(x.id),oe.delete(x.id),ye.delete(x.id),x.streaming!==!1&&(x.streaming=!1,p(x))}t({type:"status",status:"idle"})}else if(Te==="agent_start")D={executionId:b.executionId,agentId:(Mn=b.agentId)!=null?Mn:"virtual",agentName:(N=b.agentName)!=null?N:"",status:"running",currentIteration:0,maxTurns:(qn=b.maxTurns)!=null?qn:1,startedAt:K(b.startedAt)};else if(Te==="agent_iteration_start"){if(D&&(D.currentIteration=b.iteration),j==="separate"&&b.iteration>1){let I=f;I&&(I.streaming=!1,p(I),ce.set(b.iteration-1,I),f=null)}}else if(Te!=="agent_turn_start"){if(Te==="agent_turn_delta"){if(b.contentType==="text"){let I=te();I.content+=(Bn=b.delta)!=null?Bn:"",I.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:D==null?void 0:D.agentName},p(I)}else if(b.contentType==="thinking"){let I=(vr=b.turnId)!=null?vr:`agent-think-${b.iteration}`,x=ee(I);x.reasoning=(gn=x.reasoning)!=null?gn:{id:I,status:"streaming",chunks:[]},x.reasoning.chunks.push((fn=b.delta)!=null?fn:""),x.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(x)}else if(b.contentType==="tool_input"){let I=(re=b.toolCallId)!=null?re:R.lastId;if(I){let x=S.get(I);x!=null&&x.toolCall&&(x.toolCall.chunks=(kn=x.toolCall.chunks)!=null?kn:[],x.toolCall.chunks.push((sr=b.delta)!=null?sr:""),p(x))}}}else if(Te==="agent_turn_complete"){let I=b.turnId;if(I){let x=C.get(I);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=K(b.completedAt);let $=(ns=x.reasoning.startedAt)!=null?ns:Date.now();x.reasoning.durationMs=Math.max(0,((xo=x.reasoning.completedAt)!=null?xo:Date.now())-$),x.streaming=!1,p(x)}}}else if(Te==="agent_tool_start"){let I=(rs=b.toolCallId)!=null?rs:`agent-tool-${c()}`;xe(P(b),I);let x=le(I),$=(Qr=x.toolCall)!=null?Qr:{id:I,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};$.name=(vo=(Qe=b.toolName)!=null?Qe:b.name)!=null?vo:$.name,$.status="running",b.parameters!==void 0&&($.args=b.parameters),$.startedAt=K((Dn=b.startedAt)!=null?Dn:b.timestamp),x.toolCall=$,x.streaming=!0,x.agentMetadata={executionId:b.executionId,iteration:b.iteration},p(x)}else if(Te==="agent_tool_delta"){let I=(hn=b.toolCallId)!=null?hn:R.lastId;if(I){let x=(os=S.get(I))!=null?os:le(I);x.toolCall&&(x.toolCall.chunks=(ss=x.toolCall.chunks)!=null?ss:[],x.toolCall.chunks.push((Co=b.delta)!=null?Co:""),x.toolCall.status="running",x.streaming=!0,p(x))}}else if(Te==="agent_tool_complete"){let I=(ar=b.toolCallId)!=null?ar:R.lastId;if(I){let x=(as=S.get(I))!=null?as:le(I);if(x.toolCall){x.toolCall.status="complete",b.result!==void 0&&(x.toolCall.result=b.result),typeof b.executionTime=="number"&&(x.toolCall.durationMs=b.executionTime),x.toolCall.completedAt=K((Wr=b.completedAt)!=null?Wr:b.timestamp),x.streaming=!1,p(x);let $=P(b);$&&R.byCall.delete($)}}}else if(Te!=="agent_iteration_complete"){if(Te==="agent_reflection"||Te==="agent_reflect"){let I=`agent-reflection-${b.executionId}-${b.iteration}`,x={id:I,role:"assistant",content:(wo=b.reflection)!=null?wo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"complete",chunks:[(ir=b.reflection)!=null?ir:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};p(x)}else if(Te==="agent_complete"){D&&(D.status=b.success?"complete":"error",D.completedAt=K(b.completedAt),D.stopReason=b.stopReason);let I=f;I&&(I.streaming=!1,p(I)),t({type:"status",status:"idle"})}else if(Te==="agent_error"){let I=typeof b.error=="string"?b.error:(Cr=(So=b.error)==null?void 0:So.message)!=null?Cr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",I):t({type:"error",error:new Error(I)})}else if(Te!=="agent_ping")if(Te==="agent_approval_start"){let I=(wr=b.approvalId)!=null?wr:`approval-${c()}`,x={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(is=D==null?void 0:D.agentId)!=null?is:"virtual",executionId:(sa=(ls=b.executionId)!=null?ls:D==null?void 0:D.executionId)!=null?sa:"",toolName:(Rr=b.toolName)!=null?Rr:"",toolType:b.toolType,description:(Wt=b.description)!=null?Wt:`Execute ${(Hr=b.toolName)!=null?Hr:"tool"}`,parameters:b.parameters}};p(x)}else if(Te==="step_await"&&b.awaitReason==="approval_required"){let I=(eo=b.approvalId)!=null?eo:`approval-${c()}`,x={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(to=D==null?void 0:D.agentId)!=null?to:"virtual",executionId:(Qn=(Ao=b.executionId)!=null?Ao:D==null?void 0:D.executionId)!=null?Qn:"",toolName:(cs=b.toolName)!=null?cs:"",toolType:b.toolType,description:(To=b.description)!=null?To:`Execute ${(Eo=b.toolName)!=null?Eo:"tool"}`,parameters:b.parameters}};p(x)}else if(Te==="agent_approval_complete"){let I=b.approvalId;if(I){let $={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:(Mo=b.decision)!=null?Mo:"approved",agentId:(pn=D==null?void 0:D.agentId)!=null?pn:"virtual",executionId:(lr=(Ln=b.executionId)!=null?Ln:D==null?void 0:D.executionId)!=null?lr:"",toolName:(qe=b.toolName)!=null?qe:"",description:(ko=b.description)!=null?ko:"",resolvedAt:Date.now()}};p($)}}else if(Te==="artifact_start"||Te==="artifact_delta"||Te==="artifact_update"||Te==="artifact_complete"){if(Te==="artifact_start"){let I=b.artifactType,x=String(b.id),$=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:x,artifactType:I,title:$,component:typeof b.component=="string"?b.component:void 0}),me.set(x,{markdown:"",title:$}),!De.has(x)){De.add(x);let B={id:`artifact-ref-${x}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:x,title:$,artifactType:I,status:"streaming"}})};we.set(x,B),p(B)}}else if(Te==="artifact_delta"){let I=String(b.id),x=typeof b.delta=="string"?b.delta:String((Br=b.delta)!=null?Br:"");t({type:"artifact_delta",id:I,artDelta:x});let $=me.get(I);$&&($.markdown+=x)}else if(Te==="artifact_update"){let I=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:I,component:typeof b.component=="string"?b.component:void 0})}else if(Te==="artifact_complete"){let I=String(b.id);t({type:"artifact_complete",id:I});let x=we.get(I);if(x){x.streaming=!1;try{let $=JSON.parse((Un=x.rawContent)!=null?Un:"{}");if($.props){$.props.status="complete";let B=me.get(I);B!=null&&B.markdown&&($.props.markdown=B.markdown)}x.rawContent=JSON.stringify($)}catch{}me.delete(I),p(x),we.delete(I)}}}else if(Te==="transcript_insert"){let I=b.message;if(!I||typeof I!="object")continue;let x=String((ds=I.id)!=null?ds:`msg-${c()}`),$=I.role,ue={id:x,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof I.content=="string"?I.content:"",rawContent:typeof I.rawContent=="string"?I.rawContent:void 0,createdAt:typeof I.createdAt=="string"?I.createdAt:new Date().toISOString(),streaming:I.streaming===!0,...typeof I.variant=="string"?{variant:I.variant}:{},sequence:c()};if(p(ue),ue.rawContent)try{let Ue=JSON.parse(ue.rawContent),tt=(no=Ue==null?void 0:Ue.props)==null?void 0:no.artifactId;typeof tt=="string"&&De.add(tt)}catch{}f=null,g.current=null,G.delete(x),oe.delete(x),ye.delete(x)}else Te==="error"&&b.error&&t({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function td(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function io(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function qr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var As="[Image]";function nd(e){return typeof e=="string"?[{type:"text",text:e}]:e}function rd(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function od(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function sd(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function No(e){return{type:"text",text:e}}function ad(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function id(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function ld(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.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: ${r.join(", ")}`}}var cd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Zp=["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"],pr=[...cd,...Zp];function Qp(e){return cd.includes(e)||e.startsWith("image/")}function Es(e){return Qp(e.type)}async function dd(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Es(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function pd(e,r=pr,t=10*1024*1024){return r.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: ${r.join(", ")}`}}function eu(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function ud(e,r){let t=eu(r).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 Ts=class{constructor(r=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=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.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 u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var Ms=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 d=0;d<a.length;d++)i+=a[d]*a[d];let u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=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 Fo=class{constructor(r){this.config=r;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 Ms;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;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=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let d=`${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,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let v=!1,T=S=>{v||(v=!0,clearTimeout(C),g(new Error(S)))},C=setTimeout(()=>T("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(C),f())},{once:!0}),this.ws.addEventListener("error",()=>{T("WebSocket connection failed to "+d+"."+p)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!v){let M=S.code!==1006?` (code ${S.code})`:"";T("WebSocket connection failed"+M+"."+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(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.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(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ts(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let d=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:d});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("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(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ur=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.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(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({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(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Vr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Fo(e.runtype);case"browser":if(!Ur.isSupported())throw new Error("Browser speech recognition not supported");return new Ur(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ks(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Vr({type:"runtype",runtype:e.runtype});if(Ur.isSupported())return Vr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Oo(e){try{return ks(e),!0}catch{return!1}}var lo=class e{constructor(r={},t){this.config=r;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new zr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Oo((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var d,p,f,g,v,T;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((d=c.transcript)!=null&&d.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let C=(T=this.pendingVoiceAssistantMessageId)!=null?T:(v=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:v.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var d,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(d=this.callbacks).onVoiceStatusChanged)==null||p.call(d,c)}),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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,d;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(d=r.browser)==null?void 0:d.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new zr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:d}=r,f={id:a!=null?a:t==="user"?io():t==="assistant"?qr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...d!==void 0&&{voiceProcessing:d}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:d,streaming:p=!1}=n,g={id:u!=null?u:s==="user"?io():s==="assistant"?qr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,d,p,f,g;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=io(),o=qr(),a={id:s,role:"user",content:n||As,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let T=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!T){let C={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(C)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,T||(v instanceof Error?(p=(d=this.callbacks).onError)==null||p.call(d,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=qr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let d={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(d),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,d;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let g=await p.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(d=(c=this.callbacks).onError)==null||d.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.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(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},er=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var tu=jc(require("lucide"),1),fe=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=tu[s];return o?nu(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function nu(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),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){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,d])=>{c!=="stroke"&&u.setAttribute(c,String(d))}),s.appendChild(u)}}}),s}var Ls={allowedTypes:pr,maxFileSize:10*1024*1024,maxFiles:4};function ru(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ou(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-json":"file"}var Jr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ls.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Ls.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Ls.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:Ls.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let d=pd(c,this.config.allowedTypes,this.config.maxFileSize);if(!d.valid){let p=(s=d.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await dd(c),f=Es(c)?URL.createObjectURL(c):null,g={id:ru(),file:c,previewUrl:f,contentPart:p};this.attachments.push(g),this.renderPreview(g)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=Es(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.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=ou(r.file.type),u=fe(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=ud(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var md=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function $o(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];md(o)&&md(s)?t[n]=$o(o,s):t[n]=s}return t}var Wn="min(440px, calc(100vw - 24px))",Is="440px",Mt={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:Wn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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}},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 gd(e,r){if(!(!e&&!r))return e?r?$o(e,r):e:r}function Ps(e){var r,t,n,s,o,a,i,u,c,d,p,f,g,v,T,C,S,M,R,w,k;return e?{...Mt,...e,theme:gd(Mt.theme,e.theme),darkTheme:gd(Mt.darkTheme,e.darkTheme),launcher:{...Mt.launcher,...e.launcher,dock:{...(r=Mt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Mt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Mt.copy,...e.copy},sendButton:{...Mt.sendButton,...e.sendButton},statusIndicator:{...Mt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Mt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ee,xe,ne,we;let P=(ee=Mt.features)==null?void 0:ee.artifacts,E=(xe=e.features)==null?void 0:xe.artifacts,V=(ne=Mt.features)==null?void 0:ne.scrollToBottom,te=(we=e.features)==null?void 0:we.scrollToBottom,Z=P===void 0&&E===void 0?void 0:{...P,...E,layout:{...P==null?void 0:P.layout,...E==null?void 0:E.layout}},O=V===void 0&&te===void 0?void 0:{...V,...te};return{...Mt.features,...e.features,...O!==void 0?{scrollToBottom:O}:{},...Z!==void 0?{artifacts:Z}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Mt.suggestionChips,suggestionChipsConfig:{...Mt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Mt.layout,...e.layout,header:{...(a=Mt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=Mt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(d=Mt.layout)==null?void 0:d.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(T=(v=Mt.layout)==null?void 0:v.messages)==null?void 0:T.timestamp,...(S=(C=e.layout)==null?void 0:C.messages)==null?void 0:S.timestamp}},slots:{...(M=Mt.layout)==null?void 0:M.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...Mt.markdown,...e.markdown,options:{...(w=Mt.markdown)==null?void 0:w.options,...(k=e.markdown)==null?void 0:k.options}},messageActions:{...Mt.messageActions,...e.messageActions}}:Mt}var ga={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"}},fa={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"}},ha={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:Wn,maxWidth:Is,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"},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 _o(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?_o(e,n):n}function Ws(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=_o(e,a);u!==void 0&&(r[i]={path:i,value:u,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"),r}function ya(e){let r=[],t=[];return e.palette||r.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:r.length===0,errors:r,warnings:t}}function fd(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=fd(o,s):t[n]=s}return t}function su(e,r){return r?fd(e,r):e}function co(e,r={}){var s,o,a,i,u,c,d,p,f,g,v,T,C;let t={palette:ga,semantic:fa,components:ha},n={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,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(d=e==null?void 0:e.semantic)==null?void 0:d.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(T=e==null?void 0:e.semantic)==null?void 0:T.spacing},typography:{...t.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:su(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let S=ya(n);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let S of r.plugins)n=S.transform(n);return n}function Rs(e){var v,T,C,S,M,R,w,k,P,E,V,te,Z,O,ee,xe,ne,we,De,me,ke,Le,le,K,pe,G,oe,ye,Ie,Xe,ft,q,D,ce,j,J,ie,$e,Q,se,kt,ct,Bt,Xt,_e,de,Ne,It,Pt,st,at,tn,en,nn,z,We,ge,ht,Oe,ae,ve,Fe,wt,jt,dt,zt,yt,Ze,bt,He,qt,Gn,nr,_n,et,Ir,Xn,Pr,Rn,Zr,fr,rr,it,Sn,jn,cn,hr,An,Et,dn,Hn,yr,or,br,Kn,En,Zn,St,Nt,Ft,Tn,xr,zn,Mn,N,qn,Bn,vr,gn,fn;let r=Ws(e),t={};for(let[re,kn]of Object.entries(r)){let sr=re.replace(/\./g,"-");t[`--persona-${sr}`]=kn.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"]=(C=t["--persona-semantic-colors-accent"])!=null?C:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(R=t["--persona-semantic-colors-container"])!=null?R:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(k=t["--persona-semantic-colors-text-muted"])!=null?k:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(V=t["--persona-semantic-colors-divider"])!=null?V:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(te=t["--persona-components-voice-recording-indicator"])!=null?te:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(Z=t["--persona-components-voice-recording-background"])!=null?Z:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ee=t["--persona-components-voice-speaking-icon"])!=null?ee:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(xe=t["--persona-components-approval-requested-background"])!=null?xe:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ne=t["--persona-components-approval-requested-border"])!=null?ne:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(we=t["--persona-components-approval-requested-text"])!=null?we:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(De=t["--persona-components-approval-approve-background"])!=null?De:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(me=t["--persona-components-approval-deny-background"])!=null?me:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ke=t["--persona-components-attachment-image-background"])!=null?ke: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"]=(le=t["--persona-semantic-typography-fontFamily"])!=null?le:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(K=t["--persona-semantic-typography-fontSize"])!=null?K:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(pe=t["--persona-semantic-typography-fontWeight"])!=null?pe:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(G=t["--persona-semantic-typography-lineHeight"])!=null?G: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"]=(oe=t["--persona-palette-radius-sm"])!=null?oe:"0.125rem",t["--persona-radius-md"]=(ye=t["--persona-palette-radius-md"])!=null?ye:"0.375rem",t["--persona-radius-lg"]=(Ie=t["--persona-palette-radius-lg"])!=null?Ie:"0.5rem",t["--persona-radius-xl"]=(Xe=t["--persona-palette-radius-xl"])!=null?Xe:"0.75rem",t["--persona-radius-full"]=(ft=t["--persona-palette-radius-full"])!=null?ft:"9999px",t["--persona-launcher-radius"]=(D=(q=t["--persona-components-launcher-borderRadius"])!=null?q:t["--persona-palette-radius-full"])!=null?D:"9999px",t["--persona-launcher-bg"]=(ce=t["--persona-components-launcher-background"])!=null?ce:t["--persona-primary"],t["--persona-launcher-fg"]=(j=t["--persona-components-launcher-foreground"])!=null?j:t["--persona-text-inverse"],t["--persona-launcher-border"]=(J=t["--persona-components-launcher-border"])!=null?J:t["--persona-border"],t["--persona-button-primary-bg"]=(ie=t["--persona-components-button-primary-background"])!=null?ie:t["--persona-primary"],t["--persona-button-primary-fg"]=($e=t["--persona-components-button-primary-foreground"])!=null?$e:t["--persona-text-inverse"],t["--persona-button-radius"]=(se=(Q=t["--persona-components-button-primary-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?se:"9999px",t["--persona-panel-radius"]=(ct=(kt=t["--persona-components-panel-borderRadius"])!=null?kt:t["--persona-radius-xl"])!=null?ct:"0.75rem",t["--persona-panel-border"]=(Bt=t["--persona-components-panel-border"])!=null?Bt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(_e=(Xt=t["--persona-components-panel-shadow"])!=null?Xt:t["--persona-palette-shadows-xl"])!=null?_e:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ne=(de=t["--persona-components-input-borderRadius"])!=null?de:t["--persona-radius-lg"])!=null?Ne:"0.5rem",t["--persona-message-user-radius"]=(Pt=(It=t["--persona-components-message-user-borderRadius"])!=null?It:t["--persona-radius-lg"])!=null?Pt:"0.5rem",t["--persona-message-assistant-radius"]=(at=(st=t["--persona-components-message-assistant-borderRadius"])!=null?st:t["--persona-radius-lg"])!=null?at:"0.5rem",t["--persona-header-bg"]=(tn=t["--persona-components-header-background"])!=null?tn:t["--persona-surface"],t["--persona-header-border"]=(en=t["--persona-components-header-border"])!=null?en:t["--persona-divider"],t["--persona-header-icon-bg"]=(nn=t["--persona-components-header-iconBackground"])!=null?nn:t["--persona-primary"],t["--persona-header-icon-fg"]=(z=t["--persona-components-header-iconForeground"])!=null?z:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(We=t["--persona-components-header-titleForeground"])!=null?We:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ge=t["--persona-components-header-subtitleForeground"])!=null?ge:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ht=t["--persona-components-header-actionIconForeground"])!=null?ht:t["--persona-muted"];let n=(Oe=e.components)==null?void 0:Oe.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(ae=t["--persona-components-input-background"])!=null?ae:t["--persona-surface"],t["--persona-input-placeholder"]=(ve=t["--persona-components-input-placeholder"])!=null?ve:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Fe=t["--persona-components-message-user-background"])!=null?Fe:t["--persona-accent"],t["--persona-message-user-text"]=(wt=t["--persona-components-message-user-text"])!=null?wt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(jt=t["--persona-components-message-user-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(dt=t["--persona-components-message-assistant-background"])!=null?dt:t["--persona-surface"],t["--persona-message-assistant-text"]=(zt=t["--persona-components-message-assistant-text"])!=null?zt: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"]=(Ze=t["--persona-components-message-assistant-shadow"])!=null?Ze:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(He=(bt=t["--persona-components-scrollToBottom-background"])!=null?bt:t["--persona-button-primary-bg"])!=null?He:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Gn=(qt=t["--persona-components-scrollToBottom-foreground"])!=null?qt:t["--persona-button-primary-fg"])!=null?Gn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(nr=t["--persona-components-scrollToBottom-border"])!=null?nr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(_n=t["--persona-components-scrollToBottom-size"])!=null?_n:"40px",t["--persona-scroll-to-bottom-radius"]=(Xn=(Ir=(et=t["--persona-components-scrollToBottom-borderRadius"])!=null?et:t["--persona-button-radius"])!=null?Ir:t["--persona-radius-full"])!=null?Xn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Rn=(Pr=t["--persona-components-scrollToBottom-shadow"])!=null?Pr:t["--persona-palette-shadows-sm"])!=null?Rn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Zr=t["--persona-components-scrollToBottom-padding"])!=null?Zr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(fr=t["--persona-components-scrollToBottom-gap"])!=null?fr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(it=(rr=t["--persona-components-scrollToBottom-fontSize"])!=null?rr:t["--persona-palette-typography-fontSize-sm"])!=null?it:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Sn=t["--persona-components-scrollToBottom-iconSize"])!=null?Sn:"14px",t["--persona-tool-bubble-shadow"]=(jn=t["--persona-components-toolBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(cn=t["--persona-components-reasoningBubble-shadow"])!=null?cn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(hr=t["--persona-components-composer-shadow"])!=null?hr:"none",t["--persona-md-inline-code-bg"]=(An=t["--persona-components-markdown-inlineCode-background"])!=null?An:t["--persona-container"],t["--persona-md-inline-code-color"]=(Et=t["--persona-components-markdown-inlineCode-foreground"])!=null?Et:t["--persona-text"],t["--persona-md-link-color"]=(Hn=(dn=t["--persona-components-markdown-link-foreground"])!=null?dn:t["--persona-accent"])!=null?Hn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(yr=t["--persona-components-markdown-codeBlock-background"])!=null?yr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(or=t["--persona-components-markdown-codeBlock-borderColor"])!=null?or:t["--persona-border"],t["--persona-md-code-block-text-color"]=(br=t["--persona-components-markdown-codeBlock-textColor"])!=null?br:"inherit",t["--persona-md-table-header-bg"]=(Kn=t["--persona-components-markdown-table-headerBackground"])!=null?Kn:t["--persona-container"],t["--persona-md-table-border-color"]=(En=t["--persona-components-markdown-table-borderColor"])!=null?En:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(St=t["--persona-components-markdown-blockquote-borderColor"])!=null?St:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Nt=t["--persona-components-markdown-blockquote-background"])!=null?Nt:"transparent",t["--persona-md-blockquote-text-color"]=(Ft=t["--persona-components-markdown-blockquote-textColor"])!=null?Ft:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Tn=t["--persona-components-collapsibleWidget-container"])!=null?Tn:t["--persona-surface"],t["--cw-surface"]=(xr=t["--persona-components-collapsibleWidget-surface"])!=null?xr:t["--persona-surface"],t["--cw-border"]=(zn=t["--persona-components-collapsibleWidget-border"])!=null?zn:t["--persona-border"],t["--persona-message-border"]=(Mn=t["--persona-components-message-border"])!=null?Mn:t["--persona-border"];let c=e.components,d=c==null?void 0:c.iconButton;d&&(d.background&&(t["--persona-icon-btn-bg"]=d.background),d.border&&(t["--persona-icon-btn-border"]=d.border),d.color&&(t["--persona-icon-btn-color"]=d.color),d.padding&&(t["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(t["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(t["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(t["--persona-icon-btn-active-border"]=d.activeBorder));let p=c==null?void 0:c.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let re=g.toolbar;re.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=re.iconHoverColor),re.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=re.iconHoverBackground),re.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=re.iconPadding),re.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=re.iconBorderRadius),re.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=re.iconBorder),re.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=re.toggleGroupGap),re.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=re.toggleBorderRadius),re.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=re.copyBackground),re.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=re.copyBorder),re.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=re.copyColor),re.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=re.copyBorderRadius),re.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=re.copyPadding),re.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=re.copyMenuBackground,t["--persona-dropdown-bg"]=(N=t["--persona-dropdown-bg"])!=null?N:re.copyMenuBackground),re.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=re.copyMenuBorder,t["--persona-dropdown-border"]=(qn=t["--persona-dropdown-border"])!=null?qn:re.copyMenuBorder),re.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=re.copyMenuShadow,t["--persona-dropdown-shadow"]=(Bn=t["--persona-dropdown-shadow"])!=null?Bn:re.copyMenuShadow),re.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=re.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(vr=t["--persona-dropdown-radius"])!=null?vr:re.copyMenuBorderRadius),re.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=re.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:re.copyMenuItemHoverBackground),re.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=re.iconBackground),re.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=re.toolbarBorder)}if(g!=null&&g.tab){let re=g.tab;re.background&&(t["--persona-artifact-tab-bg"]=re.background),re.activeBackground&&(t["--persona-artifact-tab-active-bg"]=re.activeBackground),re.activeBorder&&(t["--persona-artifact-tab-active-border"]=re.activeBorder),re.borderRadius&&(t["--persona-artifact-tab-radius"]=re.borderRadius),re.textColor&&(t["--persona-artifact-tab-color"]=re.textColor),re.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=re.hoverBackground),re.listBackground&&(t["--persona-artifact-tab-list-bg"]=re.listBackground),re.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=re.listBorderColor),re.listPadding&&(t["--persona-artifact-tab-list-padding"]=re.listPadding)}if(g!=null&&g.pane){let re=g.pane;if(re.toolbarBackground){let kn=(fn=_o(e,re.toolbarBackground))!=null?fn:re.toolbarBackground;t["--persona-artifact-toolbar-bg"]=kn}}return t}var hd={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 au={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"}}},yd=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},jo=()=>{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"},iu=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":jo()},ba=e=>iu(e),lu=e=>co(e),cu=e=>{var t;let r=co(void 0,{validate:!1});return co({...e,palette:{...r.palette,colors:{...au.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},zo=e=>{let r=ba(e),t=yd(e==null?void 0:e.theme),n=yd(e==null?void 0:e.darkTheme);return r==="dark"?cu($o(t!=null?t:{},n!=null?n:{})):lu(t)},du=e=>Rs(e),Er=(e,r)=>{var o;let t=zo(r),n=du(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Hs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(jo())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(jo());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var bd=require("idiomorph"),xd=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;bd.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n){if(s.classList.contains("persona-animate-typing"))return!1;if(s.hasAttribute("data-preserve-animation"))return o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation")?void 0:!1}}}})};function vd(e,r){var t,n,s,o,a,i,u,c,d,p,f,g,v,T,C,S,M,R,w,k,P,E,V,te,Z,O,ee;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(d=(c=e.llmContent)==null?void 0:c.length)!=null?d:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(S=(C=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:C.length)!=null?S:0,(k=(w=(R=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?k:"",typeof((P=e.toolCall)==null?void 0:P.args)=="string"?e.toolCall.args.length:(E=e.toolCall)!=null&&E.args?JSON.stringify(e.toolCall.args).length:0,(Z=(te=(V=e.reasoning)==null?void 0:V.chunks)==null?void 0:te.length)!=null?Z:0,(ee=(O=e.contentParts)==null?void 0:O.length)!=null?ee:0,r].join("\0")}function Cd(){return new Map}function wd(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Sd(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Ad(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Bs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function qo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Uo(e,r){return qo(e)-e.scrollTop<=r}function Ds(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,d=t-n;return a||Math.abs(d)<o?{action:"none",delta:d,nextLastScrollTop:t}:!r&&s&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:t}:r&&i&&d<0?{action:"pause",delta:d,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:d,nextLastScrollTop:t}:{action:"none",delta:d,nextLastScrollTop:t}}function Ns(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var ln={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cn=1e5,Tr=Cn+1;function xa(e,r=Cn){let t=e.style.position,n=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(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Vo=0,Mr=null;function va(e=document){var t;if(Vo++,Vo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Mr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Vo=Math.max(0,Vo-1),Vo===0&&Mr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=Mr.originalOverflow,s.style.position=Mr.originalPosition,s.style.top=Mr.originalTop,s.style.width=Mr.originalWidth,o.scrollTo(0,Mr.scrollY),Mr=null}}}var Fs={side:"right",width:"420px",animate:!0,reveal:"resize"},Gt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},On=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:Fs.side,width:(s=r==null?void 0:r.width)!=null?s:Fs.width,animate:(o=r==null?void 0:r.animate)!=null?o:Fs.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Fs.reveal}};var Yn={"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 Jo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
6
+ `);a=(ce=Je.pop())!=null?ce:"";for(let Rt of Je){let xt=Rt.split(`
7
+ `),ot="message",ct="";for(let I of xt)I.startsWith("event:")?ot=I.replace("event:","").trim():I.startsWith("data:")&&(ct+=I.replace("data:","").trim());if(!ct)continue;let b;try{b=JSON.parse(ct)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let Le=ot!=="message"?ot:(_e=b.type)!=null?_e:"message";if((ee=this.onSSEEvent)==null||ee.call(this,Le,b),this.parseSSEEvent){g.current=f;let I=await this.handleCustomSSEEvent(b,t,g,d,c,v);if(g.current&&g.current!==f&&(f=g.current),I)continue}if(Le==="reason_start"){let I=(ie=O(b,!0))!=null?ie:`reason-${c()}`,x=ne(I);x.reasoning=(kt=x.reasoning)!=null?kt:{id:I,status:"streaming",chunks:[]},x.reasoning.startedAt=(Bt=x.reasoning.startedAt)!=null?Bt:X((dt=b.startedAt)!=null?dt:b.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",d(x)}else if(Le==="reason_delta"||Le==="reason_chunk"){let I=(je=(Kt=O(b,!1))!=null?Kt:O(b,!0))!=null?je:`reason-${c()}`,x=ne(I);x.reasoning=(ue=x.reasoning)!=null?ue:{id:I,status:"streaming",chunks:[]},x.reasoning.startedAt=(It=x.reasoning.startedAt)!=null?It:X((Ne=b.startedAt)!=null?Ne:b.timestamp);let _=(it=(at=(Pt=b.reasoningText)!=null?Pt:b.text)!=null?at:b.delta)!=null?it:"";if(_&&b.hidden!==!0){let D=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(D!==void 0){let fe=Re(de,I,D,String(_));x.reasoning.chunks=[fe]}else x.reasoning.chunks.push(String(_))}if(x.reasoning.status=b.done?"complete":"streaming",b.done){x.reasoning.completedAt=X((tn=b.completedAt)!=null?tn:b.timestamp);let D=(en=x.reasoning.startedAt)!=null?en:Date.now();x.reasoning.durationMs=Math.max(0,((nn=x.reasoning.completedAt)!=null?nn:Date.now())-D),de.delete(I)}x.streaming=x.reasoning.status!=="complete",d(x)}else if(Le==="reason_complete"){let I=(He=(q=O(b,!1))!=null?q:O(b,!0))!=null?He:`reason-${c()}`,x=C.get(I);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=X((he=b.completedAt)!=null?he:b.timestamp);let D=(ht=x.reasoning.startedAt)!=null?ht:Date.now();x.reasoning.durationMs=Math.max(0,(($e=x.reasoning.completedAt)!=null?$e:Date.now())-D),x.streaming=!1,de.delete(I),d(x)}let _=k(b);_&&M.byStep.delete(_)}else if(Le==="tool_start"){let I=(le=ke(b,!0))!=null?le:`tool-${c()}`,x=(we=b.toolName)!=null?we:b.name;if(Me(x)){re.add(I);continue}let _=oe(I),D=(Oe=_.toolCall)!=null?Oe:{id:I,status:"pending"};D.name=x!=null?x:D.name,D.status="running",b.args!==void 0?D.args=b.args:b.parameters!==void 0&&(D.args=b.parameters),D.startedAt=(jt=D.startedAt)!=null?jt:X((wt=b.startedAt)!=null?wt:b.timestamp),D.completedAt=void 0,D.durationMs=void 0,_.toolCall=D,_.streaming=!0;let fe=b.agentContext;(fe||b.executionId)&&(_.agentMetadata={executionId:(pt=fe==null?void 0:fe.executionId)!=null?pt:b.executionId,iteration:(zt=fe==null?void 0:fe.iteration)!=null?zt:b.iteration}),d(_)}else if(Le==="tool_chunk"||Le==="tool_delta"){let I=(Qe=(yt=ke(b,!1))!=null?yt:ke(b,!0))!=null?Qe:`tool-${c()}`;if(re.has(I))continue;let x=oe(I),_=(bt=x.toolCall)!=null?bt:{id:I,status:"running"};_.startedAt=(qt=_.startedAt)!=null?qt:X((De=b.startedAt)!=null?De:b.timestamp);let D=(_n=(nr=(Gn=b.text)!=null?Gn:b.delta)!=null?nr:b.message)!=null?_n:"";D&&(_.chunks=(tt=_.chunks)!=null?tt:[],_.chunks.push(String(D))),_.status="running",x.toolCall=_,x.streaming=!0;let fe=b.agentContext;(fe||b.executionId)&&(x.agentMetadata=(Pr=x.agentMetadata)!=null?Pr:{executionId:(Ir=fe==null?void 0:fe.executionId)!=null?Ir:b.executionId,iteration:(Kn=fe==null?void 0:fe.iteration)!=null?Kn:b.iteration}),d(x)}else if(Le==="tool_complete"){let I=(Zr=(Rn=ke(b,!1))!=null?Rn:ke(b,!0))!=null?Zr:`tool-${c()}`;if(re.has(I)){re.delete(I);continue}let x=oe(I),_=(fr=x.toolCall)!=null?fr:{id:I,status:"running"};_.status="complete",b.result!==void 0&&(_.result=b.result),typeof b.duration=="number"&&(_.duration=b.duration),_.completedAt=X((rr=b.completedAt)!=null?rr:b.timestamp);let D=(lt=b.duration)!=null?lt:b.executionTime;if(typeof D=="number")_.durationMs=D;else{let nt=(Sn=_.startedAt)!=null?Sn:Date.now();_.durationMs=Math.max(0,((jn=_.completedAt)!=null?jn:Date.now())-nt)}x.toolCall=_,x.streaming=!1;let fe=b.agentContext;(fe||b.executionId)&&(x.agentMetadata=(An=x.agentMetadata)!=null?An:{executionId:(cn=fe==null?void 0:fe.executionId)!=null?cn:b.executionId,iteration:(hr=fe==null?void 0:fe.iteration)!=null?hr:b.iteration}),d(x);let Ve=P(b);Ve&&H.byCall.delete(Ve)}else if(Le==="text_start"){let I=b.partId;if(I!==void 0&&v.current!==null&&I!==v.current){let x=f;x&&(x.streaming=!1,d(x),Ze=x,f=null,T=!0)}I!==void 0&&(v.current=I)}else if(Le==="text_end"){let I=f;I&&(I.streaming=!1,d(I),Ze=I,f=null,T=!0)}else if(Le==="step_chunk"||Le==="step_delta"){let I=b.stepType,x=b.executionType;if(I==="tool"||x==="context")continue;let _=b.partId;if(_!==void 0&&v.current!==null&&_!==v.current){let Ve=f;Ve&&(Ve.streaming=!1,d(Ve),Ze=Ve,f=null,T=!0)}_!==void 0&&(v.current=_);let D=Q();_!==void 0&&!D.partId&&(D.partId=_);let fe=(yr=(Hn=(dn=(Et=b.text)!=null?Et:b.delta)!=null?dn:b.content)!=null?Hn:b.chunk)!=null?yr:"";if(fe){let Ve=typeof b.seq=="number"?b.seq:void 0,nt;Ve!==void 0?nt=Re(ge,D.id,Ve,fe):nt=((or=te.get(D.id))!=null?or:"")+fe,D.rawContent=nt,V.has(D.id)||V.set(D.id,this.createStreamParser());let Ot=V.get(D.id),un=nt.trim().startsWith("{")||nt.trim().startsWith("[");if(un&&te.set(D.id,nt),Ot.__isPlainTextParser===!0){Ve!==void 0?D.content=nt:D.content+=fe,te.delete(D.id),V.delete(D.id),D.rawContent=void 0,d(D);continue}let $t=Ot.processChunk(nt);if($t instanceof Promise)$t.then(Ke=>{var Zt;let vt=typeof Ke=="string"?Ke:(Zt=Ke==null?void 0:Ke.text)!=null?Zt:null;if(vt!==null&&vt.trim()!=="")D.content=vt,d(D);else if(!un&&!nt.trim().startsWith("<")){let rn=f;rn&&rn.id===D.id&&(Ve!==void 0?rn.content=nt:rn.content+=fe,te.delete(rn.id),V.delete(rn.id),rn.rawContent=void 0,d(rn))}}).catch(()=>{Ve!==void 0?D.content=nt:D.content+=fe,te.delete(D.id),V.delete(D.id),D.rawContent=void 0,d(D)});else{let Ke=typeof $t=="string"?$t:(br=$t==null?void 0:$t.text)!=null?br:null;Ke!==null&&Ke.trim()!==""?(D.content=Ke,d(D)):!un&&!nt.trim().startsWith("<")&&(Ve!==void 0?D.content=nt:D.content+=fe,te.delete(D.id),V.delete(D.id),D.rawContent=void 0,d(D))}}if(b.isComplete){let Ve=(En=(Xn=b.result)==null?void 0:Xn.response)!=null?En:D.content;if(Ve){let nt=te.get(D.id),Ot=nt!=null?nt:pe(Ve);D.rawContent=Ot;let un=V.get(D.id),Xt=null,$t=!1;if(un&&(Xt=un.getExtractedText(),Xt===null&&(Xt=jr(Ot)),Xt===null)){let Ke=un.processChunk(Ot);Ke instanceof Promise?($t=!0,Ke.then(vt=>{var rn;let Zt=typeof vt=="string"?vt:(rn=vt==null?void 0:vt.text)!=null?rn:null;if(Zt!==null){let Dt=f;Dt&&Dt.id===D.id&&(Dt.content=Zt,Dt.streaming=!1,V.delete(Dt.id),te.delete(Dt.id),ge.delete(Dt.id),d(Dt))}})):Xt=typeof Ke=="string"?Ke:(Zn=Ke==null?void 0:Ke.text)!=null?Zn:null}if(!$t){Xt!==null&&Xt.trim()!==""?D.content=Xt:te.has(D.id)||(D.content=pe(Ve));let Ke=V.get(D.id);if(Ke){let vt=(St=Ke.close)==null?void 0:St.call(Ke);vt instanceof Promise&&vt.catch(()=>{}),V.delete(D.id)}te.delete(D.id),ge.delete(D.id),D.streaming=!1,d(D)}}}}else if(Le==="step_complete"){let I=b.stepType,x=b.executionType;if(I==="tool"||x==="context")continue;if(T){if(f!==null){let nt=f;V.delete(nt.id),te.delete(nt.id),ge.delete(nt.id),nt.streaming!==!1&&(nt.streaming=!1,d(nt))}let fe=(Ft=b.result)==null?void 0:Ft.response,Ve=Ze;Ve&&(fe!=null?z(Ve,fe):(V.delete(Ve.id),te.delete(Ve.id))),Ze=null;continue}let _=(Nt=b.result)==null?void 0:Nt.response,D=Q();if(_!=null){let fe=V.get(D.id),Ve=!1,nt=!1;if(fe){let Ot=fe.getExtractedText(),un=te.get(D.id),Xt=un!=null?un:pe(_);if(D.rawContent=Xt,Ot!==null&&Ot.trim()!=="")D.content=Ot,Ve=!0;else{let $t=jr(Xt);if($t!==null)D.content=$t,Ve=!0;else{let Ke=fe.processChunk(Xt);if(Ke instanceof Promise)nt=!0,Ke.then(vt=>{var rn;let Zt=typeof vt=="string"?vt:(rn=vt==null?void 0:vt.text)!=null?rn:null;if(Zt!==null&&Zt.trim()!==""){let Dt=f;Dt&&Dt.id===D.id&&(Dt.content=Zt,Dt.streaming=!1,V.delete(Dt.id),te.delete(Dt.id),ge.delete(Dt.id),d(Dt))}else{let Dt=fe.getExtractedText(),In=f;In&&In.id===D.id&&(Dt!==null&&Dt.trim()!==""?In.content=Dt:te.has(In.id)||(In.content=pe(_)),In.streaming=!1,V.delete(In.id),te.delete(In.id),ge.delete(In.id),d(In))}});else{let vt=typeof Ke=="string"?Ke:(Tn=Ke==null?void 0:Ke.text)!=null?Tn:null;if(vt!==null&&vt.trim()!=="")D.content=vt,Ve=!0;else{let Zt=fe.getExtractedText();Zt!==null&&Zt.trim()!==""&&(D.content=Zt,Ve=!0)}}}}}if(!nt){if(!D.rawContent){let Ot=te.get(D.id);D.rawContent=Ot!=null?Ot:pe(_)}if(!Ve&&!te.has(D.id)&&(D.content=pe(_)),fe){let Ot=(xr=fe.close)==null?void 0:xr.call(fe);Ot instanceof Promise&&Ot.catch(()=>{})}V.delete(D.id),te.delete(D.id),ge.delete(D.id),D.streaming=!1,d(D)}}else V.delete(D.id),te.delete(D.id),ge.delete(D.id),D.streaming=!1,d(D)}else if(Le==="flow_complete"){let I=(zn=b.result)==null?void 0:zn.response;if(T){if(f!==null){let x=f;V.delete(x.id),te.delete(x.id),ge.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}}else if(I!=null){let x=Q(),_=te.get(x.id),D=_!=null?_:pe(I);x.rawContent=D;let fe=pe(I),Ve=V.get(x.id);if(Ve){let un=jr(D);if(un!==null)fe=un;else{let Xt=Ve.processChunk(D);Xt instanceof Promise&&Xt.then(Ke=>{var Zt;let vt=typeof Ke=="string"?Ke:(Zt=Ke==null?void 0:Ke.text)!=null?Zt:null;vt!==null&&(x.content=vt,x.streaming=!1,d(x))});let $t=Ve.getExtractedText();$t!==null&&(fe=$t)}}V.delete(x.id),te.delete(x.id),ge.delete(x.id);let nt=fe!==x.content,Ot=x.streaming!==!1;nt&&(x.content=fe),x.streaming=!1,(nt||Ot)&&d(x)}else if(f!==null){let x=f;V.delete(x.id),te.delete(x.id),ge.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}t({type:"status",status:"idle"})}else if(Le==="agent_start")W={executionId:b.executionId,agentId:(Mn=b.agentId)!=null?Mn:"virtual",agentName:(F=b.agentName)!=null?F:"",status:"running",currentIteration:0,maxTurns:(qn=b.maxTurns)!=null?qn:1,startedAt:X(b.startedAt)};else if(Le==="agent_iteration_start"){if(W&&(W.currentIteration=b.iteration),$==="separate"&&b.iteration>1){let I=f;I&&(I.streaming=!1,d(I),se.set(b.iteration-1,I),f=null)}}else if(Le!=="agent_turn_start"){if(Le==="agent_turn_delta"){if(b.contentType==="text"){let I=Q();I.content+=(Bn=b.delta)!=null?Bn:"",I.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:W==null?void 0:W.agentName},d(I)}else if(b.contentType==="thinking"){let I=(vr=b.turnId)!=null?vr:`agent-think-${b.iteration}`,x=ne(I);x.reasoning=(gn=x.reasoning)!=null?gn:{id:I,status:"streaming",chunks:[]},x.reasoning.chunks.push((fn=b.delta)!=null?fn:""),x.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},d(x)}else if(b.contentType==="tool_input"){let I=(ae=b.toolCallId)!=null?ae:H.lastId;if(I){let x=S.get(I);x!=null&&x.toolCall&&(x.toolCall.chunks=(kn=x.toolCall.chunks)!=null?kn:[],x.toolCall.chunks.push((sr=b.delta)!=null?sr:""),d(x))}}}else if(Le==="agent_turn_complete"){let I=b.turnId;if(I){let x=C.get(I);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=X(b.completedAt);let _=(ns=x.reasoning.startedAt)!=null?ns:Date.now();x.reasoning.durationMs=Math.max(0,((xo=x.reasoning.completedAt)!=null?xo:Date.now())-_),x.streaming=!1,d(x)}}}else if(Le==="agent_tool_start"){let I=(rs=b.toolCallId)!=null?rs:`agent-tool-${c()}`;Ce(P(b),I);let x=oe(I),_=(Qr=x.toolCall)!=null?Qr:{id:I,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};_.name=(vo=(et=b.toolName)!=null?et:b.name)!=null?vo:_.name,_.status="running",b.parameters!==void 0&&(_.args=b.parameters),_.startedAt=X((Dn=b.startedAt)!=null?Dn:b.timestamp),x.toolCall=_,x.streaming=!0,x.agentMetadata={executionId:b.executionId,iteration:b.iteration},d(x)}else if(Le==="agent_tool_delta"){let I=(hn=b.toolCallId)!=null?hn:H.lastId;if(I){let x=(os=S.get(I))!=null?os:oe(I);x.toolCall&&(x.toolCall.chunks=(ss=x.toolCall.chunks)!=null?ss:[],x.toolCall.chunks.push((Co=b.delta)!=null?Co:""),x.toolCall.status="running",x.streaming=!0,d(x))}}else if(Le==="agent_tool_complete"){let I=(ar=b.toolCallId)!=null?ar:H.lastId;if(I){let x=(as=S.get(I))!=null?as:oe(I);if(x.toolCall){x.toolCall.status="complete",b.result!==void 0&&(x.toolCall.result=b.result),typeof b.executionTime=="number"&&(x.toolCall.durationMs=b.executionTime),x.toolCall.completedAt=X((Wr=b.completedAt)!=null?Wr:b.timestamp),x.streaming=!1,d(x);let _=P(b);_&&H.byCall.delete(_)}}}else if(Le!=="agent_iteration_complete"){if(Le==="agent_reflection"||Le==="agent_reflect"){let I=`agent-reflection-${b.executionId}-${b.iteration}`,x={id:I,role:"assistant",content:(wo=b.reflection)!=null?wo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"complete",chunks:[(ir=b.reflection)!=null?ir:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};d(x)}else if(Le==="agent_complete"){W&&(W.status=b.success?"complete":"error",W.completedAt=X(b.completedAt),W.stopReason=b.stopReason);let I=f;I&&(I.streaming=!1,d(I)),t({type:"status",status:"idle"})}else if(Le==="agent_error"){let I=typeof b.error=="string"?b.error:(Cr=(So=b.error)==null?void 0:So.message)!=null?Cr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",I):t({type:"error",error:new Error(I)})}else if(Le!=="agent_ping")if(Le==="agent_approval_start"){let I=(wr=b.approvalId)!=null?wr:`approval-${c()}`,x={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(is=W==null?void 0:W.agentId)!=null?is:"virtual",executionId:(la=(ls=b.executionId)!=null?ls:W==null?void 0:W.executionId)!=null?la:"",toolName:(Rr=b.toolName)!=null?Rr:"",toolType:b.toolType,description:(Wt=b.description)!=null?Wt:`Execute ${(Hr=b.toolName)!=null?Hr:"tool"}`,parameters:b.parameters}};d(x)}else if(Le==="step_await"&&b.awaitReason==="approval_required"){let I=(eo=b.approvalId)!=null?eo:`approval-${c()}`,x={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(to=W==null?void 0:W.agentId)!=null?to:"virtual",executionId:(Qn=(Ao=b.executionId)!=null?Ao:W==null?void 0:W.executionId)!=null?Qn:"",toolName:(cs=b.toolName)!=null?cs:"",toolType:b.toolType,description:(To=b.description)!=null?To:`Execute ${(Eo=b.toolName)!=null?Eo:"tool"}`,parameters:b.parameters}};d(x)}else if(Le==="agent_approval_complete"){let I=b.approvalId;if(I){let _={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:(Mo=b.decision)!=null?Mo:"approved",agentId:(pn=W==null?void 0:W.agentId)!=null?pn:"virtual",executionId:(lr=(Ln=b.executionId)!=null?Ln:W==null?void 0:W.executionId)!=null?lr:"",toolName:(Ue=b.toolName)!=null?Ue:"",description:(ko=b.description)!=null?ko:"",resolvedAt:Date.now()}};d(_)}}else if(Le==="artifact_start"||Le==="artifact_delta"||Le==="artifact_update"||Le==="artifact_complete"){if(Le==="artifact_start"){let I=b.artifactType,x=String(b.id),_=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:x,artifactType:I,title:_,component:typeof b.component=="string"?b.component:void 0}),me.set(x,{markdown:"",title:_}),!We.has(x)){We.add(x);let D={id:`artifact-ref-${x}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:x,title:_,artifactType:I,status:"streaming"}})};xe.set(x,D),d(D)}}else if(Le==="artifact_delta"){let I=String(b.id),x=typeof b.delta=="string"?b.delta:String((Br=b.delta)!=null?Br:"");t({type:"artifact_delta",id:I,artDelta:x});let _=me.get(I);_&&(_.markdown+=x)}else if(Le==="artifact_update"){let I=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:I,component:typeof b.component=="string"?b.component:void 0})}else if(Le==="artifact_complete"){let I=String(b.id);t({type:"artifact_complete",id:I});let x=xe.get(I);if(x){x.streaming=!1;try{let _=JSON.parse((Un=x.rawContent)!=null?Un:"{}");if(_.props){_.props.status="complete";let D=me.get(I);D!=null&&D.markdown&&(_.props.markdown=D.markdown)}x.rawContent=JSON.stringify(_)}catch{}me.delete(I),d(x),xe.delete(I)}}}else if(Le==="transcript_insert"){let I=b.message;if(!I||typeof I!="object")continue;let x=String((ds=I.id)!=null?ds:`msg-${c()}`),_=I.role,fe={id:x,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof I.content=="string"?I.content:"",rawContent:typeof I.rawContent=="string"?I.rawContent:void 0,createdAt:typeof I.createdAt=="string"?I.createdAt:new Date().toISOString(),streaming:I.streaming===!0,...typeof I.variant=="string"?{variant:I.variant}:{},sequence:c()};if(d(fe),fe.rawContent)try{let Ve=JSON.parse(fe.rawContent),nt=(no=Ve==null?void 0:Ve.props)==null?void 0:no.artifactId;typeof nt=="string"&&We.add(nt)}catch{}f=null,g.current=null,V.delete(x),te.delete(x),ge.delete(x)}else Le==="error"&&b.error&&t({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function nd(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function io(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function qr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ms="[Image]";function rd(e){return typeof e=="string"?[{type:"text",text:e}]:e}function od(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function sd(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function ad(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Fo(e){return{type:"text",text:e}}function id(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function ld(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function cd(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.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: ${r.join(", ")}`}}var dd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Qp=["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"],pr=[...dd,...Qp];function eu(e){return dd.includes(e)||e.startsWith("image/")}function ks(e){return eu(e.type)}async function pd(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;ks(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function ud(e,r=pr,t=10*1024*1024){return r.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: ${r.join(", ")}`}}function tu(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function md(e,r){let t=tu(r).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 Ls=class{constructor(r=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=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.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 u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var Is=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 p=0;p<a.length;p++)i+=a[p]*a[p];let u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=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 No=class{constructor(r){this.config=r;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 Is;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;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=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let v=!1,T=S=>{v||(v=!0,clearTimeout(C),g(new Error(S)))},C=setTimeout(()=>T("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(C),f())},{once:!0}),this.ws.addEventListener("error",()=>{T("WebSocket connection failed to "+p+"."+d)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!v){let M=S.code!==1006?` (code ${S.code})`:"";T("WebSocket connection failed"+M+"."+d)}},{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(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.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(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ls(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",d=new Blob(this.audioChunks,{type:p});await this.sendAudio(d),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("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(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ur=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.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(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({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(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Vr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new No(e.runtype);case"browser":if(!Ur.isSupported())throw new Error("Browser speech recognition not supported");return new Ur(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ps(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Vr({type:"runtype",runtype:e.runtype});if(Ur.isSupported())return Vr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Oo(e){try{return Ps(e),!0}catch{return!1}}var lo=class e{constructor(r={},t){this.config=r;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new zr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Oo((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Vr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,d,f,g,v,T;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let C=(T=this.pendingVoiceAssistantMessageId)!=null?T:(v=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:v.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.call(p,c)}),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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new zr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?io():t==="assistant"?qr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:p,streaming:d=!1}=n,g={id:u!=null?u:s==="user"?io():s==="assistant"?qr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:d,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,d,f,g;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=io(),o=qr(),a={id:s,role:"user",content:n||Ms,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let T=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!T){let C={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(C)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,T||(v instanceof Error?(d=(p=this.callbacks).onError)==null||d.call(p,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=qr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(p=(c=this.callbacks).onError)==null||p.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.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(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},er=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var nu=qc(require("lucide"),1),ye=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=nu[s];return o?ru(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function ru(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),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){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),s.appendChild(u)}}}),s}var Ws={allowedTypes:pr,maxFileSize:10*1024*1024,maxFiles:4};function ou(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function su(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-json":"file"}var Jr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ws.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Ws.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Ws.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:Ws.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=ud(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let d=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await pd(c),f=ks(c)?URL.createObjectURL(c):null,g={id:ou(),file:c,previewUrl:f,contentPart:d};this.attachments.push(g),this.renderPreview(g)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=ks(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.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=su(r.file.type),u=ye(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=md(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.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(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var gd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function $o(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];gd(o)&&gd(s)?t[n]=$o(o,s):t[n]=s}return t}var Wn="min(440px, calc(100vw - 24px))",Rs="440px",Mt={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:Wn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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"}},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 fd(e,r){if(!(!e&&!r))return e?r?$o(e,r):e:r}function Hs(e){var r,t,n,s,o,a,i,u,c,p,d,f,g,v,T,C,S,M,H,w,k;return e?{...Mt,...e,theme:fd(Mt.theme,e.theme),darkTheme:fd(Mt.darkTheme,e.darkTheme),launcher:{...Mt.launcher,...e.launcher,dock:{...(r=Mt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Mt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Mt.copy,...e.copy},sendButton:{...Mt.sendButton,...e.sendButton},statusIndicator:{...Mt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Mt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ne,Ce,re,xe;let P=(ne=Mt.features)==null?void 0:ne.artifacts,E=(Ce=e.features)==null?void 0:Ce.artifacts,G=(re=Mt.features)==null?void 0:re.scrollToBottom,Q=(xe=e.features)==null?void 0:xe.scrollToBottom,K=P===void 0&&E===void 0?void 0:{...P,...E,layout:{...P==null?void 0:P.layout,...E==null?void 0:E.layout}},O=G===void 0&&Q===void 0?void 0:{...G,...Q};return{...Mt.features,...e.features,...O!==void 0?{scrollToBottom:O}:{},...K!==void 0?{artifacts:K}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Mt.suggestionChips,suggestionChipsConfig:{...Mt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Mt.layout,...e.layout,header:{...(a=Mt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=Mt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(p=Mt.layout)==null?void 0:p.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(T=(v=Mt.layout)==null?void 0:v.messages)==null?void 0:T.timestamp,...(S=(C=e.layout)==null?void 0:C.messages)==null?void 0:S.timestamp}},slots:{...(M=Mt.layout)==null?void 0:M.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...Mt.markdown,...e.markdown,options:{...(w=Mt.markdown)==null?void 0:w.options,...(k=e.markdown)==null?void 0:k.options}},messageActions:{...Mt.messageActions,...e.messageActions}}:Mt}var ha={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"}},ya={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"}},ba={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:Wn,maxWidth:Rs,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"},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 _o(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?_o(e,n):n}function Bs(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=_o(e,a);u!==void 0&&(r[i]={path:i,value:u,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"),r}function xa(e){let r=[],t=[];return e.palette||r.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:r.length===0,errors:r,warnings:t}}function hd(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=hd(o,s):t[n]=s}return t}function au(e,r){return r?hd(e,r):e}function co(e,r={}){var s,o,a,i,u,c,p,d,f,g,v,T,C;let t={palette:ha,semantic:ya,components:ba},n={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,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(f=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(T=e==null?void 0:e.semantic)==null?void 0:T.spacing},typography:{...t.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:au(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let S=xa(n);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let S of r.plugins)n=S.transform(n);return n}function Ds(e){var v,T,C,S,M,H,w,k,P,E,G,Q,K,O,ne,Ce,re,xe,We,me,Me,ke,oe,X,pe,V,te,ge,de,Re,Ze,z,W,se,$,U,ce,_e,ee,ie,kt,dt,Bt,Kt,je,ue,Ne,It,Pt,at,it,tn,en,nn,q,He,he,ht,$e,le,we,Oe,wt,jt,pt,zt,yt,Qe,bt,De,qt,Gn,nr,_n,tt,Ir,Kn,Pr,Rn,Zr,fr,rr,lt,Sn,jn,cn,hr,An,Et,dn,Hn,yr,or,br,Xn,En,Zn,St,Ft,Nt,Tn,xr,zn,Mn,F,qn,Bn,vr,gn,fn;let r=Bs(e),t={};for(let[ae,kn]of Object.entries(r)){let sr=ae.replace(/\./g,"-");t[`--persona-${sr}`]=kn.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"]=(C=t["--persona-semantic-colors-accent"])!=null?C:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(k=t["--persona-semantic-colors-text-muted"])!=null?k:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(G=t["--persona-semantic-colors-divider"])!=null?G:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(Q=t["--persona-components-voice-recording-indicator"])!=null?Q:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(K=t["--persona-components-voice-recording-background"])!=null?K:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ce=t["--persona-components-approval-requested-background"])!=null?Ce: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"]=(xe=t["--persona-components-approval-requested-text"])!=null?xe:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(We=t["--persona-components-approval-approve-background"])!=null?We:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(me=t["--persona-components-approval-deny-background"])!=null?me: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"]=(ke=t["--persona-components-attachment-image-border"])!=null?ke:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(X=t["--persona-semantic-typography-fontSize"])!=null?X:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(pe=t["--persona-semantic-typography-fontWeight"])!=null?pe:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(V=t["--persona-semantic-typography-lineHeight"])!=null?V: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"]=(te=t["--persona-palette-radius-sm"])!=null?te:"0.125rem",t["--persona-radius-md"]=(ge=t["--persona-palette-radius-md"])!=null?ge:"0.375rem",t["--persona-radius-lg"]=(de=t["--persona-palette-radius-lg"])!=null?de:"0.5rem",t["--persona-radius-xl"]=(Re=t["--persona-palette-radius-xl"])!=null?Re:"0.75rem",t["--persona-radius-full"]=(Ze=t["--persona-palette-radius-full"])!=null?Ze:"9999px",t["--persona-launcher-radius"]=(W=(z=t["--persona-components-launcher-borderRadius"])!=null?z:t["--persona-palette-radius-full"])!=null?W:"9999px",t["--persona-launcher-bg"]=(se=t["--persona-components-launcher-background"])!=null?se:t["--persona-primary"],t["--persona-launcher-fg"]=($=t["--persona-components-launcher-foreground"])!=null?$:t["--persona-text-inverse"],t["--persona-launcher-border"]=(U=t["--persona-components-launcher-border"])!=null?U:t["--persona-border"],t["--persona-button-primary-bg"]=(ce=t["--persona-components-button-primary-background"])!=null?ce:t["--persona-primary"],t["--persona-button-primary-fg"]=(_e=t["--persona-components-button-primary-foreground"])!=null?_e:t["--persona-text-inverse"],t["--persona-button-radius"]=(ie=(ee=t["--persona-components-button-primary-borderRadius"])!=null?ee:t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-panel-radius"]=(dt=(kt=t["--persona-components-panel-borderRadius"])!=null?kt:t["--persona-radius-xl"])!=null?dt:"0.75rem",t["--persona-panel-border"]=(Bt=t["--persona-components-panel-border"])!=null?Bt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(je=(Kt=t["--persona-components-panel-shadow"])!=null?Kt:t["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ne=(ue=t["--persona-components-input-borderRadius"])!=null?ue:t["--persona-radius-lg"])!=null?Ne:"0.5rem",t["--persona-message-user-radius"]=(Pt=(It=t["--persona-components-message-user-borderRadius"])!=null?It:t["--persona-radius-lg"])!=null?Pt:"0.5rem",t["--persona-message-assistant-radius"]=(it=(at=t["--persona-components-message-assistant-borderRadius"])!=null?at:t["--persona-radius-lg"])!=null?it:"0.5rem",t["--persona-header-bg"]=(tn=t["--persona-components-header-background"])!=null?tn:t["--persona-surface"],t["--persona-header-border"]=(en=t["--persona-components-header-border"])!=null?en:t["--persona-divider"],t["--persona-header-icon-bg"]=(nn=t["--persona-components-header-iconBackground"])!=null?nn:t["--persona-primary"],t["--persona-header-icon-fg"]=(q=t["--persona-components-header-iconForeground"])!=null?q:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(He=t["--persona-components-header-titleForeground"])!=null?He:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(he=t["--persona-components-header-subtitleForeground"])!=null?he:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ht=t["--persona-components-header-actionIconForeground"])!=null?ht:t["--persona-muted"];let n=($e=e.components)==null?void 0:$e.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(le=t["--persona-components-input-background"])!=null?le:t["--persona-surface"],t["--persona-input-placeholder"]=(we=t["--persona-components-input-placeholder"])!=null?we:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Oe=t["--persona-components-message-user-background"])!=null?Oe:t["--persona-accent"],t["--persona-message-user-text"]=(wt=t["--persona-components-message-user-text"])!=null?wt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(jt=t["--persona-components-message-user-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(pt=t["--persona-components-message-assistant-background"])!=null?pt:t["--persona-surface"],t["--persona-message-assistant-text"]=(zt=t["--persona-components-message-assistant-text"])!=null?zt: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"]=(Qe=t["--persona-components-message-assistant-shadow"])!=null?Qe:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(De=(bt=t["--persona-components-scrollToBottom-background"])!=null?bt:t["--persona-button-primary-bg"])!=null?De:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Gn=(qt=t["--persona-components-scrollToBottom-foreground"])!=null?qt:t["--persona-button-primary-fg"])!=null?Gn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(nr=t["--persona-components-scrollToBottom-border"])!=null?nr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(_n=t["--persona-components-scrollToBottom-size"])!=null?_n:"40px",t["--persona-scroll-to-bottom-radius"]=(Kn=(Ir=(tt=t["--persona-components-scrollToBottom-borderRadius"])!=null?tt:t["--persona-button-radius"])!=null?Ir:t["--persona-radius-full"])!=null?Kn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Rn=(Pr=t["--persona-components-scrollToBottom-shadow"])!=null?Pr:t["--persona-palette-shadows-sm"])!=null?Rn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Zr=t["--persona-components-scrollToBottom-padding"])!=null?Zr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(fr=t["--persona-components-scrollToBottom-gap"])!=null?fr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(lt=(rr=t["--persona-components-scrollToBottom-fontSize"])!=null?rr:t["--persona-palette-typography-fontSize-sm"])!=null?lt:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(Sn=t["--persona-components-scrollToBottom-iconSize"])!=null?Sn:"14px",t["--persona-tool-bubble-shadow"]=(jn=t["--persona-components-toolBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(cn=t["--persona-components-reasoningBubble-shadow"])!=null?cn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(hr=t["--persona-components-composer-shadow"])!=null?hr:"none",t["--persona-md-inline-code-bg"]=(An=t["--persona-components-markdown-inlineCode-background"])!=null?An:t["--persona-container"],t["--persona-md-inline-code-color"]=(Et=t["--persona-components-markdown-inlineCode-foreground"])!=null?Et:t["--persona-text"],t["--persona-md-link-color"]=(Hn=(dn=t["--persona-components-markdown-link-foreground"])!=null?dn:t["--persona-accent"])!=null?Hn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(yr=t["--persona-components-markdown-codeBlock-background"])!=null?yr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(or=t["--persona-components-markdown-codeBlock-borderColor"])!=null?or:t["--persona-border"],t["--persona-md-code-block-text-color"]=(br=t["--persona-components-markdown-codeBlock-textColor"])!=null?br:"inherit",t["--persona-md-table-header-bg"]=(Xn=t["--persona-components-markdown-table-headerBackground"])!=null?Xn:t["--persona-container"],t["--persona-md-table-border-color"]=(En=t["--persona-components-markdown-table-borderColor"])!=null?En:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(St=t["--persona-components-markdown-blockquote-borderColor"])!=null?St:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Ft=t["--persona-components-markdown-blockquote-background"])!=null?Ft:"transparent",t["--persona-md-blockquote-text-color"]=(Nt=t["--persona-components-markdown-blockquote-textColor"])!=null?Nt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Tn=t["--persona-components-collapsibleWidget-container"])!=null?Tn:t["--persona-surface"],t["--cw-surface"]=(xr=t["--persona-components-collapsibleWidget-surface"])!=null?xr:t["--persona-surface"],t["--cw-border"]=(zn=t["--persona-components-collapsibleWidget-border"])!=null?zn:t["--persona-border"],t["--persona-message-border"]=(Mn=t["--persona-components-message-border"])!=null?Mn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.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 d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let ae=g.toolbar;ae.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ae.iconHoverColor),ae.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ae.iconHoverBackground),ae.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ae.iconPadding),ae.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ae.iconBorderRadius),ae.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ae.iconBorder),ae.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ae.toggleGroupGap),ae.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ae.toggleBorderRadius),ae.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ae.copyBackground),ae.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ae.copyBorder),ae.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ae.copyColor),ae.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ae.copyBorderRadius),ae.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ae.copyPadding),ae.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ae.copyMenuBackground,t["--persona-dropdown-bg"]=(F=t["--persona-dropdown-bg"])!=null?F:ae.copyMenuBackground),ae.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ae.copyMenuBorder,t["--persona-dropdown-border"]=(qn=t["--persona-dropdown-border"])!=null?qn:ae.copyMenuBorder),ae.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ae.copyMenuShadow,t["--persona-dropdown-shadow"]=(Bn=t["--persona-dropdown-shadow"])!=null?Bn:ae.copyMenuShadow),ae.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ae.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(vr=t["--persona-dropdown-radius"])!=null?vr:ae.copyMenuBorderRadius),ae.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ae.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:ae.copyMenuItemHoverBackground),ae.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ae.iconBackground),ae.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ae.toolbarBorder)}if(g!=null&&g.tab){let ae=g.tab;ae.background&&(t["--persona-artifact-tab-bg"]=ae.background),ae.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ae.activeBackground),ae.activeBorder&&(t["--persona-artifact-tab-active-border"]=ae.activeBorder),ae.borderRadius&&(t["--persona-artifact-tab-radius"]=ae.borderRadius),ae.textColor&&(t["--persona-artifact-tab-color"]=ae.textColor),ae.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ae.hoverBackground),ae.listBackground&&(t["--persona-artifact-tab-list-bg"]=ae.listBackground),ae.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ae.listBorderColor),ae.listPadding&&(t["--persona-artifact-tab-list-padding"]=ae.listPadding)}if(g!=null&&g.pane){let ae=g.pane;if(ae.toolbarBackground){let kn=(fn=_o(e,ae.toolbarBackground))!=null?fn:ae.toolbarBackground;t["--persona-artifact-toolbar-bg"]=kn}}return t}var yd={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 iu={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"}}},bd=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},jo=()=>{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"},lu=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":jo()},va=e=>lu(e),cu=e=>co(e),du=e=>{var t;let r=co(void 0,{validate:!1});return co({...e,palette:{...r.palette,colors:{...iu.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},zo=e=>{let r=va(e),t=bd(e==null?void 0:e.theme),n=bd(e==null?void 0:e.darkTheme);return r==="dark"?du($o(t!=null?t:{},n!=null?n:{})):cu(t)},pu=e=>Ds(e),Er=(e,r)=>{var o;let t=zo(r),n=pu(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},Fs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(jo())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(jo());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var xd=require("idiomorph"),vd=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;xd.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&n){if(s.classList.contains("persona-animate-typing"))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 u=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(u!==c)return}return!1}}}}})};function Cd(e,r){var t,n,s,o,a,i,u,c,p,d,f,g,v,T,C,S,M,H,w,k,P,E,G,Q,K,O,ne,Ce,re;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(C=(T=e.toolCall)==null?void 0:T.name)!=null?C:"",(H=(M=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:M.length)!=null?H:0,(E=(P=(k=(w=e.toolCall)==null?void 0:w.chunks)==null?void 0:k[e.toolCall.chunks.length-1])==null?void 0:P.slice(-32))!=null?E:"",typeof((G=e.toolCall)==null?void 0:G.args)=="string"?e.toolCall.args.length:(Q=e.toolCall)!=null&&Q.args?JSON.stringify(e.toolCall.args).length:0,(ne=(O=(K=e.reasoning)==null?void 0:K.chunks)==null?void 0:O.length)!=null?ne:0,(re=(Ce=e.contentParts)==null?void 0:Ce.length)!=null?re:0,r].join("\0")}function wd(){return new Map}function Sd(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Ad(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Ed(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Ns(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function qo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Uo(e,r){return qo(e)-e.scrollTop<=r}function Os(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function $s(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var ln={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cn=1e5,Tr=Cn+1;function Ca(e,r=Cn){let t=e.style.position,n=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(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Vo=0,Mr=null;function wa(e=document){var t;if(Vo++,Vo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Mr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Vo=Math.max(0,Vo-1),Vo===0&&Mr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=Mr.originalOverflow,s.style.position=Mr.originalPosition,s.style.top=Mr.originalTop,s.style.width=Mr.originalWidth,o.scrollTo(0,Mr.scrollY),Mr=null}}}var _s={side:"right",width:"420px",animate:!0,reveal:"resize"},Gt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},On=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:_s.side,width:(s=r==null?void 0:r.width)!=null?s:_s.width,animate:(o=r==null?void 0:r.animate)!=null?o:_s.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:_s.reveal}};var Yn={"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 Jo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
8
8
  <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>
9
9
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
10
10
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -12,14 +12,14 @@
12
12
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <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>
15
- `,t.addEventListener("click",r);let n=o=>{var R,w,k,P,E,V,te,Z,O,ee,xe,ne,we,De;let a=(R=o.launcher)!=null?R:{},i=Gt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let me=(w=a.title)!=null?w:"Chat Assistant";u.textContent=me,u.setAttribute("title",me)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let me=(k=a.subtitle)!=null?k:"Get answers fast";c.textContent=me,c.setAttribute("title",me)}let d=t.querySelector(".persona-flex-col");d&&(a.textHidden||i?d.style.display="none":d.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let me=(P=a.agentIconSize)!=null?P:"40px";if(p.style.height=me,p.style.width=me,p.innerHTML="",a.agentIconName){let ke=parseFloat(me)||24,Le=fe(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(p.appendChild(Le),p.style.display=""):(p.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(V=a.agentIconText)!=null?V:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let me=(te=a.agentIconSize)!=null?te:"40px";f.style.height=me,f.style.width=me,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let me=(Z=a.callToActionIconSize)!=null?Z:"32px";g.style.height=me,g.style.width=me,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let ke=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,ke=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Le=parseFloat(me)||24,le=Math.max(Le-ke,8),K=fe(a.callToActionIconName,le,"currentColor",2);K?g.appendChild(K):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(ee=a.callToActionIconText)!=null?ee:"\u2197"}let v=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],T="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",C="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?C:`${T} ${v}`,i||(t.style.zIndex=String((xe=a.zIndex)!=null?xe:Cn));let S="1px solid var(--persona-border, #e5e7eb)",M="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=(ne=a.border)!=null?ne:S,t.style.boxShadow=(we=a.shadow)!=null?we:M,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=(De=a.collapsedMaxWidth)!=null?De:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var wn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ur=e=>{var Z,O,ee,xe,ne,we,De,me,ke,Le,le,K,pe,G,oe,ye,Ie,Xe,ft,q,D,ce,j,J,ie,$e,Q,se,kt,ct,Bt,Xt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(Z=r==null?void 0:r.launcher)!=null?Z:{},o=(O=s.headerIconSize)!=null?O:"48px",a=(ee=s.closeButtonSize)!=null?ee:"32px",i=(xe=s.closeButtonPlacement)!=null?xe:"inline",u=(ne=s.headerIconHidden)!=null?ne:!1,c=s.headerIconName,d=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(d.style.height=o,d.style.width=o,d.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",d.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let _e=parseFloat(o)||24,de=fe(c,_e*.6,"currentColor",1);de?d.replaceChildren(de):d.textContent=(De=(we=r==null?void 0:r.launcher)==null?void 0:we.agentIconText)!=null?De:"\u{1F4AC}"}else if((me=r==null?void 0:r.launcher)!=null&&me.iconUrl){let _e=h("img");_e.src=r.launcher.iconUrl,_e.alt="",_e.className="persona-rounded-xl persona-object-cover",_e.style.height=o,_e.style.width=o,d.replaceChildren(_e)}else d.textContent=(Le=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?Le:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=wn.titleColor,f.textContent=(K=(le=r==null?void 0:r.launcher)==null?void 0:le.title)!=null?K:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=wn.subtitleColor,g.textContent=(G=(pe=r==null?void 0:r.launcher)==null?void 0:pe.subtitle)!=null?G:"Here to help you get answers fast",p.append(f,g),u?n.append(p):n.append(d,p);let v=(oe=s.clearChat)!=null?oe:{},T=(ye=v.enabled)!=null?ye:!0,C=(Ie=v.placement)!=null?Ie:"inline",S=null,M=null;if(T){let _e=(Xe=v.size)!=null?Xe:"32px",de=(ft=v.iconName)!=null?ft:"refresh-cw",Ne=(q=v.iconColor)!=null?q:"",It=(D=v.backgroundColor)!=null?D:"",Pt=(ce=v.borderWidth)!=null?ce:"",st=(j=v.borderColor)!=null?j:"",at=(J=v.borderRadius)!=null?J:"",tn=(ie=v.paddingX)!=null?ie:"",en=($e=v.paddingY)!=null?$e:"",nn=(Q=v.tooltipText)!=null?Q:"Clear chat",z=(se=v.showTooltip)!=null?se:!0;M=h("div",C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),C==="top-right"&&(M.style.right="48px"),S=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"),S.style.height=_e,S.style.width=_e,S.type="button",S.setAttribute("aria-label",nn),S.style.color=Ne||wn.actionIconColor;let We=fe(de,"20px","currentColor",1);if(We&&S.appendChild(We),It&&(S.style.backgroundColor=It,S.classList.remove("hover:persona-bg-gray-100")),Pt||st){let ge=Pt||"0px",ht=st||"transparent";S.style.border=`${ge} solid ${ht}`,S.classList.remove("persona-border-none")}if(at&&(S.style.borderRadius=at,S.classList.remove("persona-rounded-full")),tn?(S.style.paddingLeft=tn,S.style.paddingRight=tn):(S.style.paddingLeft="",S.style.paddingRight=""),en?(S.style.paddingTop=en,S.style.paddingBottom=en):(S.style.paddingTop="",S.style.paddingBottom=""),M.appendChild(S),z&&nn&&S&&M){let ge=null,ht=()=>{if(ge||!S)return;let ae=S.ownerDocument,ve=ae.body;if(!ve)return;ge=er(ae,"div","persona-clear-chat-tooltip"),ge.textContent=nn;let Fe=er(ae,"div");Fe.className="persona-clear-chat-tooltip-arrow",ge.appendChild(Fe);let wt=S.getBoundingClientRect();ge.style.position="fixed",ge.style.zIndex=String(Tr),ge.style.left=`${wt.left+wt.width/2}px`,ge.style.top=`${wt.top-8}px`,ge.style.transform="translate(-50%, -100%)",ve.appendChild(ge)},Oe=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};M.addEventListener("mouseenter",ht),M.addEventListener("mouseleave",Oe),S.addEventListener("focus",ht),S.addEventListener("blur",Oe),M._cleanupTooltip=()=>{Oe(),M&&(M.removeEventListener("mouseenter",ht),M.removeEventListener("mouseleave",Oe)),S&&(S.removeEventListener("focus",ht),S.removeEventListener("blur",Oe))}}C==="inline"&&n.appendChild(M)}let R=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":T&&C==="inline"?"":"persona-ml-auto"),w=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");w.style.height=a,w.style.width=a,w.type="button";let k=(kt=s.closeButtonTooltipText)!=null?kt:"Close chat",P=(ct=s.closeButtonShowTooltip)!=null?ct:!0;w.setAttribute("aria-label",k),w.style.display=t?"":"none";let E=(Bt=s.closeButtonIconName)!=null?Bt:"x",V=(Xt=s.closeButtonIconText)!=null?Xt:"\xD7";w.style.color=s.closeButtonColor||wn.actionIconColor;let te=fe(E,"20px","currentColor",1);if(te?w.appendChild(te):w.textContent=V,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let _e=s.closeButtonBorderWidth||"0px",de=s.closeButtonBorderColor||"transparent";w.style.border=`${_e} solid ${de}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),R.appendChild(w),P&&k){let _e=null,de=()=>{if(_e)return;let It=w.ownerDocument,Pt=It.body;if(!Pt)return;_e=er(It,"div","persona-clear-chat-tooltip"),_e.textContent=k;let st=er(It,"div");st.className="persona-clear-chat-tooltip-arrow",_e.appendChild(st);let at=w.getBoundingClientRect();_e.style.position="fixed",_e.style.zIndex=String(Tr),_e.style.left=`${at.left+at.width/2}px`,_e.style.top=`${at.top-8}px`,_e.style.transform="translate(-50%, -100%)",Pt.appendChild(_e)},Ne=()=>{_e&&_e.parentNode&&(_e.parentNode.removeChild(_e),_e=null)};R.addEventListener("mouseenter",de),R.addEventListener("mouseleave",Ne),w.addEventListener("focus",de),w.addEventListener("blur",Ne),R._cleanupTooltip=()=>{Ne(),R.removeEventListener("mouseenter",de),R.removeEventListener("mouseleave",Ne),w.removeEventListener("focus",de),w.removeEventListener("blur",Ne)}}return i!=="top-right"&&n.appendChild(R),{header:n,iconHolder:d,headerTitle:f,headerSubtitle:g,closeButton:w,closeButtonWrapper:R,clearChatButton:S,clearChatButtonWrapper:M}},Yr=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function kr(e){let{items:r,onSelect:t,anchor:n,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(Tr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of r){if(g.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let C=fe(g.icon,16,"currentColor",1.5);C&&v.appendChild(C)}let T=document.createElement("span");T.textContent=g.label,v.appendChild(T),v.addEventListener("click",C=>{C.stopPropagation(),d(),t(g.id)}),a.appendChild(v)}let i=null;function u(){if(!o)return;let g=n.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!n.contains(v.target)&&d()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function d(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():d()}function f(){d(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:d,toggle:p,destroy:f}}function Lt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=fe(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[d,p]of Object.entries(i))u.setAttribute(d,p);return u}function Yo(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let d=h("button",c);if(d.type="button",d.setAttribute("aria-label",t),r){let f=fe(r,o!=null?o:14,"currentColor",2);f&&d.appendChild(f)}let p=h("span");if(p.textContent=t,d.appendChild(p),i&&d.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))d.setAttribute(f,g);return d}function Go(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let d of i)d.btn.setAttribute("aria-pressed",d.id===a?"true":"false")}for(let d of r){let p;d.icon?p=Lt({icon:d.icon,label:d.label,onClick:()=>{a=d.id,u(),n(d.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",d.label),p.title=d.label,p.textContent=d.label,p.addEventListener("click",()=>{a=d.id,u(),n(d.id)})),p.setAttribute("aria-pressed",d.id===a?"true":"false"),i.push({id:d.id,btn:p}),o.appendChild(p)}function c(d){a=d,u()}return{element:o,setSelected:c}}function Os(e){var g,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let d=h("span","persona-combo-btn-label");d.textContent=r,c.appendChild(d);let p=fe(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(v=u.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var T,C;c.style.backgroundColor=(T=u.background)!=null?T:"",c.style.borderColor=(C=u.border)!=null?C:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=kr({items:n,onSelect:T=>{c.setAttribute("aria-expanded","false"),s(T)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",T=>{T.stopPropagation();let C=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",C?"false":"true"),f.toggle()}),c.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),c.click())}),{element:c,setLabel:T=>{d.textContent=T,c.setAttribute("aria-label",T)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Ca=e=>{var n;let r=ur({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.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 r};function pu(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){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=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=fe(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=kr({items:a.menuItems,onSelect:d=>t==null?void 0:t(d),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",d=>{d.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var wa=e=>{var M,R,w,k,P,E,V,te,Z;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},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 u=s==null?void 0:s.titleMenu,c,d;if(u)c=Os({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=wn.titleColor,d=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=h("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=wn.titleColor,d.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(d),pu(c,s==null?void 0:s.trailingActions,(P=s==null?void 0:s.onAction)!=null?P:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ee=s.onTitleClick;c.addEventListener("click",xe=>{xe.target.closest("button")||ee()}),c.addEventListener("keydown",xe=>{(xe.key==="Enter"||xe.key===" ")&&(xe.preventDefault(),ee())})}let O=s==null?void 0:s.titleRowHover;O&&(c.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",c.style.padding=(V=O.padding)!=null?V:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ee,xe;c.style.backgroundColor=(ee=O.background)!=null?ee:"",c.style.borderColor=(xe=O.border)!=null?xe:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(te=a.closeButtonSize)!=null?te:"32px",f=h("div",""),g=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");g.style.height=p,g.style.width=p,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||wn.actionIconColor;let v=(Z=a.closeButtonIconName)!=null?Z:"x",T=fe(v,"20px","currentColor",2);T?g.appendChild(T):g.textContent="\xD7",n&&g.addEventListener("click",n),f.appendChild(g),i.appendChild(f);let C=h("div");C.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:C,headerTitle:d,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},$s={default:Ca,minimal:wa},Sa=e=>{var r;return(r=$s[e])!=null?r:$s.default},po=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),d=h("div");d.style.display="none";let p=h("span"),f=h("span"),g=h("button");g.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:d,headerTitle:p,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Sa(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var uo=e=>{var Ie,Xe,ft,q,D,ce,j,J,ie,$e,Q,se,kt,ct,Bt,Xt,_e,de,Ne,It,Pt,st,at,tn,en,nn,z;let{config:r}=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 n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),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 o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(Xe=(Ie=r==null?void 0:r.copy)==null?void 0:Ie.inputPlaceholder)!=null?Xe:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let We=Math.min(o.scrollHeight,u);o.style.height=`${We}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let d=(ft=r==null?void 0:r.sendButton)!=null?ft:{},p=(q=d.useIcon)!=null?q:!1,f=(D=d.iconText)!=null?D:"\u2191",g=d.iconName,v=(ce=d.tooltipText)!=null?ce:"Send message",T=(j=d.showTooltip)!=null?j:!1,C=(J=d.size)!=null?J:"40px",S=d.backgroundColor,M=d.textColor,R=h("div","persona-send-button-wrapper"),w=h("button",p?"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");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),p){if(w.style.width=C,w.style.height=C,w.style.minWidth=C,w.style.minHeight=C,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",M?w.style.color=M:w.style.color="var(--persona-button-primary-fg, #ffffff)",g){let We=parseFloat(C)||24,ge=(M==null?void 0:M.trim())||"currentColor",ht=fe(g,We,ge,2);ht?w.appendChild(ht):w.textContent=f}else w.textContent=f;S?w.style.backgroundColor=S:w.classList.add("persona-bg-persona-primary")}else w.textContent=($e=(ie=r==null?void 0:r.copy)==null?void 0:ie.sendButtonLabel)!=null?$e:"Send",M?w.style.color=M:w.classList.add("persona-text-white");if(d.borderWidth&&(w.style.borderWidth=d.borderWidth,w.style.borderStyle="solid"),d.borderColor&&(w.style.borderColor=d.borderColor),d.paddingX?(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),d.paddingY?(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),T&&v){let We=h("div","persona-send-button-tooltip");We.textContent=v,R.appendChild(We)}R.appendChild(w);let k=(Q=r==null?void 0:r.voiceRecognition)!=null?Q:{},P=k.enabled===!0,E=null,V=null,te=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Z=((se=k.provider)==null?void 0:se.type)==="runtype";if(P&&(te||Z)){V=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let We=(kt=k.iconName)!=null?kt:"mic",ge=(ct=k.iconSize)!=null?ct:C,ht=parseFloat(ge)||24,Oe=(Bt=k.backgroundColor)!=null?Bt:S,ae=(Xt=k.iconColor)!=null?Xt:M;E.style.width=ge,E.style.height=ge,E.style.minWidth=ge,E.style.minHeight=ge,E.style.fontSize="18px",E.style.lineHeight="1",ae?E.style.color=ae:E.style.color="var(--persona-text, #111827)";let Fe=fe(We,ht,ae||"currentColor",1.5);Fe?E.appendChild(Fe):E.textContent="\u{1F3A4}",Oe&&(E.style.backgroundColor=Oe),k.borderWidth&&(E.style.borderWidth=k.borderWidth,E.style.borderStyle="solid"),k.borderColor&&(E.style.borderColor=k.borderColor),k.paddingX&&(E.style.paddingLeft=k.paddingX,E.style.paddingRight=k.paddingX),k.paddingY&&(E.style.paddingTop=k.paddingY,E.style.paddingBottom=k.paddingY),V.appendChild(E);let wt=(_e=k.tooltipText)!=null?_e:"Start voice recognition";if(((de=k.showTooltip)!=null?de:!1)&&wt){let dt=h("div","persona-send-button-tooltip");dt.textContent=wt,V.appendChild(dt)}}let ee=(Ne=r==null?void 0:r.attachments)!=null?Ne:{},xe=ee.enabled===!0,ne=null,we=null,De=null,me=null;if(xe){me=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),me.style.display="none",De=h("input"),De.type="file",De.accept=((It=ee.allowedTypes)!=null?It:pr).join(","),De.multiple=((Pt=ee.maxFiles)!=null?Pt:4)>1,De.style.display="none",De.setAttribute("aria-label","Attach files"),we=h("div","persona-send-button-wrapper"),ne=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ne.type="button",ne.setAttribute("aria-label",(st=ee.buttonTooltipText)!=null?st:"Attach file");let We=(at=ee.buttonIconName)!=null?at:"paperclip",ge=C,ht=parseFloat(ge)||40,Oe=Math.round(ht*.6);ne.style.width=ge,ne.style.height=ge,ne.style.minWidth=ge,ne.style.minHeight=ge,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.style.backgroundColor="transparent",ne.style.color="var(--persona-primary, #111827)",ne.style.border="none",ne.style.borderRadius="6px",ne.style.transition="background-color 0.15s ease",ne.addEventListener("mouseenter",()=>{ne.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ne.addEventListener("mouseleave",()=>{ne.style.backgroundColor="transparent"});let ae=fe(We,Oe,"currentColor",1.5);ae?ne.appendChild(ae):ne.textContent="\u{1F4CE}",ne.addEventListener("click",wt=>{wt.preventDefault(),De==null||De.click()}),we.appendChild(ne);let ve=(tn=ee.buttonTooltipText)!=null?tn:"Attach file",Fe=h("div","persona-send-button-tooltip");Fe.textContent=ve,we.appendChild(Fe)}s.addEventListener("click",We=>{We.target!==w&&We.target!==R&&We.target!==E&&We.target!==V&&We.target!==ne&&We.target!==we&&o.focus()}),me&&(me.style.gap="8px",s.append(me)),De&&s.append(De),s.append(o);let ke=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Le=h("div","persona-flex persona-items-center persona-gap-2");we&&Le.append(we);let le=h("div","persona-flex persona-items-center persona-gap-1");V&&le.append(V),le.append(R),ke.append(Le,le),s.append(ke);let K=(en=r==null?void 0:r.statusIndicator)!=null?en:{},pe=K.align==="left"?"persona-text-left":K.align==="center"?"persona-text-center":"persona-text-right",G=h("div",`persona-mt-2 ${pe} persona-text-xs persona-text-persona-muted`);G.setAttribute("data-persona-composer-status","");let oe=(nn=K.visible)!=null?nn:!0;G.style.display=oe?"":"none";let ye=(z=K.idleText)!=null?z:"Online";if(K.idleLink){let We=h("a");We.href=K.idleLink,We.target="_blank",We.rel="noopener noreferrer",We.textContent=ye,We.style.color="inherit",We.style.textDecoration="none",G.appendChild(We)}else G.textContent=ye;return t.append(n,s,G),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:R,micButton:E,micButtonWrapper:V,statusText:G,attachmentButton:ne,attachmentButtonWrapper:we,attachmentInput:De,attachmentPreviewsContainer:me,actionsRow:ke,leftActions:Le,rightActions:le}};var Ed=e=>{var c,d,p,f,g,v,T,C,S;let r=(d=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?d:!0;if(Gt(e)){let M=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),R=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return M.appendChild(R),{wrapper:M,panel:R}}if(!r){let M=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),R=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?f:"100%";return M.style.width=w,R.style.width="100%",M.appendChild(R),{wrapper:M,panel:R}}let n=(g=e==null?void 0:e.launcher)!=null?g:{},s=n.position&&Yn[n.position]?Yn[n.position]:Yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((T=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?T:Cn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?S:e==null?void 0:e.launcherWidth,u=i!=null?i:Wn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},Td=(e,r=!0)=>{var C,S,M,R,w,k,P,E,V;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-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=n?po(e,n,{showClose:r}):ur({config:e,showClose:r}),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=Gt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(R=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?R:"Hello \u{1F44B}";let d=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");d.textContent=(k=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",u.append(c,d);let p=h("div","persona-flex persona-flex-col persona-gap-3"),f=(P=e==null?void 0:e.layout)==null?void 0:P.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,p);let v=uo({config:e}),T=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return s?Yr(t,o,e):(o.header.style.display="none",Yr(t,o,e)),t.append(a),T||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:p,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:d,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var uu=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},mu=320,gu=320,fu=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),hu=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${mu}px`,c.style.maxHeight=`${gu}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;s+=1,c.addEventListener("error",()=>{d||(d=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{d=!0}),uu(i.image)?(c.src=i.image,n.appendChild(c)):(d=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},Gr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="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 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="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},Aa=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Gr};if(r){let s=r(n);if(s!==null)return s}return Gr()},yu=(e,r)=>{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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Md=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},bu=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){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},Ea=(e,r,t)=>{var g,v,T,C,S,M;let n=(g=r.showCopy)!=null?g:!0,s=(v=r.showUpvote)!=null?v:!0,o=(T=r.showDownvote)!=null?T:!0;if(!n&&!s&&!o){let R=h("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(C=r.visibility)!=null?C:"hover",i=(S=r.align)!=null?S:"right",u=(M=r.layout)!=null?M:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],d={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${d} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(R,w,k)=>{let P=Lt({icon:R,label:w,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",k),P};return n&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},mo=(e,r,t,n,s,o)=>{var Z,O,ee,xe,ne,we,De;let a=t!=null?t:{},i=(Z=a.layout)!=null?Z:"bubble",u=a.avatar,c=a.timestamp,d=(O=u==null?void 0:u.show)!=null?O:!1,p=(ee=c==null?void 0:c.show)!=null?ee:!1,f=(xe=u==null?void 0:u.position)!=null?xe:"left",g=(ne=c==null?void 0:c.position)!=null?ne:"below",v=bu(e.role,i),T=h("div",v.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=fu(e),S=(De=(we=e.content)==null?void 0:we.trim())!=null?De:"",R=C.length>0&&S===As,w=document.createElement("div");w.classList.add("persona-message-content");let k=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),P=null;if(R?(P=document.createElement("div"),P.innerHTML=k,P.style.display="none",w.appendChild(P)):w.innerHTML=k,p&&g==="inline"&&e.createdAt){let me=Md(e,c);me.classList.add("persona-ml-2","persona-inline"),w.appendChild(me)}if(C.length>0){let me=hu(C,!R&&!!S,()=>{R&&P&&(P.style.display="")});me?T.appendChild(me):R&&P&&(P.style.display="")}if(T.appendChild(w),p&&g==="below"&&e.createdAt){let me=Md(e,c);me.classList.add("persona-mt-1"),T.appendChild(me)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let me=Aa("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);me&&T.appendChild(me)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let me=Ea(e,n,s);T.appendChild(me)}if(!d||e.role==="system")return T;let V=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),te=yu(u,e.role);return f==="right"||f==="left"&&e.role==="user"?V.append(T,te):V.append(te,T),T.classList.remove("persona-max-w-[85%]"),T.classList.add("persona-max-w-[calc(85%-2.5rem)]"),V},kd=(e,r,t,n,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}):mo(e,r,t,n,s,o)};var go=new Set,xu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),vu=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
16
- `):""},Ld=(e,r)=>{let t=go.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=fe(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Ta=(e,r)=>{var k,P,E,V,te,Z,O;let t=e.reasoning,n=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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let s=(P=(k=r==null?void 0:r.features)==null?void 0:k.reasoningDisplay)!=null?P:{},o=s.expandable!==!1,a=o&&go.has(e.id),i=t.status!=="complete",u=vu(e,(E=s.previewMaxLines)!=null?E:3),c=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");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(te=(V=r==null?void 0:r.reasoning)==null?void 0:V.renderCollapsedSummary)==null?void 0:te.call(V,{message:e,reasoning:t,defaultSummary:f,previewText:u,isActive:i,config:r!=null?r:{}});typeof g=="string"&&g.trim()?(p.textContent=g,d.appendChild(p)):g instanceof HTMLElement?d.appendChild(g):(p.textContent=f,d.appendChild(p));let v=h("span","persona-text-xs persona-text-persona-primary");v.textContent=Xc(t),d.appendChild(v),t.status==="complete"?p.style.display="none":p.style.display="";let T=null;if(o){T=h("div","persona-flex persona-items-center");let xe=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);xe?T.appendChild(xe):T.textContent=a?"Hide":"Show";let ne=h("div","persona-flex persona-items-center persona-ml-auto");ne.append(T),c.append(d,ne)}else c.append(d);let C=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(C.setAttribute("data-persona-collapsed-preview","reasoning"),C.style.display="none",C.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let ee=(O=(Z=r==null?void 0:r.reasoning)==null?void 0:Z.renderCollapsedPreview)==null?void 0:O.call(Z,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:r!=null?r:{}});xu(C,ee)||(C.textContent=u),C.style.display=""}if(!a&&i&&s.activeMinHeight&&(n.style.minHeight=s.activeMinHeight),!o)return n.append(c,C),n;let S=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");S.style.display=a?"":"none";let M=t.chunks.join(""),R=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return R.textContent=M||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),S.appendChild(R),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),T){T.innerHTML="";let xe=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);xe?T.appendChild(xe):T.textContent=a?"Hide":"Show"}S.style.display=a?"":"none",C.style.display=a?"none":C.textContent||C.childNodes.length?"":"none"})(),n.append(c,C,S),n};var fo=new Set,Cu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),wu=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
15
+ `,t.addEventListener("click",r);let n=o=>{var H,w,k,P,E,G,Q,K,O,ne,Ce,re,xe,We;let a=(H=o.launcher)!=null?H:{},i=Gt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let me=(w=a.title)!=null?w:"Chat Assistant";u.textContent=me,u.setAttribute("title",me)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let me=(k=a.subtitle)!=null?k:"Get answers fast";c.textContent=me,c.setAttribute("title",me)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let me=(P=a.agentIconSize)!=null?P:"40px";if(d.style.height=me,d.style.width=me,d.innerHTML="",a.agentIconName){let Me=parseFloat(me)||24,ke=ye(a.agentIconName,Me*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(d.appendChild(ke),d.style.display=""):(d.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(G=a.agentIconText)!=null?G:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let me=(Q=a.agentIconSize)!=null?Q:"40px";f.style.height=me,f.style.width=me,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let me=(K=a.callToActionIconSize)!=null?K:"32px";g.style.height=me,g.style.width=me,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Me=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Me=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let ke=parseFloat(me)||24,oe=Math.max(ke-Me,8),X=ye(a.callToActionIconName,oe,"currentColor",2);X?g.appendChild(X):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let v=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],T="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",C="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?C:`${T} ${v}`,i||(t.style.zIndex=String((Ce=a.zIndex)!=null?Ce:Cn));let S="1px solid var(--persona-border, #e5e7eb)",M="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=(re=a.border)!=null?re:S,t.style.boxShadow=(xe=a.shadow)!=null?xe:M,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=(We=a.collapsedMaxWidth)!=null?We:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var wn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ur=e=>{var K,O,ne,Ce,re,xe,We,me,Me,ke,oe,X,pe,V,te,ge,de,Re,Ze,z,W,se,$,U,ce,_e,ee,ie,kt,dt,Bt,Kt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(K=r==null?void 0:r.launcher)!=null?K:{},o=(O=s.headerIconSize)!=null?O:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Ce=s.closeButtonPlacement)!=null?Ce:"inline",u=(re=s.headerIconHidden)!=null?re:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let je=parseFloat(o)||24,ue=ye(c,je*.6,"currentColor",1);ue?p.replaceChildren(ue):p.textContent=(We=(xe=r==null?void 0:r.launcher)==null?void 0:xe.agentIconText)!=null?We:"\u{1F4AC}"}else if((me=r==null?void 0:r.launcher)!=null&&me.iconUrl){let je=h("img");je.src=r.launcher.iconUrl,je.alt="",je.className="persona-rounded-xl persona-object-cover",je.style.height=o,je.style.width=o,p.replaceChildren(je)}else p.textContent=(ke=(Me=r==null?void 0:r.launcher)==null?void 0:Me.agentIconText)!=null?ke:"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=wn.titleColor,f.textContent=(X=(oe=r==null?void 0:r.launcher)==null?void 0:oe.title)!=null?X:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=wn.subtitleColor,g.textContent=(V=(pe=r==null?void 0:r.launcher)==null?void 0:pe.subtitle)!=null?V:"Here to help you get answers fast",d.append(f,g),u?n.append(d):n.append(p,d);let v=(te=s.clearChat)!=null?te:{},T=(ge=v.enabled)!=null?ge:!0,C=(de=v.placement)!=null?de:"inline",S=null,M=null;if(T){let je=(Re=v.size)!=null?Re:"32px",ue=(Ze=v.iconName)!=null?Ze:"refresh-cw",Ne=(z=v.iconColor)!=null?z:"",It=(W=v.backgroundColor)!=null?W:"",Pt=(se=v.borderWidth)!=null?se:"",at=($=v.borderColor)!=null?$:"",it=(U=v.borderRadius)!=null?U:"",tn=(ce=v.paddingX)!=null?ce:"",en=(_e=v.paddingY)!=null?_e:"",nn=(ee=v.tooltipText)!=null?ee:"Clear chat",q=(ie=v.showTooltip)!=null?ie:!0;M=h("div",C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),C==="top-right"&&(M.style.right="48px"),S=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"),S.style.height=je,S.style.width=je,S.type="button",S.setAttribute("aria-label",nn),S.style.color=Ne||wn.actionIconColor;let He=ye(ue,"20px","currentColor",1);if(He&&S.appendChild(He),It&&(S.style.backgroundColor=It,S.classList.remove("hover:persona-bg-gray-100")),Pt||at){let he=Pt||"0px",ht=at||"transparent";S.style.border=`${he} solid ${ht}`,S.classList.remove("persona-border-none")}if(it&&(S.style.borderRadius=it,S.classList.remove("persona-rounded-full")),tn?(S.style.paddingLeft=tn,S.style.paddingRight=tn):(S.style.paddingLeft="",S.style.paddingRight=""),en?(S.style.paddingTop=en,S.style.paddingBottom=en):(S.style.paddingTop="",S.style.paddingBottom=""),M.appendChild(S),q&&nn&&S&&M){let he=null,ht=()=>{if(he||!S)return;let le=S.ownerDocument,we=le.body;if(!we)return;he=er(le,"div","persona-clear-chat-tooltip"),he.textContent=nn;let Oe=er(le,"div");Oe.className="persona-clear-chat-tooltip-arrow",he.appendChild(Oe);let wt=S.getBoundingClientRect();he.style.position="fixed",he.style.zIndex=String(Tr),he.style.left=`${wt.left+wt.width/2}px`,he.style.top=`${wt.top-8}px`,he.style.transform="translate(-50%, -100%)",we.appendChild(he)},$e=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};M.addEventListener("mouseenter",ht),M.addEventListener("mouseleave",$e),S.addEventListener("focus",ht),S.addEventListener("blur",$e),M._cleanupTooltip=()=>{$e(),M&&(M.removeEventListener("mouseenter",ht),M.removeEventListener("mouseleave",$e)),S&&(S.removeEventListener("focus",ht),S.removeEventListener("blur",$e))}}C==="inline"&&n.appendChild(M)}let H=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":T&&C==="inline"?"":"persona-ml-auto"),w=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");w.style.height=a,w.style.width=a,w.type="button";let k=(kt=s.closeButtonTooltipText)!=null?kt:"Close chat",P=(dt=s.closeButtonShowTooltip)!=null?dt:!0;w.setAttribute("aria-label",k),w.style.display=t?"":"none";let E=(Bt=s.closeButtonIconName)!=null?Bt:"x",G=(Kt=s.closeButtonIconText)!=null?Kt:"\xD7";w.style.color=s.closeButtonColor||wn.actionIconColor;let Q=ye(E,"20px","currentColor",1);if(Q?w.appendChild(Q):w.textContent=G,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let je=s.closeButtonBorderWidth||"0px",ue=s.closeButtonBorderColor||"transparent";w.style.border=`${je} solid ${ue}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),H.appendChild(w),P&&k){let je=null,ue=()=>{if(je)return;let It=w.ownerDocument,Pt=It.body;if(!Pt)return;je=er(It,"div","persona-clear-chat-tooltip"),je.textContent=k;let at=er(It,"div");at.className="persona-clear-chat-tooltip-arrow",je.appendChild(at);let it=w.getBoundingClientRect();je.style.position="fixed",je.style.zIndex=String(Tr),je.style.left=`${it.left+it.width/2}px`,je.style.top=`${it.top-8}px`,je.style.transform="translate(-50%, -100%)",Pt.appendChild(je)},Ne=()=>{je&&je.parentNode&&(je.parentNode.removeChild(je),je=null)};H.addEventListener("mouseenter",ue),H.addEventListener("mouseleave",Ne),w.addEventListener("focus",ue),w.addEventListener("blur",Ne),H._cleanupTooltip=()=>{Ne(),H.removeEventListener("mouseenter",ue),H.removeEventListener("mouseleave",Ne),w.removeEventListener("focus",ue),w.removeEventListener("blur",Ne)}}return i!=="top-right"&&n.appendChild(H),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:g,closeButton:w,closeButtonWrapper:H,clearChatButton:S,clearChatButtonWrapper:M}},Yr=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function kr(e){let{items:r,onSelect:t,anchor:n,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(Tr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of r){if(g.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let C=ye(g.icon,16,"currentColor",1.5);C&&v.appendChild(C)}let T=document.createElement("span");T.textContent=g.label,v.appendChild(T),v.addEventListener("click",C=>{C.stopPropagation(),p(),t(g.id)}),a.appendChild(v)}let i=null;function u(){if(!o)return;let g=n.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!n.contains(v.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function d(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:d,destroy:f}}function Lt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=ye(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[p,d]of Object.entries(i))u.setAttribute(p,d);return u}function Yo(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=ye(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let d=h("span");if(d.textContent=t,p.appendChild(d),i&&p.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))p.setAttribute(f,g);return p}function Go(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let d;p.icon?d=Lt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,u(),n(p.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",p.label),d.title=p.label,d.textContent=p.label,d.addEventListener("click",()=>{a=p.id,u(),n(p.id)})),d.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:d}),o.appendChild(d)}function c(p){a=p,u()}return{element:o,setSelected:c}}function js(e){var g,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let d=ye(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(v=u.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var T,C;c.style.backgroundColor=(T=u.background)!=null?T:"",c.style.borderColor=(C=u.border)!=null?C:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=kr({items:n,onSelect:T=>{c.setAttribute("aria-expanded","false"),s(T)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",T=>{T.stopPropagation();let C=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",C?"false":"true"),f.toggle()}),c.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),c.click())}),{element:c,setLabel:T=>{p.textContent=T,c.setAttribute("aria-label",T)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Sa=e=>{var n;let r=ur({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.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 r};function uu(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){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=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=ye(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=kr({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Aa=e=>{var M,H,w,k,P,E,G,Q,K;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},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 u=s==null?void 0:s.titleMenu,c,p;if(u)c=js({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=wn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=wn.titleColor,p.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(p),uu(c,s==null?void 0:s.trailingActions,(P=s==null?void 0:s.onAction)!=null?P:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Ce=>{Ce.target.closest("button")||ne()}),c.addEventListener("keydown",Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),ne())})}let O=s==null?void 0:s.titleRowHover;O&&(c.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",c.style.padding=(G=O.padding)!=null?G:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ne,Ce;c.style.backgroundColor=(ne=O.background)!=null?ne:"",c.style.borderColor=(Ce=O.border)!=null?Ce:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(Q=a.closeButtonSize)!=null?Q:"32px",f=h("div",""),g=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");g.style.height=d,g.style.width=d,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||wn.actionIconColor;let v=(K=a.closeButtonIconName)!=null?K:"x",T=ye(v,"20px","currentColor",2);T?g.appendChild(T):g.textContent="\xD7",n&&g.addEventListener("click",n),f.appendChild(g),i.appendChild(f);let C=h("div");C.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},zs={default:Sa,minimal:Aa},Ea=e=>{var r;return(r=zs[e])!=null?r:zs.default},po=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let d=h("span"),f=h("span"),g=h("button");g.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:p,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Ea(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var uo=e=>{var de,Re,Ze,z,W,se,$,U,ce,_e,ee,ie,kt,dt,Bt,Kt,je,ue,Ne,It,Pt,at,it,tn,en,nn,q;let{config:r}=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 n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),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 o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(Re=(de=r==null?void 0:r.copy)==null?void 0:de.inputPlaceholder)!=null?Re:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let He=Math.min(o.scrollHeight,u);o.style.height=`${He}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(Ze=r==null?void 0:r.sendButton)!=null?Ze:{},d=(z=p.useIcon)!=null?z:!1,f=(W=p.iconText)!=null?W:"\u2191",g=p.iconName,v=(se=p.tooltipText)!=null?se:"Send message",T=($=p.showTooltip)!=null?$:!1,C=(U=p.size)!=null?U:"40px",S=p.backgroundColor,M=p.textColor,H=h("div","persona-send-button-wrapper"),w=h("button",d?"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");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),d){if(w.style.width=C,w.style.height=C,w.style.minWidth=C,w.style.minHeight=C,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",M?w.style.color=M:w.style.color="var(--persona-button-primary-fg, #ffffff)",g){let He=parseFloat(C)||24,he=(M==null?void 0:M.trim())||"currentColor",ht=ye(g,He,he,2);ht?w.appendChild(ht):w.textContent=f}else w.textContent=f;S?w.style.backgroundColor=S:w.classList.add("persona-bg-persona-primary")}else w.textContent=(_e=(ce=r==null?void 0:r.copy)==null?void 0:ce.sendButtonLabel)!=null?_e:"Send",M?w.style.color=M:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),T&&v){let He=h("div","persona-send-button-tooltip");He.textContent=v,H.appendChild(He)}H.appendChild(w);let k=(ee=r==null?void 0:r.voiceRecognition)!=null?ee:{},P=k.enabled===!0,E=null,G=null,Q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),K=((ie=k.provider)==null?void 0:ie.type)==="runtype";if(P&&(Q||K)){G=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let He=(kt=k.iconName)!=null?kt:"mic",he=(dt=k.iconSize)!=null?dt:C,ht=parseFloat(he)||24,$e=(Bt=k.backgroundColor)!=null?Bt:S,le=(Kt=k.iconColor)!=null?Kt:M;E.style.width=he,E.style.height=he,E.style.minWidth=he,E.style.minHeight=he,E.style.fontSize="18px",E.style.lineHeight="1",le?E.style.color=le:E.style.color="var(--persona-text, #111827)";let Oe=ye(He,ht,le||"currentColor",1.5);Oe?E.appendChild(Oe):E.textContent="\u{1F3A4}",$e&&(E.style.backgroundColor=$e),k.borderWidth&&(E.style.borderWidth=k.borderWidth,E.style.borderStyle="solid"),k.borderColor&&(E.style.borderColor=k.borderColor),k.paddingX&&(E.style.paddingLeft=k.paddingX,E.style.paddingRight=k.paddingX),k.paddingY&&(E.style.paddingTop=k.paddingY,E.style.paddingBottom=k.paddingY),G.appendChild(E);let wt=(je=k.tooltipText)!=null?je:"Start voice recognition";if(((ue=k.showTooltip)!=null?ue:!1)&&wt){let pt=h("div","persona-send-button-tooltip");pt.textContent=wt,G.appendChild(pt)}}let ne=(Ne=r==null?void 0:r.attachments)!=null?Ne:{},Ce=ne.enabled===!0,re=null,xe=null,We=null,me=null;if(Ce){me=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),me.style.display="none",We=h("input"),We.type="file",We.accept=((It=ne.allowedTypes)!=null?It:pr).join(","),We.multiple=((Pt=ne.maxFiles)!=null?Pt:4)>1,We.style.display="none",We.setAttribute("aria-label","Attach files"),xe=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(at=ne.buttonTooltipText)!=null?at:"Attach file");let He=(it=ne.buttonIconName)!=null?it:"paperclip",he=C,ht=parseFloat(he)||40,$e=Math.round(ht*.6);re.style.width=he,re.style.height=he,re.style.minWidth=he,re.style.minHeight=he,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let le=ye(He,$e,"currentColor",1.5);le?re.appendChild(le):re.textContent="\u{1F4CE}",re.addEventListener("click",wt=>{wt.preventDefault(),We==null||We.click()}),xe.appendChild(re);let we=(tn=ne.buttonTooltipText)!=null?tn:"Attach file",Oe=h("div","persona-send-button-tooltip");Oe.textContent=we,xe.appendChild(Oe)}s.addEventListener("click",He=>{He.target!==w&&He.target!==H&&He.target!==E&&He.target!==G&&He.target!==re&&He.target!==xe&&o.focus()}),me&&(me.style.gap="8px",s.append(me)),We&&s.append(We),s.append(o);let Me=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),ke=h("div","persona-flex persona-items-center persona-gap-2");xe&&ke.append(xe);let oe=h("div","persona-flex persona-items-center persona-gap-1");G&&oe.append(G),oe.append(H),Me.append(ke,oe),s.append(Me);let X=(en=r==null?void 0:r.statusIndicator)!=null?en:{},pe=X.align==="left"?"persona-text-left":X.align==="center"?"persona-text-center":"persona-text-right",V=h("div",`persona-mt-2 ${pe} persona-text-xs persona-text-persona-muted`);V.setAttribute("data-persona-composer-status","");let te=(nn=X.visible)!=null?nn:!0;V.style.display=te?"":"none";let ge=(q=X.idleText)!=null?q:"Online";if(X.idleLink){let He=h("a");He.href=X.idleLink,He.target="_blank",He.rel="noopener noreferrer",He.textContent=ge,He.style.color="inherit",He.style.textDecoration="none",V.appendChild(He)}else V.textContent=ge;return t.append(n,s,V),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:H,micButton:E,micButtonWrapper:G,statusText:V,attachmentButton:re,attachmentButtonWrapper:xe,attachmentInput:We,attachmentPreviewsContainer:me,actionsRow:Me,leftActions:ke,rightActions:oe}};var Td=e=>{var c,p,d,f,g,v,T,C,S;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Gt(e)){let M=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return M.appendChild(H),{wrapper:M,panel:H}}if(!r){let M=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),H=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return M.style.width=w,H.style.width="100%",M.appendChild(H),{wrapper:M,panel:H}}let n=(g=e==null?void 0:e.launcher)!=null?g:{},s=n.position&&Yn[n.position]?Yn[n.position]:Yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((T=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?T:Cn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?S:e==null?void 0:e.launcherWidth,u=i!=null?i:Wn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},Md=(e,r=!0)=>{var C,S,M,H,w,k,P,E,G;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-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=n?po(e,n,{showClose:r}):ur({config:e,showClose:r}),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=Gt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(H=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?H:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(k=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",u.append(c,p);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(P=e==null?void 0:e.layout)==null?void 0:P.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,d);let v=uo({config:e}),T=((G=e==null?void 0:e.layout)==null?void 0:G.showFooter)!==!1;return s?Yr(t,o,e):(o.header.style.display="none",Yr(t,o,e)),t.append(a),T||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:d,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:p,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:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var mu=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},gu=320,fu=320,hu=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),yu=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${gu}px`,c.style.maxHeight=`${fu}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),mu(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},Gr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="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 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="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},Ta=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Gr};if(r){let s=r(n);if(s!==null)return s}return Gr()},bu=(e,r)=>{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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},kd=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},xu=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){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},Ma=(e,r,t)=>{var g,v,T,C,S,M;let n=(g=r.showCopy)!=null?g:!0,s=(v=r.showUpvote)!=null?v:!0,o=(T=r.showDownvote)!=null?T:!0;if(!n&&!s&&!o){let H=h("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(C=r.visibility)!=null?C:"hover",i=(S=r.align)!=null?S:"right",u=(M=r.layout)!=null?M:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(H,w,k)=>{let P=Lt({icon:H,label:w,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",k),P};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},mo=(e,r,t,n,s,o)=>{var K,O,ne,Ce,re,xe,We;let a=t!=null?t:{},i=(K=a.layout)!=null?K:"bubble",u=a.avatar,c=a.timestamp,p=(O=u==null?void 0:u.show)!=null?O:!1,d=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Ce=u==null?void 0:u.position)!=null?Ce:"left",g=(re=c==null?void 0:c.position)!=null?re:"below",v=xu(e.role,i),T=h("div",v.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=hu(e),S=(We=(xe=e.content)==null?void 0:xe.trim())!=null?We:"",H=C.length>0&&S===Ms,w=document.createElement("div");w.classList.add("persona-message-content");let k=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),P=null;if(H?(P=document.createElement("div"),P.innerHTML=k,P.style.display="none",w.appendChild(P)):w.innerHTML=k,d&&g==="inline"&&e.createdAt){let me=kd(e,c);me.classList.add("persona-ml-2","persona-inline"),w.appendChild(me)}if(C.length>0){let me=yu(C,!H&&!!S,()=>{H&&P&&(P.style.display="")});me?T.appendChild(me):H&&P&&(P.style.display="")}if(T.appendChild(w),d&&g==="below"&&e.createdAt){let me=kd(e,c);me.classList.add("persona-mt-1"),T.appendChild(me)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let me=Ta("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);me&&T.appendChild(me)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let me=Ma(e,n,s);T.appendChild(me)}if(!p||e.role==="system")return T;let G=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Q=bu(u,e.role);return f==="right"||f==="left"&&e.role==="user"?G.append(T,Q):G.append(Q,T),T.classList.remove("persona-max-w-[85%]"),T.classList.add("persona-max-w-[calc(85%-2.5rem)]"),G},Ld=(e,r,t,n,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}):mo(e,r,t,n,s,o)};var go=new Set,vu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Cu=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
16
+ `):""},Id=(e,r)=>{let t=go.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},ka=(e,r)=>{var xe,We,me,Me,ke,oe,X,pe,V,te,ge;let t=e.reasoning,n=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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let s=(We=(xe=r==null?void 0:r.features)==null?void 0:xe.reasoningDisplay)!=null?We:{},o=s.expandable!==!1,a=o&&go.has(e.id),i=t.status!=="complete",u=Cu(e,(me=s.previewMaxLines)!=null?me:3),c=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");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Me=r==null?void 0:r.reasoning)!=null?Me:{},v=String((ke=t.startedAt)!=null?ke:Date.now()),T=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",v),de.textContent=Cs(t),de},C=(oe=g.renderCollapsedSummary)==null?void 0:oe.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:u,isActive:i,config:r!=null?r:{},elapsed:Cs(t),createElapsedElement:T});typeof C=="string"&&C.trim()?(d.textContent=C,p.appendChild(d)):C instanceof HTMLElement?p.appendChild(C):(d.textContent=f,p.appendChild(d));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=Zc(t),p.appendChild(S);let M=(X=s.loadingAnimation)!=null?X:"none",H=g.activeTextTemplate,w=g.completeTextTemplate,k=i?H:w,P=C instanceof HTMLElement,E=(de,Re,Ze)=>{let z=Ze;for(let W of Re){let se=h("span","persona-tool-char");se.style.setProperty("--char-index",String(z)),se.textContent=W===" "?"\xA0":W,de.appendChild(se),z++}return z},G=(de,Re)=>{d.textContent="";let Ze=ws(de,""),z=0;for(let W of Ze){let se=W.styles.length>0?(()=>{let $=h("span",W.styles.map(U=>`persona-tool-text-${U}`).join(" "));return d.appendChild($),$})():d;if(W.isDuration&&i)se.appendChild(T());else{let $=W.isDuration?Cs(t):W.text;Re?z=E(se,$,z):se.appendChild(document.createTextNode($))}}};if(!P&&k)if(S.style.display="none",d.style.display="",i&&M!=="none"){let de=(pe=g.loadingAnimationDuration)!=null?pe:2e3;d.setAttribute("data-preserve-animation","true"),M==="pulse"?(d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${de}ms`),G(k,!1)):(d.classList.add(`persona-tool-loading-${M}`),d.style.setProperty("--persona-tool-anim-duration",`${de}ms`),M==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),G(k,!0))}else G(k,!1);else if(!P&&i&&M!=="none"){d.style.display="";let de=(V=g.loadingAnimationDuration)!=null?V:2e3;if(d.setAttribute("data-preserve-animation","true"),M==="pulse")d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{d.classList.add(`persona-tool-loading-${M}`),d.style.setProperty("--persona-tool-anim-duration",`${de}ms`),M==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Re=d.textContent||f;d.textContent="",E(d,Re,0)}t.status==="complete"&&(d.style.display="none")}else P||(t.status==="complete"?d.style.display="none":d.style.display="");let Q=null;if(o){Q=h("div","persona-flex persona-items-center");let Re=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?Q.appendChild(Re):Q.textContent=a?"Hide":"Show";let Ze=h("div","persona-flex persona-items-center persona-ml-auto");Ze.append(Q),c.append(p,Ze)}else c.append(p);let K=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(K.setAttribute("data-persona-collapsed-preview","reasoning"),K.style.display="none",K.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let de=(ge=(te=r==null?void 0:r.reasoning)==null?void 0:te.renderCollapsedPreview)==null?void 0:ge.call(te,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:r!=null?r:{}});vu(K,de)||(K.textContent=u),K.style.display=""}if(!a&&i&&s.activeMinHeight&&(n.style.minHeight=s.activeMinHeight),!o)return n.append(c,K),n;let O=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let ne=t.chunks.join(""),Ce=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Ce.textContent=ne||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Ce),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),Q){Q.innerHTML="";let Re=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?Q.appendChild(Re):Q.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",K.style.display=a?"none":K.textContent||K.childNodes.length?"":"none"})(),n.append(c,K,O),n};var fo=new Set,wu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Su=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
17
17
  `);let s=ao(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
18
- `):""},Su=(e,r)=>{var d,p,f,g,v;let t=e.toolCall,n=(d=r==null?void 0:r.features)==null?void 0:d.toolCallDisplay,s=(p=n==null?void 0:n.collapsedMode)!=null?p:"tool-call",o=wu(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=t?Kc(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=r==null?void 0:r.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=pa(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=pa(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Id=(e,r,t)=>{var d;let n=fo.has(e),s=(d=t==null?void 0:t.toolCall)!=null?d:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=fe(n?"chevron-up":"chevron-down",16,p,2);f?c.appendChild(f):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Ma=(e,r)=>{var ee,xe,ne,we,De,me,ke,Le,le;let t=e.toolCall,n=(ee=r==null?void 0:r.toolCall)!=null?ee:{},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),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=(ne=(xe=r==null?void 0:r.features)==null?void 0:xe.toolCallDisplay)!=null?ne:{},a=o.expandable!==!1,i=a&&fo.has(e.id),{summary:u,previewText:c,isActive:d}=Su(e,r),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"),n.headerBackgroundColor&&(p.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(p.style.paddingLeft=n.headerPaddingX,p.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(p.style.paddingTop=n.headerPaddingY,p.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(g.style.color=n.headerTextColor);let v=String((we=t.startedAt)!=null?we:Date.now()),T=()=>{let K=h("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Do(t),K},C=(me=n.renderCollapsedSummary)==null?void 0:me.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(De=o.collapsedMode)!=null?De:"tool-call",isActive:d,config:r!=null?r:{},elapsed:Do(t),createElapsedElement:T});typeof C=="string"&&C.trim()?(g.textContent=C,f.appendChild(g)):C instanceof HTMLElement?f.appendChild(C):(g.textContent=u,f.appendChild(g));let S=(ke=o.loadingAnimation)!=null?ke:"none",M=n.activeTextTemplate,R=n.completeTextTemplate,w=d?M:R,k=C instanceof HTMLElement,P=(K,pe,G)=>{let oe=G;for(let ye of pe){let Ie=h("span","persona-tool-char");Ie.style.setProperty("--char-index",String(oe)),Ie.textContent=ye===" "?"\xA0":ye,K.appendChild(Ie),oe++}return oe},E=(K,pe)=>{var Ie;g.textContent="";let G=((Ie=t.name)==null?void 0:Ie.trim())||"tool",oe=Zc(K,G),ye=0;for(let Xe of oe){let ft=Xe.styles.length>0?(()=>{let q=h("span",Xe.styles.map(D=>`persona-tool-text-${D}`).join(" "));return g.appendChild(q),q})():g;if(Xe.isDuration&&d)ft.appendChild(T());else{let q=Xe.isDuration?Do(t):Xe.text;pe?ye=P(ft,q,ye):ft.appendChild(document.createTextNode(q))}}};if(!k)if(d&&S!=="none"){let K=(Le=n.loadingAnimationDuration)!=null?Le:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),w&&E(w,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="shimmer-color"&&(n.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),w)E(w,!0);else{let pe=g.textContent||u;g.textContent="",P(g,pe,0)}}else w&&E(w,!1);let V=null;if(a){V=h("div","persona-flex persona-items-center");let K=n.toggleTextColor||n.headerTextColor||"currentColor",pe=fe(i?"chevron-up":"chevron-down",16,K,2);pe?V.appendChild(pe):V.textContent=i?"Hide":"Show";let G=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");G.append(V),p.append(f,G)}else p.append(f);let te=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(te.setAttribute("data-persona-collapsed-preview","tool"),te.style.display="none",te.style.whiteSpace="pre-wrap",!i&&d&&o.activePreview&&c){let K=(le=n.renderCollapsedPreview)==null?void 0:le.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:d,config:r!=null?r:{}});Cu(te,K)||(te.textContent=c),te.style.display=""}if(!i&&d&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,te),s;let Z=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(Z.style.display=i?"":"none",n.contentBackgroundColor&&(Z.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(Z.style.color=n.contentTextColor),n.contentPaddingX&&(Z.style.paddingLeft=n.contentPaddingX,Z.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(Z.style.paddingTop=n.contentPaddingY,Z.style.paddingBottom=n.contentPaddingY),t.name){let K=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?K.style.color=n.contentTextColor:n.headerTextColor&&(K.style.color=n.headerTextColor),K.textContent=t.name,Z.appendChild(K)}if(t.args!==void 0){let K=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(pe.style.color=n.labelTextColor),pe.textContent="Arguments";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(G.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(G.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(G.style.color=n.codeBlockTextColor),G.textContent=ao(t.args),K.append(pe,G),Z.appendChild(K)}if(t.chunks&&t.chunks.length){let K=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(pe.style.color=n.labelTextColor),pe.textContent="Activity";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(G.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(G.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(G.style.color=n.codeBlockTextColor),G.textContent=t.chunks.join(""),K.append(pe,G),Z.appendChild(K)}if(t.status==="complete"&&t.result!==void 0){let K=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(pe.style.color=n.labelTextColor),pe.textContent="Result";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(G.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(G.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(G.style.color=n.codeBlockTextColor),G.textContent=ao(t.result),K.append(pe,G),Z.appendChild(K)}if(t.status==="complete"&&typeof t.duration=="number"){let K=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(K.style.color=n.contentTextColor),K.textContent=`Duration: ${t.duration}ms`,Z.appendChild(K)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),V){V.innerHTML="";let K=n.toggleTextColor||n.headerTextColor||"currentColor",pe=fe(i?"chevron-up":"chevron-down",16,K,2);pe?V.appendChild(pe):V.textContent=i?"Hide":"Show"}Z.style.display=i?"":"none",te.style.display=i?"none":te.textContent||te.childNodes.length?"":"none"})(),s.append(p,te,Z),s};var ka=(e,r)=>{var T,C,S,M,R,w,k,P,E,V,te,Z;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.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=(T=n==null?void 0:n.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=n==null?void 0:n.borderColor)!=null?C:"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 u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=n==null?void 0:n.titleColor)!=null?S:"currentColor",d=fe(u,20,c,2);d&&i.appendChild(d);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(g.style.color=n.titleColor),g.textContent=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(g),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}p.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,p.appendChild(v),t.parameters){let O=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=ao(t.parameters),p.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let ee=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");ee.type="button",ee.style.backgroundColor=(R=n==null?void 0:n.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",ee.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",ee.setAttribute("data-approval-action","approve");let xe=fe("shield-check",14,(k=n==null?void 0:n.approveButtonTextColor)!=null?k:"#ffffff",2);xe&&(xe.style.marginRight="4px",ee.appendChild(xe));let ne=document.createTextNode((P=n==null?void 0:n.approveLabel)!=null?P:"Approve");ee.appendChild(ne);let we=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");we.type="button",we.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",we.style.color=(V=n==null?void 0:n.denyButtonTextColor)!=null?V:"var(--persona-feedback-error, #dc2626)",we.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,we.setAttribute("data-approval-action","deny");let De=fe("shield-x",14,(te=n==null?void 0:n.denyButtonTextColor)!=null?te:"var(--persona-feedback-error, #dc2626)",2);De&&(De.style.marginRight="4px",we.appendChild(De));let me=document.createTextNode((Z=n==null?void 0:n.denyLabel)!=null?Z:"Deny");we.appendChild(me),O.append(ee,we),p.appendChild(O)}return a.append(i,p),o.appendChild(a),o};var Pd=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let d=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=g=>{switch(g){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'}};n.forEach(g=>{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=g,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(g))}),d.appendChild(v),r.push(v)}),e.appendChild(d)}}};var Xo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ko=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function ho(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Au={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)"}},Eu={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Tu=["flowName","stepName","reasoningText","text","name","tool","toolName"],Mu=100;function ku(e,r){let t={...Au,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Eu}function Lu(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Iu(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function Pu(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.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 Wu(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Ru(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function Hu(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function La(e,r,t,n,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ho(c,(f=n.classNames)==null?void 0:f.eventRow);let d=a.find(g=>g.renderEventStreamRow);if(d!=null&&d.renderEventStreamRow&&i){let g=d.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(p()),c;function p(){var ee,xe;let g=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 T=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=fe(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&T.appendChild(C);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(ee=n.timestampFormat)!=null?ee:"relative";S.textContent=M==="relative"?Lu(e.timestamp,t):Iu(e.timestamp);let R=null;n.showSequenceNumbers!==!1&&(R=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(r+1));let w=ku(e.type,n.badgeColors),k=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");k.style.backgroundColor=w.bg,k.style.color=w.text,k.style.borderColor=w.text+"50",k.textContent=e.type;let P=(xe=n.descriptionFields)!=null?xe:Tu,E=Pu(e.payload,P),V=null;E&&(V=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),V.textContent=E);let te=h("div","persona-flex-1 persona-min-w-0"),Z=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=fe("clipboard","12px","currentColor",1.5);return O&&Z.appendChild(O),Z.addEventListener("click",async ne=>{ne.stopPropagation(),await Wu(Ru(e)),Z.innerHTML="";let we=fe("check","12px","currentColor",1.5);we&&Z.appendChild(we),setTimeout(()=>{Z.innerHTML="";let De=fe("clipboard","12px","currentColor",1.5);De&&Z.appendChild(De)},1500)}),v.appendChild(T),v.appendChild(S),R&&v.appendChild(R),v.appendChild(k),V&&v.appendChild(V),v.appendChild(te),v.appendChild(Z),g.appendChild(v),u&&g.appendChild(Hu(e,a,i)),g}}function Wd(e){var g,v,T,C,S;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(T=a==null?void 0:a.label)!=null?T:"",d=(S=(C=s==null?void 0:s.features)==null?void 0:C.eventStream)!=null?S:{},p=o.find(M=>M.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let M=p.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return f();function f(){let M=d.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ho(R,M==null?void 0:M.panel);let w=[],k="",P="",E=null,V=[],te={},Z=0,O=Bs(),ee=0,xe=0,ne=!1,we=null,De=!1,me=0,ke=new Set,Le=new Map,le="",K="",pe=null,G,oe,ye,Ie,Xe;function ft(){let ae=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ve=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");ho(ve,M==null?void 0:M.headerBar);let Fe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Fe.textContent="Events",G=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),G.textContent="0";let wt=h("div","persona-flex-1");oe=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 jt=h("option","");jt.value="",jt.textContent="All events",oe.appendChild(jt),ye=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"),ye.type="button",ye.title="Copy All";let zt=fe("clipboard-copy","12px","currentColor",1.5);zt&&ye.appendChild(zt);let yt=h("span","persona-text-xs");yt.textContent="Copy All",ye.appendChild(yt),ve.appendChild(Fe),ve.appendChild(G),ve.appendChild(wt),ve.appendChild(oe),ve.appendChild(ye);let Ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ho(Ze,M==null?void 0:M.searchBar);let bt=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),He=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&&He.appendChild(bt),Ie=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"),ho(Ie,M==null?void 0:M.searchInput),Ie.type="text",Ie.placeholder="Search event payloads...",Xe=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"),Xe.type="button",Xe.style.display="none";let qt=fe("x","12px","currentColor",2);return qt&&Xe.appendChild(qt),Ze.appendChild(He),Ze.appendChild(Ie),Ze.appendChild(Xe),ae.appendChild(ve),ae.appendChild(Ze),ae}let q,D=o.find(ae=>ae.renderEventStreamToolbar);if(D!=null&&D.renderEventStreamToolbar&&s){let ae=D.renderEventStreamToolbar({config:s,defaultRenderer:()=>ft(),eventCount:r.getSize(),filteredCount:0,onFilterChange:ve=>{k=ve,Xt(),Ne()},onSearchChange:ve=>{P=ve,Xt(),Ne()}});q=ae!=null?ae:ft()}else q=ft();let ce=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");ce.style.display="none";let j=h("div","persona-flex-1 persona-min-h-0 persona-relative"),J=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ie=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");ho(ie,M==null?void 0:M.scrollIndicator),ie.style.display="none",ie.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let $e=fe(u,"14px","currentColor",2);$e&&ie.appendChild($e);let Q=h("span","");Q.textContent=c,ie.appendChild(Q);let se=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");se.style.display="none",j.appendChild(J),j.appendChild(se),j.appendChild(ie),R.setAttribute("tabindex","0"),R.appendChild(q),R.appendChild(ce),R.appendChild(j);function kt(){let ae=r.getAll(),ve={};for(let yt of ae)ve[yt.type]=(ve[yt.type]||0)+1;let Fe=Object.keys(ve).sort(),wt=Fe.length!==V.length||!Fe.every((yt,Ze)=>yt===V[Ze]),jt=!wt&&Fe.some(yt=>ve[yt]!==te[yt]),dt=ae.length!==Object.values(te).reduce((yt,Ze)=>yt+Ze,0);if(!wt&&!jt&&!dt||(V=Fe,te=ve,!oe))return;let zt=oe.value;if(oe.options[0].textContent="All events",wt){for(;oe.options.length>1;)oe.remove(1);for(let yt of Fe){let Ze=h("option","");Ze.value=yt,Ze.textContent=`${yt} (${ve[yt]||0})`,oe.appendChild(Ze)}zt&&Fe.includes(zt)?oe.value=zt:zt&&(oe.value="",k="")}else for(let yt=1;yt<oe.options.length;yt++){let Ze=oe.options[yt];Ze.textContent=`${Ze.value} (${ve[Ze.value]||0})`}}function ct(){let ae=r.getAll();if(k&&(ae=ae.filter(ve=>ve.type===k)),P){let ve=P.toLowerCase();ae=ae.filter(Fe=>Fe.type.toLowerCase().includes(ve)||Fe.payload.toLowerCase().includes(ve))}return ae}function Bt(){return k!==""||P!==""}function Xt(){Z=0,ee=0,O.resume(),ie.style.display="none"}function _e(ae){ke.has(ae)?ke.delete(ae):ke.add(ae),pe=ae;let ve=J.scrollTop,Fe=O.isFollowing();De=!0,O.pause(),Ne(),J.scrollTop=ve,Fe&&O.resume(),De=!1}function de(){return Uo(J,50)}function Ne(){xe=Date.now(),ne=!1,kt();let ae=r.getEvictedCount();ae>0?(ce.textContent=`${ae.toLocaleString()} older events truncated`,ce.style.display=""):ce.style.display="none",w=ct();let ve=w.length,Fe=r.getSize()>0;G&&(G.textContent=String(r.getSize())),ve===0&&Fe&&Bt()?(se.textContent=P?`No events matching '${P}'`:"No events matching filter",se.style.display="",J.style.display="none"):(se.style.display="none",J.style.display=""),ye&&(ye.title=Bt()?`Copy Filtered (${ve})`:"Copy All"),i&&!O.isFollowing()&&ve>Z&&(ee+=ve-Z,Q.textContent=c?`${c}${ee>0?` (${ee})`:""}`:"",ie.style.display=""),Z=ve;let wt=r.getAll(),jt=wt.length>0?wt[0].timestamp:0,dt=new Set(w.map(Ze=>Ze.id));for(let Ze of ke)dt.has(Ze)||ke.delete(Ze);let zt=k!==le||P!==K,yt=Le.size===0&&w.length>0;if(zt||yt||w.length===0){J.innerHTML="",Le.clear();let Ze=document.createDocumentFragment();for(let bt=0;bt<w.length;bt++){let He=La(w[bt],bt,jt,d,ke,_e,o,s);Le.set(w[bt].id,He),Ze.appendChild(He)}J.appendChild(Ze),le=k,K=P,pe=null}else{if(pe!==null){let bt=Le.get(pe);if(bt&&bt.parentNode===J){let He=w.findIndex(qt=>qt.id===pe);if(He>=0){let qt=La(w[He],He,jt,d,ke,_e,o,s);J.insertBefore(qt,bt),bt.remove(),Le.set(pe,qt)}}pe=null}let Ze=new Set(w.map(bt=>bt.id));for(let[bt,He]of Le)Ze.has(bt)||(He.remove(),Le.delete(bt));for(let bt=0;bt<w.length;bt++){let He=w[bt];if(!Le.has(He.id)){let qt=La(He,bt,jt,d,ke,_e,o,s);Le.set(He.id,qt),J.appendChild(qt)}}}O.isFollowing()&&(J.scrollTop=J.scrollHeight)}function It(){if(Date.now()-xe>=Mu){we!==null&&(cancelAnimationFrame(we),we=null),Ne();return}ne||(ne=!0,we=requestAnimationFrame(()=>{we=null,Ne()}))}let Pt=(ae,ve)=>{if(!ye)return;ye.innerHTML="";let Fe=fe(ae,"12px","currentColor",1.5);Fe&&ye.appendChild(Fe);let wt=h("span","persona-text-xs");wt.textContent="Copy All",ye.appendChild(wt),setTimeout(()=>{ye.innerHTML="";let jt=fe("clipboard-copy","12px","currentColor",1.5);jt&&ye.appendChild(jt);let dt=h("span","persona-text-xs");dt.textContent="Copy All",ye.appendChild(dt),ye.disabled=!1},ve)},st=async()=>{if(ye){ye.disabled=!0;try{let ae;Bt()?ae=w:t?(ae=await t(),ae.length===0&&(ae=r.getAll())):ae=r.getAll();let ve=ae.map(Fe=>{try{return JSON.parse(Fe.payload)}catch{return Fe.payload}});await navigator.clipboard.writeText(JSON.stringify(ve,null,2)),Pt("check",1500)}catch{Pt("x",1500)}}},at=()=>{oe&&(k=oe.value,Xt(),Ne())},tn=()=>{!Ie||!Xe||(Xe.style.display=Ie.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{P=Ie.value,Xt(),Ne()},150))},en=()=>{!Ie||!Xe||(Ie.value="",P="",Xe.style.display="none",E&&clearTimeout(E),Xt(),Ne())},nn=()=>{if(De)return;let ae=J.scrollTop,{action:ve,nextLastScrollTop:Fe}=Ds({following:O.isFollowing(),currentScrollTop:ae,lastScrollTop:me,nearBottom:de(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});me=Fe,ve==="resume"?(O.resume(),ee=0,ie.style.display="none"):ve==="pause"&&(O.pause(),i&&(Q.textContent=c,ie.style.display=""))},z=ae=>{let ve=Ns({following:O.isFollowing(),deltaY:ae.deltaY,nearBottom:de(),resumeWhenNearBottom:!0});ve==="pause"?(O.pause(),i&&(Q.textContent=c,ie.style.display="")):ve==="resume"&&(O.resume(),ee=0,ie.style.display="none")},We=()=>{i&&(J.scrollTop=J.scrollHeight,O.resume(),ee=0,ie.style.display="none")},ge=ae=>{let ve=ae.target;if(!ve||ve.closest("button"))return;let Fe=ve.closest("[data-event-id]");if(!Fe)return;let wt=Fe.getAttribute("data-event-id");wt&&_e(wt)},ht=ae=>{if((ae.metaKey||ae.ctrlKey)&&ae.key==="f"){ae.preventDefault(),Ie==null||Ie.focus(),Ie==null||Ie.select();return}ae.key==="Escape"&&(Ie&&document.activeElement===Ie?(en(),Ie.blur(),R.focus()):n&&n())};ye&&ye.addEventListener("click",st),oe&&oe.addEventListener("change",at),Ie&&Ie.addEventListener("input",tn),Xe&&Xe.addEventListener("click",en),J.addEventListener("scroll",nn),J.addEventListener("wheel",z,{passive:!0}),J.addEventListener("click",ge),ie.addEventListener("click",We),R.addEventListener("keydown",ht);function Oe(){E&&clearTimeout(E),we!==null&&(cancelAnimationFrame(we),we=null),ne=!1,Le.clear(),ye&&ye.removeEventListener("click",st),oe&&oe.removeEventListener("change",at),Ie&&Ie.removeEventListener("input",tn),Xe&&Xe.removeEventListener("click",en),J.removeEventListener("scroll",nn),J.removeEventListener("wheel",z),J.removeEventListener("click",ge),ie.removeEventListener("click",We),R.removeEventListener("keydown",ht)}return{element:R,update:It,destroy:Oe}}}function Rd(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=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`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let d=document.createElement("div");d.className="persona-truncate persona-text-sm persona-font-medium",d.style.color="var(--persona-text, #1f2937)",d.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 g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(g)}else p.textContent=a;if(c.append(d,p),i.append(u,c),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",n),i.append(f)}return i}var Hd=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.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:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",d=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>Rd(e,r)});if(d)return d}return Rd(e,r)};var Ia=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},mr=new Ia;mr.register("PersonaArtifactCard",Hd);function Bu(e){var s;let r=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 n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function Bd(e,r){var ye,Ie,Xe,ft;let t=(Ie=(ye=e.features)==null?void 0:ye.artifacts)==null?void 0:Ie.layout,s=((Xe=t==null?void 0:t.toolbarPreset)!=null?Xe:"default")==="document",o=(ft=t==null?void 0:t.panePadding)==null?void 0:ft.trim(),a=e.markdown?_r(e.markdown):null,i=so(e.sanitize),u=q=>{let D=a?a(q):oo(q);return i?i(D):D},c=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,d=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});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 g=h("span","persona-text-xs persona-font-medium persona-truncate");g.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 q;d(),(q=r.onDismiss)==null||q.call(r)});let T="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?Lt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Lt({icon:"eye",label:"Rendered view"}),M=s?Lt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Lt({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,k=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,P=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(k&&P&&P.length>0),V=null,te,Z=null,O=null;if(s&&(w||k)&&!E){if(te=w?Yo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k){let q=fe("chevron-down",14,"currentColor",2);q&&te.appendChild(q)}}else s&&E?(V=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),te=w?Yo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),Z=Lt({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"}}),V.append(te,Z)):s?te=Lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):te=Lt({icon:"copy",label:"Copy"});let ee=s?Lt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Lt({icon:"refresh-cw",label:"Refresh"}),xe=s?Lt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Lt({icon:"x",label:"Close"}),ne=()=>{var J,ie,$e;let q=(J=le.find(Q=>Q.id===K))!=null?J:le[le.length-1],D=(ie=q==null?void 0:q.id)!=null?ie:null,ce=(q==null?void 0:q.artifactType)==="markdown"&&($e=q.markdown)!=null?$e:"",j=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:ce,jsonPayload:j,id:D}},we=async()=>{var J;let{markdown:q,jsonPayload:D}=ne(),ce=(J=le.find(ie=>ie.id===K))!=null?J:le[le.length-1],j=(ce==null?void 0:ce.artifactType)==="markdown"?q:ce?D:"";try{await navigator.clipboard.writeText(j)}catch{}};if(te.addEventListener("click",async()=>{let q=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(q&&E){let{markdown:D,jsonPayload:ce,id:j}=ne();try{await q({actionId:"primary",artifactId:j,markdown:D,jsonPayload:ce})}catch{}return}await we()}),Z&&(P!=null&&P.length)){let q=()=>{var ce;return(ce=p.closest("[data-persona-root]"))!=null?ce:document.body},D=()=>{O=kr({items:P.map(ce=>({id:ce.id,label:ce.label})),onSelect:async ce=>{let{markdown:j,jsonPayload:J,id:ie}=ne(),$e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:ce,artifactId:ie,markdown:j,jsonPayload:J}):ce==="markdown"||ce==="md"?await navigator.clipboard.writeText(j):ce==="json"||ce==="source"?await navigator.clipboard.writeText(J):await navigator.clipboard.writeText(j||J)}catch{}},anchor:V!=null?V:Z,position:"bottom-right",portal:q()})};p.isConnected?D():requestAnimationFrame(D),Z.addEventListener("click",ce=>{ce.stopPropagation(),O==null||O.toggle()})}ee.addEventListener("click",async()=>{var q;try{await((q=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:q.call(t))}catch{}G()}),xe.addEventListener("click",()=>{var q;d(),(q=r.onDismiss)==null||q.call(r)});let De=()=>{s&&(S.setAttribute("aria-pressed",T==="rendered"?"true":"false"),M.setAttribute("aria-pressed",T==="source"?"true":"false"))};S.addEventListener("click",()=>{T="rendered",De(),G()}),M.addEventListener("click",()=>{T="source",De(),G()});let me=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(),C.append(S,M),V?R.append(V,ee,xe):R.append(te,ee,xe),f.append(C,me,R),De()):(f.appendChild(g),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ke=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"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ke.style.paddingLeft=o,ke.style.paddingRight=o,Le.style.padding=o),p.appendChild(f),p.appendChild(ke),p.appendChild(Le);let le=[],K=null,pe=!1,G=()=>{var j,J,ie,$e;let q=s&&le.length<=1;ke.classList.toggle("persona-hidden",q),ke.replaceChildren();for(let Q of le){let se=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");se.type="button",se.textContent=Q.title||Q.id.slice(0,8),Q.id===K&&se.classList.add("persona-bg-persona-container","persona-border-persona-border"),se.addEventListener("click",()=>r.onSelect(Q.id)),ke.appendChild(se)}Le.replaceChildren();let D=K&&le.find(Q=>Q.id===K)||le[le.length-1];if(!D)return;if(s){let Q=D.artifactType==="markdown"?"MD":(j=D.component)!=null?j:"Component",kt=(D.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";me.textContent=`${kt} \xB7 ${Q}`}else g.textContent="Artifacts";if(D.artifactType==="markdown"){if(s&&T==="source"){let se=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");se.textContent=(J=D.markdown)!=null?J:"",Le.appendChild(se);return}let Q=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Q.innerHTML=u((ie=D.markdown)!=null?ie:""),Le.appendChild(Q);return}let ce=D.component?mr.get(D.component):void 0;if(ce){let se={message:{id:D.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let kt=ce(($e=D.props)!=null?$e:{},se);if(kt){Le.appendChild(kt);return}}catch{}}Le.appendChild(Bu(D))},oe=()=>{var D;let q=le.length>0;if(p.classList.toggle("persona-hidden",!q),c){let ce=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,J=((D=ce==null?void 0:ce.classList.contains("persona-artifact-narrow-host"))!=null?D:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;q&&J&&pe?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(q){var D,ce,j;le=q.artifacts,K=(j=(ce=q.selectedId)!=null?ce:(D=q.artifacts[q.artifacts.length-1])==null?void 0:D.id)!=null?j:null,le.length>0&&(pe=!0),G(),oe()},setMobileOpen(q){pe=q,!q&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):oe()}}}function $n(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Dd(e,r){var o,a,i,u;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"),!$n(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Du(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 _s(e,r){var u,c,d,p,f,g,v,T,C,S;if(!$n(r)){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"),Du(e),Dd(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(d=t==null?void 0:t.splitGap)!=null?d:"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 n=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(T=t==null?void 0:t.documentToolbarIconColor)==null?void 0:T.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Dd(e,r)}var Nd=["panel","seamless"];function js(e,r){var i,u,c,d,p,f;for(let g of Nd)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!$n(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Nd.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(d=t==null?void 0:t.paneBorderRadius)==null?void 0:d.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 g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Fd(e,r){var t,n,s;return!r||!$n(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Nu(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function Fu(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function Ou(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function $u(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Od(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function $d(e,r,t,n,s,o){let a=Nu(s,200),i=$u(r,t,n,200);i=Math.max(a,i);let u=Fu(o);return u!==null&&(i=Math.min(i,u)),Ou(e,a,i)}var _d={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"}},Pa=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,T,C;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(T=_d[a])!=null?T:_d.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,u.appendChild(S)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var P,E;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${S.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=S.label,M.appendChild(R);let w=(P=S.type)!=null?P:"text",k;w==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=w),k.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",k.id=`${r.id}-${a}-${S.name}`,k.name=S.name,k.placeholder=(E=S.placeholder)!=null?E:"",S.required&&(k.required=!0),M.appendChild(k),d.appendChild(M)});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]"),g=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");g.type="submit",g.textContent=(C=i.submitLabel)!=null?C:"Submit",p.appendChild(f),p.appendChild(g),d.appendChild(p),o.replaceChildren(u,d),d.addEventListener("submit",async S=>{var k,P;S.preventDefault();let M=(k=t.formEndpoint)!=null?k:"/form",R=new FormData(d),w={};R.forEach((E,V)=>{w[V]=E}),w.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let V=await E.json();f.textContent=(P=V.message)!=null?P:"Thanks! We'll be in touch soon.",V.success&&V.nextPrompt&&await n.sendMessage(String(V.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Wa=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Zo=new Wa;var jd=()=>{let e=new Map,r=(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:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var _u=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},ju=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},Qo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=_u(e),t=ju(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},Ra=e=>typeof e=="string"?e:e==null?"":String(e),Xr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ra(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Ra(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Ra(t.text)}}},zd=e=>Array.isArray(e)?e.map(r=>String(r)):[],es=e=>{let r=new Set(zd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(zd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,d)=>c||(d==null?void 0:d({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let d=()=>{e.emit("action:resubmit",u)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});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(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:t}};var zu=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},qu=e=>e.map(r=>({...r,streaming:!1})),zs=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?zu(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?qu(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var yo=require("partial-json");function Uu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Vu(e,r){if(!Uu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function qs(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=(0,yo.parse)(t,yo.STR|yo.OBJ),o=Vu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function qd(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Us(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=mr.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:n,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 Ud(){let e=qs();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Vs(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Js(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var Ju=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ys(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=Ju}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,g.appendChild(v);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,g.appendChild(T),f.appendChild(g);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let P=1;P<=5;P++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${P} star${P>1?"s":""}: ${c[P-1]}`),E.title=c[P-1],E.dataset.rating=String(P),E.innerHTML=`
18
+ `):""},Au=(e,r)=>{var p,d,f,g,v;let t=e.toolCall,n=(p=r==null?void 0:r.features)==null?void 0:p.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=Su(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=t?Qc(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=r==null?void 0:r.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=ma(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=ma(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Pd=(e,r,t)=>{var p;let n=fo.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=ye(n?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},La=(e,r)=>{var ne,Ce,re,xe,We,me,Me,ke,oe;let t=e.toolCall,n=(ne=r==null?void 0:r.toolCall)!=null?ne:{},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),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=(re=(Ce=r==null?void 0:r.features)==null?void 0:Ce.toolCallDisplay)!=null?re:{},a=o.expandable!==!1,i=a&&fo.has(e.id),{summary:u,previewText:c,isActive:p}=Au(e,r),d=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");d.type="button",a&&(d.setAttribute("aria-expanded",i?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(d.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(d.style.paddingLeft=n.headerPaddingX,d.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(d.style.paddingTop=n.headerPaddingY,d.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(g.style.color=n.headerTextColor);let v=String((xe=t.startedAt)!=null?xe:Date.now()),T=()=>{let X=h("span","");return X.setAttribute("data-tool-elapsed",v),X.textContent=Do(t),X},C=(me=n.renderCollapsedSummary)==null?void 0:me.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(We=o.collapsedMode)!=null?We:"tool-call",isActive:p,config:r!=null?r:{},elapsed:Do(t),createElapsedElement:T});typeof C=="string"&&C.trim()?(g.textContent=C,f.appendChild(g)):C instanceof HTMLElement?f.appendChild(C):(g.textContent=u,f.appendChild(g));let S=(Me=o.loadingAnimation)!=null?Me:"none",M=n.activeTextTemplate,H=n.completeTextTemplate,w=p?M:H,k=C instanceof HTMLElement,P=(X,pe,V)=>{let te=V;for(let ge of pe){let de=h("span","persona-tool-char");de.style.setProperty("--char-index",String(te)),de.textContent=ge===" "?"\xA0":ge,X.appendChild(de),te++}return te},E=(X,pe)=>{var de;g.textContent="";let V=((de=t.name)==null?void 0:de.trim())||"tool",te=ws(X,V),ge=0;for(let Re of te){let Ze=Re.styles.length>0?(()=>{let z=h("span",Re.styles.map(W=>`persona-tool-text-${W}`).join(" "));return g.appendChild(z),z})():g;if(Re.isDuration&&p)Ze.appendChild(T());else{let z=Re.isDuration?Do(t):Re.text;pe?ge=P(Ze,z,ge):Ze.appendChild(document.createTextNode(z))}}};if(!k)if(p&&S!=="none"){let X=(ke=n.loadingAnimationDuration)!=null?ke:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${X}ms`),w&&E(w,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${X}ms`),S==="shimmer-color"&&(n.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),w)E(w,!0);else{let pe=g.textContent||u;g.textContent="",P(g,pe,0)}}else w&&E(w,!1);let G=null;if(a){G=h("div","persona-flex persona-items-center");let X=n.toggleTextColor||n.headerTextColor||"currentColor",pe=ye(i?"chevron-up":"chevron-down",16,X,2);pe?G.appendChild(pe):G.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(G),d.append(f,V)}else d.append(f);let Q=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(Q.setAttribute("data-persona-collapsed-preview","tool"),Q.style.display="none",Q.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let X=(oe=n.renderCollapsedPreview)==null?void 0:oe.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:p,config:r!=null?r:{}});wu(Q,X)||(Q.textContent=c),Q.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,Q),s;let K=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(K.style.display=i?"":"none",n.contentBackgroundColor&&(K.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(K.style.color=n.contentTextColor),n.contentPaddingX&&(K.style.paddingLeft=n.contentPaddingX,K.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(K.style.paddingTop=n.contentPaddingY,K.style.paddingBottom=n.contentPaddingY),t.name){let X=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?X.style.color=n.contentTextColor:n.headerTextColor&&(X.style.color=n.headerTextColor),X.textContent=t.name,K.appendChild(X)}if(t.args!==void 0){let X=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(pe.style.color=n.labelTextColor),pe.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",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=ao(t.args),X.append(pe,V),K.appendChild(X)}if(t.chunks&&t.chunks.length){let X=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(pe.style.color=n.labelTextColor),pe.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",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=t.chunks.join(""),X.append(pe,V),K.appendChild(X)}if(t.status==="complete"&&t.result!==void 0){let X=h("div","persona-space-y-1"),pe=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(pe.style.color=n.labelTextColor),pe.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",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=ao(t.result),X.append(pe,V),K.appendChild(X)}if(t.status==="complete"&&typeof t.duration=="number"){let X=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(X.style.color=n.contentTextColor),X.textContent=`Duration: ${t.duration}ms`,K.appendChild(X)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),G){G.innerHTML="";let X=n.toggleTextColor||n.headerTextColor||"currentColor",pe=ye(i?"chevron-up":"chevron-down",16,X,2);pe?G.appendChild(pe):G.textContent=i?"Hide":"Show"}K.style.display=i?"":"none",Q.style.display=i?"none":Q.textContent||Q.childNodes.length?"":"none"})(),s.append(d,Q,K),s};var Ia=(e,r)=>{var T,C,S,M,H,w,k,P,E,G,Q,K;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.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=(T=n==null?void 0:n.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=n==null?void 0:n.borderColor)!=null?C:"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 u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=n==null?void 0:n.titleColor)!=null?S:"currentColor",p=ye(u,20,c,2);p&&i.appendChild(p);let d=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(g.style.color=n.titleColor),g.textContent=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(g),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}d.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,d.appendChild(v),t.parameters){let O=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=ao(t.parameters),d.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let ne=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");ne.type="button",ne.style.backgroundColor=(H=n==null?void 0:n.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",ne.setAttribute("data-approval-action","approve");let Ce=ye("shield-check",14,(k=n==null?void 0:n.approveButtonTextColor)!=null?k:"#ffffff",2);Ce&&(Ce.style.marginRight="4px",ne.appendChild(Ce));let re=document.createTextNode((P=n==null?void 0:n.approveLabel)!=null?P:"Approve");ne.appendChild(re);let xe=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");xe.type="button",xe.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",xe.style.color=(G=n==null?void 0:n.denyButtonTextColor)!=null?G:"var(--persona-feedback-error, #dc2626)",xe.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,xe.setAttribute("data-approval-action","deny");let We=ye("shield-x",14,(Q=n==null?void 0:n.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",2);We&&(We.style.marginRight="4px",xe.appendChild(We));let me=document.createTextNode((K=n==null?void 0:n.denyLabel)!=null?K:"Deny");xe.appendChild(me),O.append(ne,xe),d.appendChild(O)}return a.append(i,d),o.appendChild(a),o};var Wd=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let p=document.createDocumentFragment(),d=s?s.isStreaming():!1,f=g=>{switch(g){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'}};n.forEach(g=>{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=g,v.disabled=d,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(g))}),p.appendChild(v),r.push(v)}),e.appendChild(p)}}};var Ko=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Xo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function ho(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Eu={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)"}},Tu={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Mu=["flowName","stepName","reasoningText","text","name","tool","toolName"],ku=100;function Lu(e,r){let t={...Eu,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Tu}function Iu(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Pu(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function Wu(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.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 Ru(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Hu(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function Bu(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function Pa(e,r,t,n,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");ho(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var ne,Ce;let g=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 T=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ye(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&T.appendChild(C);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(ne=n.timestampFormat)!=null?ne:"relative";S.textContent=M==="relative"?Iu(e.timestamp,t):Pu(e.timestamp);let H=null;n.showSequenceNumbers!==!1&&(H=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(r+1));let w=Lu(e.type,n.badgeColors),k=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");k.style.backgroundColor=w.bg,k.style.color=w.text,k.style.borderColor=w.text+"50",k.textContent=e.type;let P=(Ce=n.descriptionFields)!=null?Ce:Mu,E=Wu(e.payload,P),G=null;E&&(G=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),G.textContent=E);let Q=h("div","persona-flex-1 persona-min-w-0"),K=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=ye("clipboard","12px","currentColor",1.5);return O&&K.appendChild(O),K.addEventListener("click",async re=>{re.stopPropagation(),await Ru(Hu(e)),K.innerHTML="";let xe=ye("check","12px","currentColor",1.5);xe&&K.appendChild(xe),setTimeout(()=>{K.innerHTML="";let We=ye("clipboard","12px","currentColor",1.5);We&&K.appendChild(We)},1500)}),v.appendChild(T),v.appendChild(S),H&&v.appendChild(H),v.appendChild(k),G&&v.appendChild(G),v.appendChild(Q),v.appendChild(K),g.appendChild(v),u&&g.appendChild(Bu(e,a,i)),g}}function Rd(e){var g,v,T,C,S;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(T=a==null?void 0:a.label)!=null?T:"",p=(S=(C=s==null?void 0:s.features)==null?void 0:C.eventStream)!=null?S:{},d=o.find(M=>M.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let M=d.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return f();function f(){let M=p.classNames,H=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ho(H,M==null?void 0:M.panel);let w=[],k="",P="",E=null,G=[],Q={},K=0,O=Ns(),ne=0,Ce=0,re=!1,xe=null,We=!1,me=0,Me=new Set,ke=new Map,oe="",X="",pe=null,V,te,ge,de,Re;function Ze(){let le=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),we=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");ho(we,M==null?void 0:M.headerBar);let Oe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Oe.textContent="Events",V=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"),V.textContent="0";let wt=h("div","persona-flex-1");te=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 jt=h("option","");jt.value="",jt.textContent="All events",te.appendChild(jt),ge=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"),ge.type="button",ge.title="Copy All";let zt=ye("clipboard-copy","12px","currentColor",1.5);zt&&ge.appendChild(zt);let yt=h("span","persona-text-xs");yt.textContent="Copy All",ge.appendChild(yt),we.appendChild(Oe),we.appendChild(V),we.appendChild(wt),we.appendChild(te),we.appendChild(ge);let Qe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ho(Qe,M==null?void 0:M.searchBar);let bt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),De=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&&De.appendChild(bt),de=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"),ho(de,M==null?void 0:M.searchInput),de.type="text",de.placeholder="Search event payloads...",Re=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Re.type="button",Re.style.display="none";let qt=ye("x","12px","currentColor",2);return qt&&Re.appendChild(qt),Qe.appendChild(De),Qe.appendChild(de),Qe.appendChild(Re),le.appendChild(we),le.appendChild(Qe),le}let z,W=o.find(le=>le.renderEventStreamToolbar);if(W!=null&&W.renderEventStreamToolbar&&s){let le=W.renderEventStreamToolbar({config:s,defaultRenderer:()=>Ze(),eventCount:r.getSize(),filteredCount:0,onFilterChange:we=>{k=we,Kt(),Ne()},onSearchChange:we=>{P=we,Kt(),Ne()}});z=le!=null?le:Ze()}else z=Ze();let se=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");se.style.display="none";let $=h("div","persona-flex-1 persona-min-h-0 persona-relative"),U=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");U.style.height="100%";let ce=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");ho(ce,M==null?void 0:M.scrollIndicator),ce.style.display="none",ce.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let _e=ye(u,"14px","currentColor",2);_e&&ce.appendChild(_e);let ee=h("span","");ee.textContent=c,ce.appendChild(ee);let ie=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ie.style.display="none",$.appendChild(U),$.appendChild(ie),$.appendChild(ce),H.setAttribute("tabindex","0"),H.appendChild(z),H.appendChild(se),H.appendChild($);function kt(){let le=r.getAll(),we={};for(let yt of le)we[yt.type]=(we[yt.type]||0)+1;let Oe=Object.keys(we).sort(),wt=Oe.length!==G.length||!Oe.every((yt,Qe)=>yt===G[Qe]),jt=!wt&&Oe.some(yt=>we[yt]!==Q[yt]),pt=le.length!==Object.values(Q).reduce((yt,Qe)=>yt+Qe,0);if(!wt&&!jt&&!pt||(G=Oe,Q=we,!te))return;let zt=te.value;if(te.options[0].textContent="All events",wt){for(;te.options.length>1;)te.remove(1);for(let yt of Oe){let Qe=h("option","");Qe.value=yt,Qe.textContent=`${yt} (${we[yt]||0})`,te.appendChild(Qe)}zt&&Oe.includes(zt)?te.value=zt:zt&&(te.value="",k="")}else for(let yt=1;yt<te.options.length;yt++){let Qe=te.options[yt];Qe.textContent=`${Qe.value} (${we[Qe.value]||0})`}}function dt(){let le=r.getAll();if(k&&(le=le.filter(we=>we.type===k)),P){let we=P.toLowerCase();le=le.filter(Oe=>Oe.type.toLowerCase().includes(we)||Oe.payload.toLowerCase().includes(we))}return le}function Bt(){return k!==""||P!==""}function Kt(){K=0,ne=0,O.resume(),ce.style.display="none"}function je(le){Me.has(le)?Me.delete(le):Me.add(le),pe=le;let we=U.scrollTop,Oe=O.isFollowing();We=!0,O.pause(),Ne(),U.scrollTop=we,Oe&&O.resume(),We=!1}function ue(){return Uo(U,50)}function Ne(){Ce=Date.now(),re=!1,kt();let le=r.getEvictedCount();le>0?(se.textContent=`${le.toLocaleString()} older events truncated`,se.style.display=""):se.style.display="none",w=dt();let we=w.length,Oe=r.getSize()>0;V&&(V.textContent=String(r.getSize())),we===0&&Oe&&Bt()?(ie.textContent=P?`No events matching '${P}'`:"No events matching filter",ie.style.display="",U.style.display="none"):(ie.style.display="none",U.style.display=""),ge&&(ge.title=Bt()?`Copy Filtered (${we})`:"Copy All"),i&&!O.isFollowing()&&we>K&&(ne+=we-K,ee.textContent=c?`${c}${ne>0?` (${ne})`:""}`:"",ce.style.display=""),K=we;let wt=r.getAll(),jt=wt.length>0?wt[0].timestamp:0,pt=new Set(w.map(Qe=>Qe.id));for(let Qe of Me)pt.has(Qe)||Me.delete(Qe);let zt=k!==oe||P!==X,yt=ke.size===0&&w.length>0;if(zt||yt||w.length===0){U.innerHTML="",ke.clear();let Qe=document.createDocumentFragment();for(let bt=0;bt<w.length;bt++){let De=Pa(w[bt],bt,jt,p,Me,je,o,s);ke.set(w[bt].id,De),Qe.appendChild(De)}U.appendChild(Qe),oe=k,X=P,pe=null}else{if(pe!==null){let bt=ke.get(pe);if(bt&&bt.parentNode===U){let De=w.findIndex(qt=>qt.id===pe);if(De>=0){let qt=Pa(w[De],De,jt,p,Me,je,o,s);U.insertBefore(qt,bt),bt.remove(),ke.set(pe,qt)}}pe=null}let Qe=new Set(w.map(bt=>bt.id));for(let[bt,De]of ke)Qe.has(bt)||(De.remove(),ke.delete(bt));for(let bt=0;bt<w.length;bt++){let De=w[bt];if(!ke.has(De.id)){let qt=Pa(De,bt,jt,p,Me,je,o,s);ke.set(De.id,qt),U.appendChild(qt)}}}O.isFollowing()&&(U.scrollTop=U.scrollHeight)}function It(){if(Date.now()-Ce>=ku){xe!==null&&(cancelAnimationFrame(xe),xe=null),Ne();return}re||(re=!0,xe=requestAnimationFrame(()=>{xe=null,Ne()}))}let Pt=(le,we)=>{if(!ge)return;ge.innerHTML="";let Oe=ye(le,"12px","currentColor",1.5);Oe&&ge.appendChild(Oe);let wt=h("span","persona-text-xs");wt.textContent="Copy All",ge.appendChild(wt),setTimeout(()=>{ge.innerHTML="";let jt=ye("clipboard-copy","12px","currentColor",1.5);jt&&ge.appendChild(jt);let pt=h("span","persona-text-xs");pt.textContent="Copy All",ge.appendChild(pt),ge.disabled=!1},we)},at=async()=>{if(ge){ge.disabled=!0;try{let le;Bt()?le=w:t?(le=await t(),le.length===0&&(le=r.getAll())):le=r.getAll();let we=le.map(Oe=>{try{return JSON.parse(Oe.payload)}catch{return Oe.payload}});await navigator.clipboard.writeText(JSON.stringify(we,null,2)),Pt("check",1500)}catch{Pt("x",1500)}}},it=()=>{te&&(k=te.value,Kt(),Ne())},tn=()=>{!de||!Re||(Re.style.display=de.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{P=de.value,Kt(),Ne()},150))},en=()=>{!de||!Re||(de.value="",P="",Re.style.display="none",E&&clearTimeout(E),Kt(),Ne())},nn=()=>{if(We)return;let le=U.scrollTop,{action:we,nextLastScrollTop:Oe}=Os({following:O.isFollowing(),currentScrollTop:le,lastScrollTop:me,nearBottom:ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});me=Oe,we==="resume"?(O.resume(),ne=0,ce.style.display="none"):we==="pause"&&(O.pause(),i&&(ee.textContent=c,ce.style.display=""))},q=le=>{let we=$s({following:O.isFollowing(),deltaY:le.deltaY,nearBottom:ue(),resumeWhenNearBottom:!0});we==="pause"?(O.pause(),i&&(ee.textContent=c,ce.style.display="")):we==="resume"&&(O.resume(),ne=0,ce.style.display="none")},He=()=>{i&&(U.scrollTop=U.scrollHeight,O.resume(),ne=0,ce.style.display="none")},he=le=>{let we=le.target;if(!we||we.closest("button"))return;let Oe=we.closest("[data-event-id]");if(!Oe)return;let wt=Oe.getAttribute("data-event-id");wt&&je(wt)},ht=le=>{if((le.metaKey||le.ctrlKey)&&le.key==="f"){le.preventDefault(),de==null||de.focus(),de==null||de.select();return}le.key==="Escape"&&(de&&document.activeElement===de?(en(),de.blur(),H.focus()):n&&n())};ge&&ge.addEventListener("click",at),te&&te.addEventListener("change",it),de&&de.addEventListener("input",tn),Re&&Re.addEventListener("click",en),U.addEventListener("scroll",nn),U.addEventListener("wheel",q,{passive:!0}),U.addEventListener("click",he),ce.addEventListener("click",He),H.addEventListener("keydown",ht);function $e(){E&&clearTimeout(E),xe!==null&&(cancelAnimationFrame(xe),xe=null),re=!1,ke.clear(),ge&&ge.removeEventListener("click",at),te&&te.removeEventListener("change",it),de&&de.removeEventListener("input",tn),Re&&Re.removeEventListener("click",en),U.removeEventListener("scroll",nn),U.removeEventListener("wheel",q),U.removeEventListener("click",he),ce.removeEventListener("click",He),H.removeEventListener("keydown",ht)}return{element:H,update:It,destroy:$e}}}function Hd(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=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`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.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",d.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(g)}else d.textContent=a;if(c.append(p,d),i.append(u,c),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",n),i.append(f)}return i}var Bd=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.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:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>Hd(e,r)});if(p)return p}return Hd(e,r)};var Wa=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},mr=new Wa;mr.register("PersonaArtifactCard",Bd);function Du(e){var s;let r=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 n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function Dd(e,r){var ge,de,Re,Ze;let t=(de=(ge=e.features)==null?void 0:ge.artifacts)==null?void 0:de.layout,s=((Re=t==null?void 0:t.toolbarPreset)!=null?Re:"default")==="document",o=(Ze=t==null?void 0:t.panePadding)==null?void 0:Ze.trim(),a=e.markdown?_r(e.markdown):null,i=so(e.sanitize),u=z=>{let W=a?a(z):oo(z);return i?i(W):W},c=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,p=()=>{c==null||c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let d=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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.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 g=h("span","persona-text-xs persona-font-medium persona-truncate");g.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;p(),(z=r.onDismiss)==null||z.call(r)});let T="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?Lt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Lt({icon:"eye",label:"Rendered view"}),M=s?Lt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Lt({icon:"code-2",label:"Source"}),H=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,k=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,P=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(k&&P&&P.length>0),G=null,Q,K=null,O=null;if(s&&(w||k)&&!E){if(Q=w?Yo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k){let z=ye("chevron-down",14,"currentColor",2);z&&Q.appendChild(z)}}else s&&E?(G=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=w?Yo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),K=Lt({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"}}),G.append(Q,K)):s?Q=Lt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):Q=Lt({icon:"copy",label:"Copy"});let ne=s?Lt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Lt({icon:"refresh-cw",label:"Refresh"}),Ce=s?Lt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Lt({icon:"x",label:"Close"}),re=()=>{var U,ce,_e;let z=(U=oe.find(ee=>ee.id===X))!=null?U:oe[oe.length-1],W=(ce=z==null?void 0:z.id)!=null?ce:null,se=(z==null?void 0:z.artifactType)==="markdown"&&(_e=z.markdown)!=null?_e:"",$=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:se,jsonPayload:$,id:W}},xe=async()=>{var U;let{markdown:z,jsonPayload:W}=re(),se=(U=oe.find(ce=>ce.id===X))!=null?U:oe[oe.length-1],$=(se==null?void 0:se.artifactType)==="markdown"?z:se?W:"";try{await navigator.clipboard.writeText($)}catch{}};if(Q.addEventListener("click",async()=>{let z=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(z&&E){let{markdown:W,jsonPayload:se,id:$}=re();try{await z({actionId:"primary",artifactId:$,markdown:W,jsonPayload:se})}catch{}return}await xe()}),K&&(P!=null&&P.length)){let z=()=>{var se;return(se=d.closest("[data-persona-root]"))!=null?se:document.body},W=()=>{O=kr({items:P.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:$,jsonPayload:U,id:ce}=re(),_e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:se,artifactId:ce,markdown:$,jsonPayload:U}):se==="markdown"||se==="md"?await navigator.clipboard.writeText($):se==="json"||se==="source"?await navigator.clipboard.writeText(U):await navigator.clipboard.writeText($||U)}catch{}},anchor:G!=null?G:K,position:"bottom-right",portal:z()})};d.isConnected?W():requestAnimationFrame(W),K.addEventListener("click",se=>{se.stopPropagation(),O==null||O.toggle()})}ne.addEventListener("click",async()=>{var z;try{await((z=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:z.call(t))}catch{}V()}),Ce.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let We=()=>{s&&(S.setAttribute("aria-pressed",T==="rendered"?"true":"false"),M.setAttribute("aria-pressed",T==="source"?"true":"false"))};S.addEventListener("click",()=>{T="rendered",We(),V()}),M.addEventListener("click",()=>{T="source",We(),V()});let me=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(),C.append(S,M),G?H.append(G,ne,Ce):H.append(Q,ne,Ce),f.append(C,me,H),We()):(f.appendChild(g),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Me=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"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Me.style.paddingLeft=o,Me.style.paddingRight=o,ke.style.padding=o),d.appendChild(f),d.appendChild(Me),d.appendChild(ke);let oe=[],X=null,pe=!1,V=()=>{var $,U,ce,_e;let z=s&&oe.length<=1;Me.classList.toggle("persona-hidden",z),Me.replaceChildren();for(let ee of oe){let ie=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");ie.type="button",ie.textContent=ee.title||ee.id.slice(0,8),ee.id===X&&ie.classList.add("persona-bg-persona-container","persona-border-persona-border"),ie.addEventListener("click",()=>r.onSelect(ee.id)),Me.appendChild(ie)}ke.replaceChildren();let W=X&&oe.find(ee=>ee.id===X)||oe[oe.length-1];if(!W)return;if(s){let ee=W.artifactType==="markdown"?"MD":($=W.component)!=null?$:"Component",kt=(W.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";me.textContent=`${kt} \xB7 ${ee}`}else g.textContent="Artifacts";if(W.artifactType==="markdown"){if(s&&T==="source"){let ie=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ie.textContent=(U=W.markdown)!=null?U:"",ke.appendChild(ie);return}let ee=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ee.innerHTML=u((ce=W.markdown)!=null?ce:""),ke.appendChild(ee);return}let se=W.component?mr.get(W.component):void 0;if(se){let ie={message:{id:W.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let kt=se((_e=W.props)!=null?_e:{},ie);if(kt){ke.appendChild(kt);return}}catch{}}ke.appendChild(Du(W))},te=()=>{var W;let z=oe.length>0;if(d.classList.toggle("persona-hidden",!z),c){let se=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,U=((W=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?W:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;z&&U&&pe?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(z){var W,se,$;oe=z.artifacts,X=($=(se=z.selectedId)!=null?se:(W=z.artifacts[z.artifacts.length-1])==null?void 0:W.id)!=null?$:null,oe.length>0&&(pe=!0),V(),te()},setMobileOpen(z){pe=z,!z&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):te()}}}function $n(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Fd(e,r){var o,a,i,u;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"),!$n(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Fu(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 qs(e,r){var u,c,p,d,f,g,v,T,C,S;if(!$n(r)){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"),Fu(e),Fd(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(d=t==null?void 0:t.paneWidth)!=null?d:"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 n=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(T=t==null?void 0:t.documentToolbarIconColor)==null?void 0:T.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Fd(e,r)}var Nd=["panel","seamless"];function Us(e,r){var i,u,c,p,d,f;for(let g of Nd)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!$n(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Nd.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(d=t==null?void 0:t.paneShadow)==null?void 0:d.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 g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Od(e,r){var t,n,s;return!r||!$n(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Nu(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function Ou(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function $u(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function _u(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function $d(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function _d(e,r,t,n,s,o){let a=Nu(s,200),i=_u(r,t,n,200);i=Math.max(a,i);let u=Ou(o);return u!==null&&(i=Math.min(i,u)),$u(e,a,i)}var jd={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"}},Ra=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,T,C;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(T=jd[a])!=null?T:jd.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,u.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var P,E;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${S.name}`;let H=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=S.label,M.appendChild(H);let w=(P=S.type)!=null?P:"text",k;w==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=w),k.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",k.id=`${r.id}-${a}-${S.name}`,k.name=S.name,k.placeholder=(E=S.placeholder)!=null?E:"",S.required&&(k.required=!0),M.appendChild(k),p.appendChild(M)});let d=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]"),g=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");g.type="submit",g.textContent=(C=i.submitLabel)!=null?C:"Submit",d.appendChild(f),d.appendChild(g),p.appendChild(d),o.replaceChildren(u,p),p.addEventListener("submit",async S=>{var k,P;S.preventDefault();let M=(k=t.formEndpoint)!=null?k:"/form",H=new FormData(p),w={};H.forEach((E,G)=>{w[G]=E}),w.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let G=await E.json();f.textContent=(P=G.message)!=null?P:"Thanks! We'll be in touch soon.",G.success&&G.nextPrompt&&await n.sendMessage(String(G.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ha=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Zo=new Ha;var zd=()=>{let e=new Map,r=(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:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var ju=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},zu=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},Qo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=ju(e),t=zu(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},Ba=e=>typeof e=="string"?e:e==null?"":String(e),Kr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ba(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Ba(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:Ba(t.text)}}},qd=e=>Array.isArray(e)?e.map(r=>String(r)):[],es=e=>{let r=new Set(qd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(qd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var qu=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Uu=e=>e.map(r=>({...r,streaming:!1})),Vs=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?qu(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Uu(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var yo=require("partial-json");function Vu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Ju(e,r){if(!Vu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function Js(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=(0,yo.parse)(t,yo.STR|yo.OBJ),o=Ju(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Ud(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ys(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=mr.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:n,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 Vd(){let e=Js();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Gs(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Ks(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var Yu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xs(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=Yu}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let d=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,g.appendChild(v);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,g.appendChild(T),f.appendChild(g);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let P=1;P<=5;P++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${P} star${P>1?"s":""}: ${c[P-1]}`),E.title=c[P-1],E.dataset.rating=String(P),E.innerHTML=`
19
19
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
20
20
  <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>
21
21
  </svg>
22
- `,E.addEventListener("click",()=>{p=P,S.forEach((V,te)=>{let Z=te<P;V.classList.toggle("selected",Z),V.setAttribute("aria-checked",te===P-1?"true":"false")})}),S.push(E),C.appendChild(E)}f.appendChild(C);let M=null;if(u){let P=document.createElement("div");P.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),P.appendChild(M),f.appendChild(P)}let R=document.createElement("div");R.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),d.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(p===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let P=(M==null?void 0:M.value.trim())||void 0;await r(p,P),d.remove()}catch(P){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",P)}}),R.appendChild(w),R.appendChild(k),f.appendChild(R),d.appendChild(f),d}function Gs(e){let{onSubmit:r,onDismiss:t,title:n="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:u=!0,lowLabel:c="Not likely",highLabel:d="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,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,v.appendChild(T);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,v.appendChild(C),g.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=d,M.appendChild(R),M.appendChild(w);let k=document.createElement("div");k.className="persona-feedback-numbers";let P=[];for(let O=0;O<=10;O++){let ee=document.createElement("button");ee.type="button",ee.className="persona-feedback-rating-btn persona-feedback-number-btn",ee.setAttribute("role","radio"),ee.setAttribute("aria-checked","false"),ee.setAttribute("aria-label",`Rating ${O} out of 10`),ee.textContent=String(O),ee.dataset.rating=String(O),O<=6?ee.classList.add("persona-feedback-detractor"):O<=8?ee.classList.add("persona-feedback-passive"):ee.classList.add("persona-feedback-promoter"),ee.addEventListener("click",()=>{f=O,P.forEach((xe,ne)=>{xe.classList.toggle("selected",ne===O),xe.setAttribute("aria-checked",ne===O?"true":"false")})}),P.push(ee),k.appendChild(ee)}S.appendChild(M),S.appendChild(k),g.appendChild(S);let E=null;if(u){let O=document.createElement("div");O.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),g.appendChild(O)}let V=document.createElement("div");V.className="persona-feedback-actions";let te=document.createElement("button");te.type="button",te.className="persona-feedback-btn persona-feedback-btn-skip",te.textContent=i,te.addEventListener("click",()=>{t==null||t(),p.remove()});let Z=document.createElement("button");return Z.type="button",Z.className="persona-feedback-btn persona-feedback-btn-submit",Z.textContent=a,Z.addEventListener("click",async()=>{if(f===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await r(f,O),p.remove()}catch(O){Z.disabled=!1,Z.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),V.appendChild(te),V.appendChild(Z),g.appendChild(V),p.appendChild(g),p}var bo="persona-chat-history",Yu=30*1e3,Gu={"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 Xu(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Gu[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function Xs(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Ku(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Zu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ha=e=>!e||typeof e!="object"?{}:{...e},Vd=e=>e.map(r=>({...r,streaming:!1})),Jd=(e,r,t)=>{let n=e!=null&&e.markdown?_r(e.markdown):null,s=so(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 c,d,p;let a=(c=o.text)!=null?c:"",i=(d=o.message.rawContent)!=null?d:null;if(r){let f=r.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 u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):n?u=n(a):u=oo(a),s?s(u):u}};function Yd(e){var i,u,c,d;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(d=e==null?void 0:e.iconStrokeWidth)!=null?d:.5,a=fe(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,r.appendChild(p)}return r}var Ks=(e,r,t)=>{var ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Fi,Oi;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 n=Ps(r),s=Zo.getForInstance(n.plugins);n.components&&mr.registerAll(n.components);let o=jd(),a=(ei=n.storageAdapter)!=null?ei:zs(),i={},u=null,c=!1,d=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:A}=m;return A&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return d(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=d(m);y.metadata&&(i=Ha(y.metadata)),(ti=y.messages)!=null&&ti.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=d({messages:[],metadata:{}});(ni=l.messages)!=null&&ni.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Co()},g=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Qo],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Xr.message,Xr.messageAndClick],T=es({parsers:g,handlers:v,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let C=(oi=(ri=n.launcher)==null?void 0:ri.enabled)!=null?oi:!0,S=(ai=(si=n.launcher)==null?void 0:si.autoExpand)!=null?ai:!1,M=(ii=n.autoFocusInput)!=null?ii:!1,R=S,w=C,k=(ci=(li=n.layout)==null?void 0:li.header)==null?void 0:ci.layout,P=!1,E=C?S:!0,V=!1,te=null,Z=()=>{V=!0,te&&clearTimeout(te),te=setTimeout(()=>{V&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),V=!1)},1e4)},O=Jd(n,T,Z),ee=(pi=(di=n.features)==null?void 0:di.showReasoning)!=null?pi:!0,xe=(mi=(ui=n.features)==null?void 0:ui.showToolCalls)!=null?mi:!0,ne=(fi=(gi=n.features)==null?void 0:gi.showEventStreamToggle)!=null?fi:!1,we=(yi=(hi=n.features)==null?void 0:hi.scrollToBottom)!=null?yi:{},me=`${(xi=typeof n.persistState=="object"?(bi=n.persistState)==null?void 0:bi.keyPrefix:void 0)!=null?xi:"persona-"}event-stream`,ke=ne?new Ko(me):null,Le=(wi=(Ci=(vi=n.features)==null?void 0:vi.eventStream)==null?void 0:Ci.maxEvents)!=null?wi:2e3,le=ne?new Xo(Le,ke):null,K=null,pe=!1,G=null,oe=0;ke==null||ke.open().then(()=>le==null?void 0:le.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ye={onCopy:l=>{var m,y;o.emit("message:copy",l),N!=null&&N.isClientTokenMode()&&N.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),N!=null&&N.isClientTokenMode()&&N.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},Ie=(Si=n.statusIndicator)!=null?Si:{},Xe=l=>{var m,y,A,L;return l==="idle"?(m=Ie.idleText)!=null?m:ln.idle:l==="connecting"?(y=Ie.connectingText)!=null?y:ln.connecting:l==="connected"?(A=Ie.connectedText)!=null?A:ln.connected:l==="error"?(L=Ie.errorText)!=null?L:ln.error:ln[l]};function ft(l,m,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=m}let{wrapper:q,panel:D}=Ed(n),ce=Td(n,C),{container:j,body:J,messagesWrapper:ie,suggestions:$e,textarea:Q,sendButton:se,sendButtonWrapper:kt,composerForm:ct,statusText:Bt,introTitle:Xt,introSubtitle:_e,closeButton:de,iconHolder:Ne,headerTitle:It,headerSubtitle:Pt,header:st,footer:at,actionsRow:tn,leftActions:en,rightActions:nn}=ce,z=ce.micButton,We=ce.micButtonWrapper,ge=ce.attachmentButton,ht=ce.attachmentButtonWrapper,Oe=ce.attachmentInput,ae=ce.attachmentPreviewsContainer;j.classList.add("persona-relative"),J.classList.add("persona-relative");let ve=12,Fe=()=>{var l;return(l=we.label)!=null?l:""},wt=()=>{var l;return(l=we.iconName)!=null?l:"arrow-down"},jt=()=>we.enabled!==!1,dt=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");dt.type="button",dt.style.display="none",dt.setAttribute("data-persona-scroll-to-bottom","true");let zt=h("span","persona-flex persona-items-center"),yt=h("span","");dt.append(zt,yt),j.appendChild(dt);let Ze=()=>{let m=at.style.display==="none"?0:at.offsetHeight;dt.style.bottom=`${m+ve}px`};Ze();let bt=()=>{let l=!!Fe();dt.setAttribute("aria-label",Fe()||"Jump to latest"),dt.title=Fe(),dt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),zt.innerHTML="";let m=fe(wt(),"14px","currentColor",2);m?(zt.appendChild(m),zt.style.display=""):zt.style.display="none",yt.textContent=Fe(),yt.style.display=l?"":"none"};bt();let He=null,qt=null,Gn=s.find(l=>l.renderHeader);if(Gn!=null&&Gn.renderHeader){let l=Gn.renderHeader({config:n,defaultRenderer:()=>{let m=ur({config:n,showClose:C});return Yr(j,m,n),m.header},onClose:()=>Wt(!1,"user")});if(l){let m=j.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),st=l)}}let nr=()=>{var m,y,A,L;if(!le)return;if(pe=!0,!K&&le&&(K=Wd({buffer:le,getFullHistory:()=>le.getAllFromStore(),onClose:()=>_n(),config:n,plugins:s})),K&&(J.style.display="none",(m=at.parentNode)==null||m.insertBefore(K.element,at),K.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${wn.actionIconColor}`;let W=(L=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;W&&W.split(/\s+/).forEach(H=>H&&et.classList.add(H))}let l=()=>{if(!pe)return;let W=Date.now();W-oe>=200&&(K==null||K.update(),oe=W),G=requestAnimationFrame(l)};oe=0,G=requestAnimationFrame(l),ir(),o.emit("eventStream:opened",{timestamp:Date.now()})},_n=()=>{var l,m,y;if(pe){if(pe=!1,K&&K.element.remove(),J.style.display="",et){et.style.boxShadow="";let A=(y=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&et.classList.remove(L))}G!==null&&(cancelAnimationFrame(G),G=null),ir(),o.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(ne){let l=(Ei=(Ai=n.features)==null?void 0:Ai.eventStream)==null?void 0:Ei.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");et=h("button",m),et.style.width="28px",et.style.height="28px",et.style.color=wn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let y=fe("activity","18px","currentColor",1.5);y&&et.appendChild(y);let A=ce.clearChatButtonWrapper,L=ce.closeButtonWrapper,W=A||L;W&&W.parentNode===st?st.insertBefore(et,W):st.appendChild(et),et.addEventListener("click",()=>{pe?_n():nr()})}let Ir=l=>{var A,L,W;let m=n.attachments;if(!(m!=null&&m.enabled))return;let y=l.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 H=l.querySelector("[data-persona-composer-form]");H!=null&&H.parentNode?H.parentNode.insertBefore(y,H):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let H=h("input");H.type="file",H.accept=((A=m.allowedTypes)!=null?A:pr).join(","),H.multiple=((L=m.maxFiles)!=null?L:4)>1,H.style.display="none",H.setAttribute("aria-label",(W=m.buttonTooltipText)!=null?W:"Attach files"),l.appendChild(H)}},Xn=s.find(l=>l.renderComposer);if(Xn!=null&&Xn.renderComposer){let l=n.composer,m=Xn.renderComposer({config:n,defaultRenderer:()=>uo({config:n}).footer,onSubmit:y=>{var H;if(!N||N.isStreaming())return;let A=y.trim(),L=(H=He==null?void 0:He.hasAttachments())!=null?H:!1;if(!A&&!L)return;let W;L&&(W=[],W.push(...He.getContentParts()),A&&W.push(No(A))),N.sendMessage(A,{contentParts:W}),L&&He.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Oe==null||Oe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((Ti=n.voiceRecognition)==null?void 0:Ti.enabled)===!0?()=>{qt==null||qt()}:void 0});m&&(at.replaceWith(m),at=m)}let Pr=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),W=l.querySelector("[data-persona-composer-status]");m&&(ct=m),y&&(Q=y),A&&(se=A),L&&(z=L,We=L.parentElement),W&&(Bt=W);let H=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");H&&($e=H);let U=l.querySelector(".persona-attachment-button");U&&(ge=U,ht=U.parentElement),Oe=l.querySelector('input[type="file"]'),ae=l.querySelector(".persona-attachment-previews");let F=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(tn=F)};Ir(at),Pr(at);let Rn=(Mi=n.layout)==null?void 0:Mi.contentMaxWidth;if(Rn&&ct&&(ct.style.maxWidth=Rn,ct.style.marginLeft="auto",ct.style.marginRight="auto"),Rn&&$e&&($e.style.maxWidth=Rn,$e.style.marginLeft="auto",$e.style.marginRight="auto"),Rn&&ae&&(ae.style.maxWidth=Rn,ae.style.marginLeft="auto",ae.style.marginRight="auto"),(ki=n.attachments)!=null&&ki.enabled&&Oe&&ae){He=Jr.fromConfig(n.attachments),He.setPreviewsContainer(ae),Oe.addEventListener("change",y=>{let A=y.target;He==null||He.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=Yd(l);j.appendChild(m)}(()=>{var A,L;let l=(L=(A=n.layout)==null?void 0:A.slots)!=null?L:{},m=W=>{switch(W){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ie;case"footer-top":return $e;case"composer":return ct;case"footer-bottom":return Bt;default:return null}},y=(W,H)=>{var U;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")st.insertBefore(H,st.firstChild);else if(W==="header-right")st.appendChild(H);else{let F=st.querySelector(".persona-flex-col");F?(U=F.parentNode)==null||U.insertBefore(H,F.nextSibling):st.appendChild(H)}break;case"body-top":{let F=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(H):J.insertBefore(H,J.firstChild);break}case"body-bottom":J.appendChild(H);break;case"footer-top":$e.replaceWith(H);break;case"footer-bottom":Bt.replaceWith(H);break;default:break}};for(let[W,H]of Object.entries(l))if(H)try{let U=H({config:n,defaultContent:()=>m(W)});U&&y(W,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,U)}})();let fr=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let W=y.getAttribute("data-bubble-type");W==="reasoning"?(go.has(L)?go.delete(L):go.add(L),Ld(L,A)):W==="tool"&&(fo.has(L)?fo.delete(L):fo.add(L),Id(L,A,n)),Bn.delete(L)};ie.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),fr(l))}),ie.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),fr(l))});let rr=new Map;ie.addEventListener("click",l=>{var H;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let W=y.getAttribute("data-action");if(W==="copy"){let F=N.getMessages().find(he=>he.id===L);if(F&&ye.onCopy){let he=F.content||"";navigator.clipboard.writeText(he).then(()=>{y.classList.add("persona-message-action-success");let Se=fe("check",14,"currentColor",2);Se&&(y.innerHTML="",y.appendChild(Se)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Ee=fe("copy",14,"currentColor",2);Ee&&(y.innerHTML="",y.appendChild(Ee))},2e3)}).catch(Se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Se)}),ye.onCopy(F)}}else if(W==="upvote"||W==="downvote")if(((H=rr.get(L))!=null?H:null)===W)rr.delete(L),y.classList.remove("persona-message-action-active");else{let he=W==="upvote"?"downvote":"upvote",Se=A.querySelector(`[data-action="${he}"]`);Se&&Se.classList.remove("persona-message-action-active"),rr.set(L,W),y.classList.add("persona-message-action-active");let Ce=N.getMessages().find(Me=>Me.id===L);Ce&&ye.onFeedback&&ye.onFeedback({type:W,messageId:Ce.id,message:Ce})}}),ie.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let W=y.getAttribute("data-approval-action");if(!W)return;let H=W==="approve"?"approved":"denied",F=N.getMessages().find(Se=>Se.id===L);if(!(F!=null&&F.approval))return;let he=A.querySelector("[data-approval-buttons]");he&&he.querySelectorAll("button").forEach(Ee=>{Ee.disabled=!0,Ee.style.opacity="0.5",Ee.style.cursor="not-allowed"}),N.resolveApproval(F.approval,H)});let it=null,Sn=null,jn={artifacts:[],selectedId:null},cn=!1,hr={current:null};ie.addEventListener("click",l=>{var Ee,Ce,Me,ze,ut;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Me=(Ce=(Ee=n.features)==null?void 0:Ee.artifacts)==null?void 0:Ce.onArtifactAction)==null?void 0:Me.call(Ce,{type:"download",artifactId:A}))===!0)return;let W=N.getArtifactById(A),H=W==null?void 0:W.markdown,U=(W==null?void 0:W.title)||"artifact";if(!H){let Ke=y.closest("[data-open-artifact]"),_=Ke==null?void 0:Ke.closest("[data-message-id]"),Pe=_==null?void 0:_.getAttribute("data-message-id");if(Pe){let be=N.getMessages().find(Be=>Be.id===Pe);if(be!=null&&be.rawContent)try{let Be=JSON.parse(be.rawContent);H=(ze=Be==null?void 0:Be.props)==null?void 0:ze.markdown,U=((ut=Be==null?void 0:Be.props)==null?void 0:ut.title)||U}catch{}}}if(!H)return;let F=new Blob([H],{type:"text/markdown"}),he=URL.createObjectURL(F),Se=document.createElement("a");Se.href=he,Se.download=`${U}.md`,Se.click(),URL.revokeObjectURL(he)}),ie.addEventListener("click",l=>{var W,H,U;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((U=(H=(W=n.features)==null?void 0:W.artifacts)==null?void 0:H.onArtifactAction)==null?void 0:U.call(H,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),cn=!1,N.selectArtifact(A),En())}),ie.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let An=null,Et=null,dn=null,Hn=null,yr=()=>{};function or(){Hn==null||Hn(),Hn=null}let br=()=>{var H;if(!An||!Et)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((H=e.ownerDocument.defaultView)!=null?H:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){Et.style.removeProperty("position"),Et.style.removeProperty("left"),Et.style.removeProperty("top"),Et.style.removeProperty("bottom"),Et.style.removeProperty("width"),Et.style.removeProperty("z-index");return}let A=An.firstElementChild;if(!A||A===Et)return;let L=10;Et.style.position="absolute",Et.style.top="0",Et.style.bottom="0",Et.style.width=`${L}px`,Et.style.zIndex="5";let W=A.offsetWidth-L/2;Et.style.left=`${Math.max(0,W)}px`},Kn=()=>{},En=()=>{var y,A,L,W,H;if(!it||!$n(n))return;_s(e,n),js(e,n),Kn();let l=(W=(L=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?W:520,m=D.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),it.update(jn),cn?(it.setMobileOpen(!1),it.element.classList.add("persona-hidden"),(H=it.backdrop)==null||H.classList.add("persona-hidden")):jn.artifacts.length>0&&(it.element.classList.remove("persona-hidden"),it.setMobileOpen(!0)),yr()};if($n(n)){D.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(j),it=Bd(n,{onSelect:y=>{var A;return(A=hr.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{cn=!0,En()}}),it.element.classList.add("persona-hidden"),An=m,m.appendChild(l),m.appendChild(it.element),it.backdrop&&D.appendChild(it.backdrop),D.appendChild(m),yr=()=>{var A,L,W,H;if(!An||!it)return;if(!(((W=(L=(A=n.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:W.resizable)===!0)){dn==null||dn(),dn=null,or(),Et&&(Et.remove(),Et=null),it.element.style.removeProperty("width"),it.element.style.removeProperty("maxWidth");return}if(!Et){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 F=e.ownerDocument,he=(H=F.defaultView)!=null?H:window,Se=Ee=>{var _,Pe;if(!it||Ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||he.innerWidth<=640)return;Ee.preventDefault(),or();let Ce=Ee.clientX,Me=it.element.getBoundingClientRect().width,ze=(Pe=(_=n.features)==null?void 0:_.artifacts)==null?void 0:Pe.layout,ut=Re=>{let be=An.getBoundingClientRect().width,Be=e.classList.contains("persona-artifact-appearance-seamless"),At=Be?0:Od(An,he),Ct=Be?0:U.getBoundingClientRect().width||6,Jt=Me-(Re.clientX-Ce),on=$d(Jt,be,At,Ct,ze==null?void 0:ze.resizableMinWidth,ze==null?void 0:ze.resizableMaxWidth);it.element.style.width=`${on}px`,it.element.style.maxWidth="none",br()},Ke=()=>{F.removeEventListener("pointermove",ut),F.removeEventListener("pointerup",Ke),F.removeEventListener("pointercancel",Ke),Hn=null;try{U.releasePointerCapture(Ee.pointerId)}catch{}};Hn=Ke,F.addEventListener("pointermove",ut),F.addEventListener("pointerup",Ke),F.addEventListener("pointercancel",Ke);try{U.setPointerCapture(Ee.pointerId)}catch{}};U.addEventListener("pointerdown",Se),Et=U,An.insertBefore(U,it.element),dn=()=>{U.removeEventListener("pointerdown",Se)}}if(Et){let U=jn.artifacts.length>0&&!cn;Et.classList.toggle("persona-hidden",!U),br()}},Kn=()=>{var he,Se,Ee,Ce,Me,ze,ut,Ke,_,Pe,Re,be,Be,At;if(!C||!it||((Se=(he=n.launcher)==null?void 0:he.sidebarMode)!=null?Se:!1)||Gt(n)&&On(n).reveal==="emerge")return;let A=(Ee=e.ownerDocument.defaultView)!=null?Ee:window,L=(Me=(Ce=n.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Me:!0,W=(ut=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?ut:640;if(L&&A.innerWidth<=W||!Fd(n,C))return;let H=(Pe=(_=(Ke=n.launcher)==null?void 0:Ke.width)!=null?_:n.launcherWidth)!=null?Pe:Wn,U=(At=(Be=(be=(Re=n.features)==null?void 0:Re.artifacts)==null?void 0:be.layout)==null?void 0:Be.expandedPanelWidth)!=null?At:"min(720px, calc(100vw - 24px))";jn.artifacts.length>0&&!cn?(D.style.width=U,D.style.maxWidth=U):(D.style.width=H,D.style.maxWidth=H)},typeof ResizeObserver!="undefined"&&(Sn=new ResizeObserver(()=>{En()}),Sn.observe(D))}else D.appendChild(j);e.appendChild(q);let Zn=()=>{var Ct,Jt,on,Ae,yn,sn,Vn,ot,mt,bn,cr,Je,Tt,Dr,Nr,us,ms,gs,aa,ia,Ut,fs,Lo;let l=Gt(n),m=(Jt=(Ct=n.launcher)==null?void 0:Ct.sidebarMode)!=null?Jt:!1,y=l||m||((Ae=(on=n.launcher)==null?void 0:on.fullHeight)!=null?Ae:!1),A=((yn=n.launcher)==null?void 0:yn.enabled)===!1,L=(Vn=(sn=n.theme)==null?void 0:sn.components)==null?void 0:Vn.panel,W=zo(n),H=(xn,Fn)=>{var ro;return xn==null||xn===""?Fn:(ro=_o(W,xn))!=null?ro:xn},U=(ot=e.ownerDocument.defaultView)!=null?ot:window,F=(bn=(mt=n.launcher)==null?void 0:mt.mobileFullscreen)!=null?bn:!0,he=(Je=(cr=n.launcher)==null?void 0:cr.mobileBreakpoint)!=null?Je:640,Se=U.innerWidth<=he,Ee=F&&Se&&C,Ce=(Dr=(Tt=n.launcher)==null?void 0:Tt.position)!=null?Dr:"bottom-left",Me=Ce==="bottom-left"||Ce==="top-left",ze=(us=(Nr=n.launcher)==null?void 0:Nr.zIndex)!=null?us:Cn,ut=m||Ee?"none":"1px solid var(--persona-border)",Ke=Ee?"none":m?Me?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Ee&&(Ke="none",ut="none");let _=m||Ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Pe=H(L==null?void 0:L.border,ut),Re=H(L==null?void 0:L.shadow,Ke),be=H(L==null?void 0:L.borderRadius,_);if(e.style.cssText="",q.style.cssText="",D.style.cssText="",j.style.cssText="",J.style.cssText="",at.style.cssText="",Ee){q.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"),q.style.cssText=`
22
+ `,E.addEventListener("click",()=>{d=P,S.forEach((G,Q)=>{let K=Q<P;G.classList.toggle("selected",K),G.setAttribute("aria-checked",Q===P-1?"true":"false")})}),S.push(E),C.appendChild(E)}f.appendChild(C);let M=null;if(u){let P=document.createElement("div");P.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),P.appendChild(M),f.appendChild(P)}let H=document.createElement("div");H.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(d===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let P=(M==null?void 0:M.value.trim())||void 0;await r(d,P),p.remove()}catch(P){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",P)}}),H.appendChild(w),H.appendChild(k),f.appendChild(H),p.appendChild(f),p}function Zs(e){let{onSubmit:r,onDismiss:t,title:n="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:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,v.appendChild(T);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,v.appendChild(C),g.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,M.appendChild(H),M.appendChild(w);let k=document.createElement("div");k.className="persona-feedback-numbers";let P=[];for(let O=0;O<=10;O++){let ne=document.createElement("button");ne.type="button",ne.className="persona-feedback-rating-btn persona-feedback-number-btn",ne.setAttribute("role","radio"),ne.setAttribute("aria-checked","false"),ne.setAttribute("aria-label",`Rating ${O} out of 10`),ne.textContent=String(O),ne.dataset.rating=String(O),O<=6?ne.classList.add("persona-feedback-detractor"):O<=8?ne.classList.add("persona-feedback-passive"):ne.classList.add("persona-feedback-promoter"),ne.addEventListener("click",()=>{f=O,P.forEach((Ce,re)=>{Ce.classList.toggle("selected",re===O),Ce.setAttribute("aria-checked",re===O?"true":"false")})}),P.push(ne),k.appendChild(ne)}S.appendChild(M),S.appendChild(k),g.appendChild(S);let E=null;if(u){let O=document.createElement("div");O.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),g.appendChild(O)}let G=document.createElement("div");G.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=i,Q.addEventListener("click",()=>{t==null||t(),d.remove()});let K=document.createElement("button");return K.type="button",K.className="persona-feedback-btn persona-feedback-btn-submit",K.textContent=a,K.addEventListener("click",async()=>{if(f===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}K.disabled=!0,K.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await r(f,O),d.remove()}catch(O){K.disabled=!1,K.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),G.appendChild(Q),G.appendChild(K),g.appendChild(G),d.appendChild(g),d}var bo="persona-chat-history",Gu=30*1e3,Ku={"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 Xu(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Ku[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function Qs(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Zu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Qu(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Da=e=>!e||typeof e!="object"?{}:{...e},Jd=e=>e.map(r=>({...r,streaming:!1})),Yd=(e,r,t)=>{let n=e!=null&&e.markdown?_r(e.markdown):null,s=so(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 c,p,d;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.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 u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?u=n(a):u=oo(a),s?s(u):u}};function Gd(e){var i,u,c,p;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,r.appendChild(d)}return r}var ea=(e,r,t)=>{var ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i;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 n=Hs(r),s=Zo.getForInstance(n.plugins);n.components&&mr.registerAll(n.components);let o=zd(),a=(ni=n.storageAdapter)!=null?ni:Vs(),i={},u=null,c=!1,p=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:A}=m;return A&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=p(m);y.metadata&&(i=Da(y.metadata)),(ri=y.messages)!=null&&ri.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(oi=l.messages)!=null&&oi.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Co()},g=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Qo],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Kr.message,Kr.messageAndClick],T=es({parsers:g,handlers:v,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let C=(ai=(si=n.launcher)==null?void 0:si.enabled)!=null?ai:!0,S=(li=(ii=n.launcher)==null?void 0:ii.autoExpand)!=null?li:!1,M=(ci=n.autoFocusInput)!=null?ci:!1,H=S,w=C,k=(pi=(di=n.layout)==null?void 0:di.header)==null?void 0:pi.layout,P=!1,E=C?S:!0,G=!1,Q=null,K=()=>{G=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{G&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),G=!1)},1e4)},O=Yd(n,T,K),ne=(mi=(ui=n.features)==null?void 0:ui.showReasoning)!=null?mi:!0,Ce=(fi=(gi=n.features)==null?void 0:gi.showToolCalls)!=null?fi:!0,re=(yi=(hi=n.features)==null?void 0:hi.showEventStreamToggle)!=null?yi:!1,xe=(xi=(bi=n.features)==null?void 0:bi.scrollToBottom)!=null?xi:{},me=`${(Ci=typeof n.persistState=="object"?(vi=n.persistState)==null?void 0:vi.keyPrefix:void 0)!=null?Ci:"persona-"}event-stream`,Me=re?new Xo(me):null,ke=(Ai=(Si=(wi=n.features)==null?void 0:wi.eventStream)==null?void 0:Si.maxEvents)!=null?Ai:2e3,oe=re?new Ko(ke,Me):null,X=null,pe=!1,V=null,te=0;Me==null||Me.open().then(()=>oe==null?void 0:oe.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ge={onCopy:l=>{var m,y;o.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},de=(Ei=n.statusIndicator)!=null?Ei:{},Re=l=>{var m,y,A,L;return l==="idle"?(m=de.idleText)!=null?m:ln.idle:l==="connecting"?(y=de.connectingText)!=null?y:ln.connecting:l==="connected"?(A=de.connectedText)!=null?A:ln.connected:l==="error"?(L=de.errorText)!=null?L:ln.error:ln[l]};function Ze(l,m,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=m}let{wrapper:z,panel:W}=Td(n),se=Md(n,C),{container:$,body:U,messagesWrapper:ce,suggestions:_e,textarea:ee,sendButton:ie,sendButtonWrapper:kt,composerForm:dt,statusText:Bt,introTitle:Kt,introSubtitle:je,closeButton:ue,iconHolder:Ne,headerTitle:It,headerSubtitle:Pt,header:at,footer:it,actionsRow:tn,leftActions:en,rightActions:nn}=se,q=se.micButton,He=se.micButtonWrapper,he=se.attachmentButton,ht=se.attachmentButtonWrapper,$e=se.attachmentInput,le=se.attachmentPreviewsContainer;$.classList.add("persona-relative"),U.classList.add("persona-relative");let we=12,Oe=()=>{var l;return(l=xe.label)!=null?l:""},wt=()=>{var l;return(l=xe.iconName)!=null?l:"arrow-down"},jt=()=>xe.enabled!==!1,pt=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");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let zt=h("span","persona-flex persona-items-center"),yt=h("span","");pt.append(zt,yt),$.appendChild(pt);let Qe=()=>{let m=it.style.display==="none"?0:it.offsetHeight;pt.style.bottom=`${m+we}px`};Qe();let bt=()=>{let l=!!Oe();pt.setAttribute("aria-label",Oe()||"Jump to latest"),pt.title=Oe(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),zt.innerHTML="";let m=ye(wt(),"14px","currentColor",2);m?(zt.appendChild(m),zt.style.display=""):zt.style.display="none",yt.textContent=Oe(),yt.style.display=l?"":"none"};bt();let De=null,qt=null,Gn=s.find(l=>l.renderHeader);if(Gn!=null&&Gn.renderHeader){let l=Gn.renderHeader({config:n,defaultRenderer:()=>{let m=ur({config:n,showClose:C});return Yr($,m,n),m.header},onClose:()=>Wt(!1,"user")});if(l){let m=$.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),at=l)}}let nr=()=>{var m,y,A,L;if(!oe)return;if(pe=!0,!X&&oe&&(X=Rd({buffer:oe,getFullHistory:()=>oe.getAllFromStore(),onClose:()=>_n(),config:n,plugins:s})),X&&(U.style.display="none",(m=it.parentNode)==null||m.insertBefore(X.element,it),X.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${wn.actionIconColor}`;let R=(L=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;R&&R.split(/\s+/).forEach(B=>B&&tt.classList.add(B))}let l=()=>{if(!pe)return;let R=Date.now();R-te>=200&&(X==null||X.update(),te=R),V=requestAnimationFrame(l)};te=0,V=requestAnimationFrame(l),ir(),o.emit("eventStream:opened",{timestamp:Date.now()})},_n=()=>{var l,m,y;if(pe){if(pe=!1,X&&X.element.remove(),U.style.display="",tt){tt.style.boxShadow="";let A=(y=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&tt.classList.remove(L))}V!==null&&(cancelAnimationFrame(V),V=null),ir(),o.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(re){let l=(Mi=(Ti=n.features)==null?void 0:Ti.eventStream)==null?void 0:Mi.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");tt=h("button",m),tt.style.width="28px",tt.style.height="28px",tt.style.color=wn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let y=ye("activity","18px","currentColor",1.5);y&&tt.appendChild(y);let A=se.clearChatButtonWrapper,L=se.closeButtonWrapper,R=A||L;R&&R.parentNode===at?at.insertBefore(tt,R):at.appendChild(tt),tt.addEventListener("click",()=>{pe?_n():nr()})}let Ir=l=>{var A,L,R;let m=n.attachments;if(!(m!=null&&m.enabled))return;let y=l.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 B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(y,B):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((A=m.allowedTypes)!=null?A:pr).join(","),B.multiple=((L=m.maxFiles)!=null?L:4)>1,B.style.display="none",B.setAttribute("aria-label",(R=m.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(B)}},Kn=s.find(l=>l.renderComposer);if(Kn!=null&&Kn.renderComposer){let l=n.composer,m=Kn.renderComposer({config:n,defaultRenderer:()=>uo({config:n}).footer,onSubmit:y=>{var B;if(!F||F.isStreaming())return;let A=y.trim(),L=(B=De==null?void 0:De.hasAttachments())!=null?B:!1;if(!A&&!L)return;let R;L&&(R=[],R.push(...De.getContentParts()),A&&R.push(Fo(A))),F.sendMessage(A,{contentParts:R}),L&&De.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{$e==null||$e.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((ki=n.voiceRecognition)==null?void 0:ki.enabled)===!0?()=>{qt==null||qt()}:void 0});m&&(it.replaceWith(m),it=m)}let Pr=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),R=l.querySelector("[data-persona-composer-status]");m&&(dt=m),y&&(ee=y),A&&(ie=A),L&&(q=L,He=L.parentElement),R&&(Bt=R);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(_e=B);let J=l.querySelector(".persona-attachment-button");J&&(he=J,ht=J.parentElement),$e=l.querySelector('input[type="file"]'),le=l.querySelector(".persona-attachment-previews");let N=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(tn=N)};Ir(it),Pr(it);let Rn=(Li=n.layout)==null?void 0:Li.contentMaxWidth;if(Rn&&dt&&(dt.style.maxWidth=Rn,dt.style.marginLeft="auto",dt.style.marginRight="auto"),Rn&&_e&&(_e.style.maxWidth=Rn,_e.style.marginLeft="auto",_e.style.marginRight="auto"),Rn&&le&&(le.style.maxWidth=Rn,le.style.marginLeft="auto",le.style.marginRight="auto"),(Ii=n.attachments)!=null&&Ii.enabled&&$e&&le){De=Jr.fromConfig(n.attachments),De.setPreviewsContainer(le),$e.addEventListener("change",y=>{let A=y.target;De==null||De.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=Gd(l);$.appendChild(m)}(()=>{var A,L;let l=(L=(A=n.layout)==null?void 0:A.slots)!=null?L:{},m=R=>{switch(R){case"body-top":return $.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ce;case"footer-top":return _e;case"composer":return dt;case"footer-bottom":return Bt;default:return null}},y=(R,B)=>{var J;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")at.insertBefore(B,at.firstChild);else if(R==="header-right")at.appendChild(B);else{let N=at.querySelector(".persona-flex-col");N?(J=N.parentNode)==null||J.insertBefore(B,N.nextSibling):at.appendChild(B)}break;case"body-top":{let N=U.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(B):U.insertBefore(B,U.firstChild);break}case"body-bottom":U.appendChild(B);break;case"footer-top":_e.replaceWith(B);break;case"footer-bottom":Bt.replaceWith(B);break;default:break}};for(let[R,B]of Object.entries(l))if(B)try{let J=B({config:n,defaultContent:()=>m(R)});J&&y(R,J)}catch(J){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,J)}})();let fr=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=y.getAttribute("data-bubble-type");R==="reasoning"?(go.has(L)?go.delete(L):go.add(L),Id(L,A)):R==="tool"&&(fo.has(L)?fo.delete(L):fo.add(L),Pd(L,A,n)),Bn.delete(L)};ce.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),fr(l))}),ce.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),fr(l))});let rr=new Map;ce.addEventListener("click",l=>{var B;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let R=y.getAttribute("data-action");if(R==="copy"){let N=F.getMessages().find(be=>be.id===L);if(N&&ge.onCopy){let be=N.content||"";navigator.clipboard.writeText(be).then(()=>{y.classList.add("persona-message-action-success");let Ae=ye("check",14,"currentColor",2);Ae&&(y.innerHTML="",y.appendChild(Ae)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Te=ye("copy",14,"currentColor",2);Te&&(y.innerHTML="",y.appendChild(Te))},2e3)}).catch(Ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ae)}),ge.onCopy(N)}}else if(R==="upvote"||R==="downvote")if(((B=rr.get(L))!=null?B:null)===R)rr.delete(L),y.classList.remove("persona-message-action-active");else{let be=R==="upvote"?"downvote":"upvote",Ae=A.querySelector(`[data-action="${be}"]`);Ae&&Ae.classList.remove("persona-message-action-active"),rr.set(L,R),y.classList.add("persona-message-action-active");let Se=F.getMessages().find(Ie=>Ie.id===L);Se&&ge.onFeedback&&ge.onFeedback({type:R,messageId:Se.id,message:Se})}}),ce.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let R=y.getAttribute("data-approval-action");if(!R)return;let B=R==="approve"?"approved":"denied",N=F.getMessages().find(Ae=>Ae.id===L);if(!(N!=null&&N.approval))return;let be=A.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(Te=>{Te.disabled=!0,Te.style.opacity="0.5",Te.style.cursor="not-allowed"}),F.resolveApproval(N.approval,B)});let lt=null,Sn=null,jn={artifacts:[],selectedId:null},cn=!1,hr={current:null};ce.addEventListener("click",l=>{var Te,Se,Ie,qe,mt;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Ie=(Se=(Te=n.features)==null?void 0:Te.artifacts)==null?void 0:Se.onArtifactAction)==null?void 0:Ie.call(Se,{type:"download",artifactId:A}))===!0)return;let R=F.getArtifactById(A),B=R==null?void 0:R.markdown,J=(R==null?void 0:R.title)||"artifact";if(!B){let Xe=y.closest("[data-open-artifact]"),j=Xe==null?void 0:Xe.closest("[data-message-id]"),Pe=j==null?void 0:j.getAttribute("data-message-id");if(Pe){let ve=F.getMessages().find(Fe=>Fe.id===Pe);if(ve!=null&&ve.rawContent)try{let Fe=JSON.parse(ve.rawContent);B=(qe=Fe==null?void 0:Fe.props)==null?void 0:qe.markdown,J=((mt=Fe==null?void 0:Fe.props)==null?void 0:mt.title)||J}catch{}}}if(!B)return;let N=new Blob([B],{type:"text/markdown"}),be=URL.createObjectURL(N),Ae=document.createElement("a");Ae.href=be,Ae.download=`${J}.md`,Ae.click(),URL.revokeObjectURL(be)}),ce.addEventListener("click",l=>{var R,B,J;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((J=(B=(R=n.features)==null?void 0:R.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:J.call(B,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),cn=!1,F.selectArtifact(A),En())}),ce.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let An=null,Et=null,dn=null,Hn=null,yr=()=>{};function or(){Hn==null||Hn(),Hn=null}let br=()=>{var B;if(!An||!Et)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){Et.style.removeProperty("position"),Et.style.removeProperty("left"),Et.style.removeProperty("top"),Et.style.removeProperty("bottom"),Et.style.removeProperty("width"),Et.style.removeProperty("z-index");return}let A=An.firstElementChild;if(!A||A===Et)return;let L=10;Et.style.position="absolute",Et.style.top="0",Et.style.bottom="0",Et.style.width=`${L}px`,Et.style.zIndex="5";let R=A.offsetWidth-L/2;Et.style.left=`${Math.max(0,R)}px`},Xn=()=>{},En=()=>{var y,A,L,R,B;if(!lt||!$n(n))return;qs(e,n),Us(e,n),Xn();let l=(R=(L=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?R:520,m=W.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),lt.update(jn),cn?(lt.setMobileOpen(!1),lt.element.classList.add("persona-hidden"),(B=lt.backdrop)==null||B.classList.add("persona-hidden")):jn.artifacts.length>0&&(lt.element.classList.remove("persona-hidden"),lt.setMobileOpen(!0)),yr()};if($n(n)){W.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild($),lt=Dd(n,{onSelect:y=>{var A;return(A=hr.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{cn=!0,En()}}),lt.element.classList.add("persona-hidden"),An=m,m.appendChild(l),m.appendChild(lt.element),lt.backdrop&&W.appendChild(lt.backdrop),W.appendChild(m),yr=()=>{var A,L,R,B;if(!An||!lt)return;if(!(((R=(L=(A=n.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:R.resizable)===!0)){dn==null||dn(),dn=null,or(),Et&&(Et.remove(),Et=null),lt.element.style.removeProperty("width"),lt.element.style.removeProperty("maxWidth");return}if(!Et){let J=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");J.setAttribute("role","separator"),J.setAttribute("aria-orientation","vertical"),J.setAttribute("aria-label","Resize artifacts panel"),J.tabIndex=0;let N=e.ownerDocument,be=(B=N.defaultView)!=null?B:window,Ae=Te=>{var j,Pe;if(!lt||Te.button!==0||e.classList.contains("persona-artifact-narrow-host")||be.innerWidth<=640)return;Te.preventDefault(),or();let Se=Te.clientX,Ie=lt.element.getBoundingClientRect().width,qe=(Pe=(j=n.features)==null?void 0:j.artifacts)==null?void 0:Pe.layout,mt=Be=>{let ve=An.getBoundingClientRect().width,Fe=e.classList.contains("persona-artifact-appearance-seamless"),At=Fe?0:$d(An,be),Ct=Fe?0:J.getBoundingClientRect().width||6,Jt=Ie-(Be.clientX-Se),on=_d(Jt,ve,At,Ct,qe==null?void 0:qe.resizableMinWidth,qe==null?void 0:qe.resizableMaxWidth);lt.element.style.width=`${on}px`,lt.element.style.maxWidth="none",br()},Xe=()=>{N.removeEventListener("pointermove",mt),N.removeEventListener("pointerup",Xe),N.removeEventListener("pointercancel",Xe),Hn=null;try{J.releasePointerCapture(Te.pointerId)}catch{}};Hn=Xe,N.addEventListener("pointermove",mt),N.addEventListener("pointerup",Xe),N.addEventListener("pointercancel",Xe);try{J.setPointerCapture(Te.pointerId)}catch{}};J.addEventListener("pointerdown",Ae),Et=J,An.insertBefore(J,lt.element),dn=()=>{J.removeEventListener("pointerdown",Ae)}}if(Et){let J=jn.artifacts.length>0&&!cn;Et.classList.toggle("persona-hidden",!J),br()}},Xn=()=>{var be,Ae,Te,Se,Ie,qe,mt,Xe,j,Pe,Be,ve,Fe,At;if(!C||!lt||((Ae=(be=n.launcher)==null?void 0:be.sidebarMode)!=null?Ae:!1)||Gt(n)&&On(n).reveal==="emerge")return;let A=(Te=e.ownerDocument.defaultView)!=null?Te:window,L=(Ie=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?Ie:!0,R=(mt=(qe=n.launcher)==null?void 0:qe.mobileBreakpoint)!=null?mt:640;if(L&&A.innerWidth<=R||!Od(n,C))return;let B=(Pe=(j=(Xe=n.launcher)==null?void 0:Xe.width)!=null?j:n.launcherWidth)!=null?Pe:Wn,J=(At=(Fe=(ve=(Be=n.features)==null?void 0:Be.artifacts)==null?void 0:ve.layout)==null?void 0:Fe.expandedPanelWidth)!=null?At:"min(720px, calc(100vw - 24px))";jn.artifacts.length>0&&!cn?(W.style.width=J,W.style.maxWidth=J):(W.style.width=B,W.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(Sn=new ResizeObserver(()=>{En()}),Sn.observe(W))}else W.appendChild($);e.appendChild(z);let Zn=()=>{var Ct,Jt,on,Ee,yn,sn,Vn,st,gt,bn,cr,Ye,Tt,Dr,Fr,us,ms,gs,ca,da,Ut,fs,Lo;let l=Gt(n),m=(Jt=(Ct=n.launcher)==null?void 0:Ct.sidebarMode)!=null?Jt:!1,y=l||m||((Ee=(on=n.launcher)==null?void 0:on.fullHeight)!=null?Ee:!1),A=((yn=n.launcher)==null?void 0:yn.enabled)===!1,L=(Vn=(sn=n.theme)==null?void 0:sn.components)==null?void 0:Vn.panel,R=zo(n),B=(xn,Nn)=>{var ro;return xn==null||xn===""?Nn:(ro=_o(R,xn))!=null?ro:xn},J=(st=e.ownerDocument.defaultView)!=null?st:window,N=(bn=(gt=n.launcher)==null?void 0:gt.mobileFullscreen)!=null?bn:!0,be=(Ye=(cr=n.launcher)==null?void 0:cr.mobileBreakpoint)!=null?Ye:640,Ae=J.innerWidth<=be,Te=N&&Ae&&C,Se=(Dr=(Tt=n.launcher)==null?void 0:Tt.position)!=null?Dr:"bottom-left",Ie=Se==="bottom-left"||Se==="top-left",qe=(us=(Fr=n.launcher)==null?void 0:Fr.zIndex)!=null?us:Cn,mt=m||Te?"none":"1px solid var(--persona-border)",Xe=Te?"none":m?Ie?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Te&&(Xe="none",mt="none");let j=m||Te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Pe=B(L==null?void 0:L.border,mt),Be=B(L==null?void 0:L.shadow,Xe),ve=B(L==null?void 0:L.borderRadius,j);if(e.style.cssText="",z.style.cssText="",W.style.cssText="",$.style.cssText="",U.style.cssText="",it.style.cssText="",Te){z.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"),z.style.cssText=`
23
23
  position: fixed !important;
24
24
  inset: 0 !important;
25
25
  width: 100% !important;
@@ -29,9 +29,9 @@
29
29
  padding: 0 !important;
30
30
  display: flex !important;
31
31
  flex-direction: column !important;
32
- z-index: ${ze} !important;
32
+ z-index: ${qe} !important;
33
33
  background-color: var(--persona-surface, #ffffff) !important;
34
- `,D.style.cssText=`
34
+ `,W.style.cssText=`
35
35
  position: relative !important;
36
36
  display: flex !important;
37
37
  flex-direction: column !important;
@@ -44,7 +44,7 @@
44
44
  padding: 0 !important;
45
45
  box-shadow: none !important;
46
46
  border-radius: 0 !important;
47
- `,j.style.cssText=`
47
+ `,$.style.cssText=`
48
48
  display: flex !important;
49
49
  flex-direction: column !important;
50
50
  flex: 1 1 0% !important;
@@ -55,7 +55,7 @@
55
55
  overflow: hidden !important;
56
56
  border-radius: 0 !important;
57
57
  border: none !important;
58
- `,J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",at.style.flexShrink="0",P=!0;return}let Be=(gs=(ms=n==null?void 0:n.launcher)==null?void 0:ms.width)!=null?gs:n==null?void 0:n.launcherWidth,At=Be!=null?Be:Wn;if(!m&&!l)A&&y?(D.style.width="100%",D.style.maxWidth="100%"):(D.style.width=At,D.style.maxWidth=At);else if(l)if(On(n).reveal==="emerge"){let Fn=On(n).width;D.style.width=Fn,D.style.maxWidth=Fn}else D.style.width="100%",D.style.maxWidth="100%";if(Kn(),D.style.boxShadow=Re,D.style.borderRadius=be,j.style.border=Pe,j.style.borderRadius=be,l&&!Ee&&(L==null?void 0:L.border)===void 0&&(j.style.border="none",On(n).side==="right"?j.style.borderLeft="1px solid var(--persona-border)":j.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),q.style.display="flex",q.style.flexDirection="column",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.maxHeight="100%",q.style.height="100%",A&&(q.style.overflow="hidden"),D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.height="100%",D.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.overflowY="auto",at.style.flexShrink="0"),q.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!A&&!l&&((aa=Yn[Ce])!=null?aa:Yn["bottom-right"]).split(" ").forEach(Fn=>q.classList.add(Fn)),m){let xn=(Ut=(ia=n.launcher)==null?void 0:ia.sidebarWidth)!=null?Ut:"420px";q.style.cssText=`
58
+ `,U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",it.style.flexShrink="0",P=!0;return}let Fe=(gs=(ms=n==null?void 0:n.launcher)==null?void 0:ms.width)!=null?gs:n==null?void 0:n.launcherWidth,At=Fe!=null?Fe:Wn;if(!m&&!l)A&&y?(W.style.width="100%",W.style.maxWidth="100%"):(W.style.width=At,W.style.maxWidth=At);else if(l)if(On(n).reveal==="emerge"){let Nn=On(n).width;W.style.width=Nn,W.style.maxWidth=Nn}else W.style.width="100%",W.style.maxWidth="100%";if(Xn(),W.style.boxShadow=Be,W.style.borderRadius=ve,$.style.border=Pe,$.style.borderRadius=ve,l&&!Te&&(L==null?void 0:L.border)===void 0&&($.style.border="none",On(n).side==="right"?$.style.borderLeft="1px solid var(--persona-border)":$.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",A&&(z.style.overflow="hidden"),W.style.display="flex",W.style.flexDirection="column",W.style.flex="1 1 0%",W.style.minHeight="0",W.style.maxHeight="100%",W.style.height="100%",W.style.overflow="hidden",$.style.display="flex",$.style.flexDirection="column",$.style.flex="1 1 0%",$.style.minHeight="0",$.style.maxHeight="100%",$.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",it.style.flexShrink="0"),z.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!A&&!l&&((ca=Yn[Se])!=null?ca:Yn["bottom-right"]).split(" ").forEach(Nn=>z.classList.add(Nn)),m){let xn=(Ut=(da=n.launcher)==null?void 0:da.sidebarWidth)!=null?Ut:"420px";z.style.cssText=`
59
59
  position: fixed !important;
60
60
  top: 0 !important;
61
61
  bottom: 0 !important;
@@ -66,9 +66,9 @@
66
66
  padding: 0 !important;
67
67
  display: flex !important;
68
68
  flex-direction: column !important;
69
- z-index: ${ze} !important;
70
- ${Me?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
71
- `,D.style.cssText=`
69
+ z-index: ${qe} !important;
70
+ ${Ie?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
71
+ `,W.style.cssText=`
72
72
  position: relative !important;
73
73
  display: flex !important;
74
74
  flex-direction: column !important;
@@ -79,9 +79,9 @@
79
79
  min-height: 0 !important;
80
80
  margin: 0 !important;
81
81
  padding: 0 !important;
82
- box-shadow: ${Re} !important;
83
- border-radius: ${be} !important;
84
- `,D.style.setProperty("width","100%","important"),D.style.setProperty("max-width","100%","important"),j.style.cssText=`
82
+ box-shadow: ${Be} !important;
83
+ border-radius: ${ve} !important;
84
+ `,W.style.setProperty("width","100%","important"),W.style.setProperty("max-width","100%","important"),$.style.cssText=`
85
85
  display: flex !important;
86
86
  flex-direction: column !important;
87
87
  flex: 1 1 0% !important;
@@ -90,29 +90,29 @@
90
90
  min-height: 0 !important;
91
91
  max-height: 100% !important;
92
92
  overflow: hidden !important;
93
- border-radius: ${be} !important;
93
+ border-radius: ${ve} !important;
94
94
  border: ${Pe} !important;
95
- `,at.style.cssText=`
95
+ `,it.style.cssText=`
96
96
  flex-shrink: 0 !important;
97
97
  border-top: none !important;
98
98
  padding: 8px 16px 12px 16px !important;
99
- `}if(!A&&!l){let xn="max-height: -moz-available !important; max-height: stretch !important;",Fn=m?"":"padding-top: 1.25em !important;",ro=m?"":`z-index: ${(Lo=(fs=n.launcher)==null?void 0:fs.zIndex)!=null?Lo:Cn} !important;`;q.style.cssText+=xn+Fn+ro}};Zn(),Er(e,n),_s(e,n),js(e,n);let St=[],Nt=null,Ft=null;St.push(()=>{Nt==null||Nt(),Nt=null,Ft==null||Ft(),Ft=null}),Sn&&St.push(()=>{Sn==null||Sn.disconnect(),Sn=null}),St.push(()=>{dn==null||dn(),dn=null,or(),Et&&(Et.remove(),Et=null),it==null||it.element.style.removeProperty("width"),it==null||it.element.style.removeProperty("maxWidth")}),ne&&St.push(()=>{G!==null&&(cancelAnimationFrame(G),G=null),K==null||K.destroy(),K=null,le==null||le.destroy(),le=null,ke=null});let Tn=null,xr=()=>{Tn&&(Tn(),Tn=null),n.colorScheme==="auto"&&(Tn=Hs(()=>{Er(e,n)}))};xr(),St.push(()=>{Tn&&(Tn(),Tn=null)});let zn=Pd($e),Mn=null,N,qn=!1,Bn=Cd(),vr=0,gn=Bs(),fn=0,re=null,kn=!1,sr=!1,ns=4,xo=24,rs=80,Qr=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},vo=(Ii=(Li=n.voiceRecognition)==null?void 0:Li.autoResume)!=null?Ii:!1,Dn=l=>{o.emit("voice:state",{active:Qe.active,source:l,timestamp:Date.now()})},hn=()=>{f(l=>({...l,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},os=()=>{var A,L;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Ha(i.voiceState),m=!!l.active,y=Number((L=l.timestamp)!=null?L:0);Qe.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Yu&&setTimeout(()=>{var W,H;Qe.active||(Qe.manuallyDeactivated=!1,((H=(W=n.voiceRecognition)==null?void 0:W.provider)==null?void 0:H.type)==="runtype"?N.toggleVoice().then(()=>{Qe.active=N.isVoiceActive(),Dn("restore"),N.isVoiceActive()&&Ve()}):Br("restore"))},1e3)},ss=()=>N?Vd(N.getMessages()).filter(l=>!l.__skipPersist):[];function Co(l){if(!(a!=null&&a.save))return;let y={messages:l?Vd(l):N?ss():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let ar=null,as=()=>q.querySelector("#persona-scroll-container")||J,Wr=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null),kn=!1},wo=()=>{re!==null&&(cancelAnimationFrame(re),re=null),sr=!1,Wr()},ir=()=>{if(!jt()||pe){dt.parentNode&&dt.remove(),dt.style.display="none";return}dt.parentNode!==j&&j.appendChild(dt),Ze();let l=qo(J)>0;dt.style.display=gn.isFollowing()||!l?"none":""},So=()=>{gn.pause()&&(wo(),ir())},Cr=()=>{gn.resume(),ir()},wr=(l=!1)=>{gn.isFollowing()&&(!l&&!qn||(re!==null&&(cancelAnimationFrame(re),re=null),sr=!0,re=requestAnimationFrame(()=>{re=null,sr=!1,gn.isFollowing()&&is(as(),l?220:140)})))},is=(l,m=500)=>{let y=l.scrollTop,A=qo(l),L=A-y;if(Math.abs(L)<1){fn=l.scrollTop;return}if(Math.abs(L)>=rs){Wr(),kn=!0,l.scrollTop=A,fn=l.scrollTop,kn=!1;return}Wr();let W=performance.now();kn=!0;let H=F=>1-Math.pow(1-F,3),U=F=>{if(!gn.isFollowing()){Wr();return}let he=qo(l);he!==A&&(A=he,L=A-y);let Se=F-W,Ee=Math.min(Se/m,1),Ce=H(Ee),Me=y+L*Ce;l.scrollTop=Me,fn=l.scrollTop,Ee<1?ar=requestAnimationFrame(U):(l.scrollTop=A,fn=l.scrollTop,ar=null,kn=!1)};ar=requestAnimationFrame(U)},ls=l=>{let m=new Map;l.forEach(y=>{let A=Qr.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Qr.clear(),m.forEach((y,A)=>{Qr.set(A,y)})},Rr=(l,m,y)=>{var Ee,Ce,Me,ze,ut,Ke;let A=document.createElement("div"),W=(()=>{var Pe;let _=s.find(Re=>Re.renderLoadingIndicator);if(_!=null&&_.renderLoadingIndicator)return _.renderLoadingIndicator;if((Pe=n.loadingIndicator)!=null&&Pe.render)return n.loadingIndicator.render})(),H=(_,Pe)=>Pe==null?!1:typeof Pe=="string"?(_.textContent=Pe,!0):(_.appendChild(Pe),!0),U=new Set;if(m.forEach(_=>{var Jt,on;U.add(_.id);let Pe=vd(_,vr),Re=wd(Bn,_.id,Pe);if(Re){A.appendChild(Re.cloneNode(!0));return}let be=null,Be=s.find(Ae=>!!(_.variant==="reasoning"&&Ae.renderReasoning||_.variant==="tool"&&Ae.renderToolCall||_.variant==="approval"&&Ae.renderApproval||!_.variant&&Ae.renderMessage)),At=(Jt=n.layout)==null?void 0:Jt.messages;if(Be)if(_.variant==="reasoning"&&_.reasoning&&Be.renderReasoning){if(!ee)return;be=Be.renderReasoning({message:_,defaultRenderer:()=>Ta(_,n),config:n})}else if(_.variant==="tool"&&_.toolCall&&Be.renderToolCall){if(!xe)return;be=Be.renderToolCall({message:_,defaultRenderer:()=>Ma(_,n),config:n})}else if(_.variant==="approval"&&_.approval&&Be.renderApproval){if(n.approval===!1)return;be=Be.renderApproval({message:_,defaultRenderer:()=>ka(_,n),config:n})}else Be.renderMessage&&(be=Be.renderMessage({message:_,defaultRenderer:()=>{let Ae=mo(_,y,At,n.messageActions,ye,{loadingIndicatorRenderer:W,widgetConfig:n});return _.role!=="user"&&Pa(Ae,_,n,N),Ae},config:n}));if(!be&&_.role==="assistant"&&!_.variant&&n.enableComponentStreaming!==!1&&Vs(_)){let yn=Js(_);if(yn){let sn=Us(yn,{config:n,message:_,transform:y});if(sn)if(n.wrapComponentDirectiveInBubble!==!1){let ot=document.createElement("div");if(ot.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(" "),ot.id=`bubble-${_.id}`,ot.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let mt=document.createElement("div");mt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",mt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),ot.appendChild(mt)}ot.appendChild(sn),be=ot}else{let ot=document.createElement("div");if(ot.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ot.id=`bubble-${_.id}`,ot.setAttribute("data-message-id",_.id),ot.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let mt=document.createElement("div");mt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",mt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),ot.appendChild(mt)}ot.appendChild(sn),be=ot}}}if(!be)if(_.variant==="reasoning"&&_.reasoning){if(!ee)return;be=Ta(_,n)}else if(_.variant==="tool"&&_.toolCall){if(!xe)return;be=Ma(_,n)}else if(_.variant==="approval"&&_.approval){if(n.approval===!1)return;be=ka(_,n)}else{let Ae=(on=n.layout)==null?void 0:on.messages;Ae!=null&&Ae.renderUserMessage&&_.role==="user"?be=Ae.renderUserMessage({message:_,config:n,streaming:!!_.streaming}):Ae!=null&&Ae.renderAssistantMessage&&_.role==="assistant"?be=Ae.renderAssistantMessage({message:_,config:n,streaming:!!_.streaming}):be=mo(_,y,Ae,n.messageActions,ye,{loadingIndicatorRenderer:W,widgetConfig:n}),_.role!=="user"&&be&&Pa(be,_,n,N)}let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id=`wrapper-${_.id}`,Ct.setAttribute("data-wrapper-id",_.id),_.role==="user"&&Ct.classList.add("persona-justify-end"),(be==null?void 0:be.getAttribute("data-persona-component-directive"))==="true"&&Ct.classList.add("persona-w-full"),Ct.appendChild(be),Sd(Bn,_.id,Pe,Ct),A.appendChild(Ct)}),(Ce=(Ee=n.features)==null?void 0:Ee.toolCallDisplay)!=null&&Ce.grouped){let _=[],Pe=[];m.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&xe){Pe.push(Re);return}Pe.length>1&&_.push(Pe),Pe=[]}),Pe.length>1&&_.push(Pe),_.forEach((Re,be)=>{var sn,Vn;let Be=Re.map(ot=>Array.from(A.children).find(mt=>mt instanceof HTMLElement&&mt.getAttribute("data-wrapper-id")===ot.id)).filter(ot=>!!ot);if(Be.length<2)return;let At=document.createElement("div");At.className="persona-flex",At.id=`wrapper-tool-group-${be}-${Re[0].id}`,At.setAttribute("data-wrapper-id",`tool-group-${be}-${Re[0].id}`);let Ct=document.createElement("div");Ct.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ct.setAttribute("data-persona-tool-group","true");let Jt=document.createElement("div");Jt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let on=`Called ${Re.length} tools`,Ae=(Vn=(sn=n.toolCall)==null?void 0:sn.renderGroupedSummary)==null?void 0:Vn.call(sn,{messages:Re,toolCalls:Re.map(ot=>ot.toolCall).filter(ot=>!!ot),defaultSummary:on,config:n});H(Jt,Ae)||(Jt.textContent=on);let yn=document.createElement("div");yn.className="persona-tool-group-stack persona-flex persona-flex-col",Ct.append(Jt,yn),At.appendChild(Ct),Be[0].before(At),Be.forEach((ot,mt)=>{let bn=document.createElement("div");bn.className="persona-tool-group-item persona-relative",bn.setAttribute("data-persona-tool-group-item","true"),mt<Be.length-1&&bn.setAttribute("data-persona-tool-group-connector","true"),bn.appendChild(ot),yn.appendChild(bn)})})}Ad(Bn,U);let F=m.some(_=>_.role==="assistant"&&_.streaming),he=m[m.length-1],Se=(he==null?void 0:he.role)==="assistant"&&!he.streaming&&he.variant!=="approval";if(qn&&m.some(_=>_.role==="user")&&!F&&!Se){let _={config:n,streaming:!0,location:"standalone",defaultRenderer:Gr},Pe=s.find(be=>be.renderLoadingIndicator),Re=null;if(Pe!=null&&Pe.renderLoadingIndicator&&(Re=Pe.renderLoadingIndicator(_)),Re===null&&((Me=n.loadingIndicator)!=null&&Me.render)&&(Re=n.loadingIndicator.render(_)),Re===null&&(Re=Gr()),Re){let be=document.createElement("div"),Be=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;be.className=Be?["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(" "),be.setAttribute("data-typing-indicator","true"),be.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",be.appendChild(Re);let At=document.createElement("div");At.className="persona-flex",At.id="wrapper-typing-indicator",At.setAttribute("data-wrapper-id","typing-indicator"),At.appendChild(be),A.appendChild(At)}}if(!qn&&m.length>0){let _=m[m.length-1],Pe={config:n,lastMessage:_,messageCount:m.length},Re=s.find(Be=>Be.renderIdleIndicator),be=null;if(Re!=null&&Re.renderIdleIndicator&&(be=Re.renderIdleIndicator(Pe)),be===null&&((ut=n.loadingIndicator)!=null&&ut.renderIdle)&&(be=n.loadingIndicator.renderIdle(Pe)),be){let Be=document.createElement("div"),At=((Ke=n.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;Be.className=At?["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(" "),Be.setAttribute("data-idle-indicator","true"),Be.appendChild(be);let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id="wrapper-idle-indicator",Ct.setAttribute("data-wrapper-id","idle-indicator"),Ct.appendChild(Be),A.appendChild(Ct)}}xd(l,A)},Hr=()=>{var F,he,Se,Ee,Ce;if(!C)return;let l=Gt(n),m=(F=e.ownerDocument.defaultView)!=null?F:window,y=(Se=(he=n.launcher)==null?void 0:he.mobileBreakpoint)!=null?Se:640,A=(Ce=(Ee=n.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Ce:!0,L=m.innerWidth<=y,W=A&&L&&C,H=On(n).reveal;E?(q.style.removeProperty("display"),q.style.display=l?"flex":"",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-95","persona-opacity-0"),D.classList.add("persona-scale-100","persona-opacity-100"),x?x.element.style.display="none":$&&($.style.display="none")):(l?l&&(H==="overlay"||H==="push")&&!W?(q.style.removeProperty("display"),q.style.display="flex",q.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.setProperty("display","none","important"),q.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(q.style.display="",q.classList.add("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100"),D.classList.add("persona-scale-95","persona-opacity-0")),x?x.element.style.display=l?"none":"":$&&($.style.display=l?"none":""))},Wt=(l,m="user")=>{var W,H;if(!C||E===l)return;let y=E;E=l,Hr();let A=(()=>{var Me,ze,ut,Ke,_,Pe,Re;let U=(ze=(Me=n.launcher)==null?void 0:Me.sidebarMode)!=null?ze:!1,F=(ut=e.ownerDocument.defaultView)!=null?ut:window,he=(_=(Ke=n.launcher)==null?void 0:Ke.mobileFullscreen)!=null?_:!0,Se=(Re=(Pe=n.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Re:640,Ee=F.innerWidth<=Se,Ce=Gt(n)&&he&&Ee;return U||he&&Ee&&C||Ce})();if(E&&A){if(!Nt){let U=e.getRootNode(),F=U instanceof ShadowRoot?U.host:e.closest(".persona-host");F&&(Nt=xa(F,(H=(W=n.launcher)==null?void 0:W.zIndex)!=null?H:Cn))}Ft||(Ft=va(e.ownerDocument))}else E||(Nt==null||Nt(),Nt=null,Ft==null||Ft(),Ft=null);E&&(B(),wr(!0));let L={open:E,source:m,timestamp:Date.now()};E&&!y?o.emit("widget:opened",L):!E&&y&&o.emit("widget:closed",L),o.emit("widget:state",{open:E,launcherEnabled:C,voiceActive:Qe.active,streaming:N.isStreaming()})},eo=l=>{se.disabled=l,z&&(z.disabled=l),zn.buttons.forEach(m=>{m.disabled=l}),at.dataset.personaComposerStreaming=l?"true":"false",at.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},to=()=>{Qe.active||Q&&Q.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>to(),200)});let Ao=()=>{var y,A,L,W,H,U,F,he,Se,Ee,Ce;Xt.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",_e.textContent=(W=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",Q.placeholder=(U=(H=n.copy)==null?void 0:H.inputPlaceholder)!=null?U:"How can I help...";let l=J.querySelector("[data-persona-intro-card]");if(l){let Me=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;l.style.display=Me?"":"none",Me?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}(Se=(he=n.sendButton)==null?void 0:he.useIcon)!=null&&Se||(se.textContent=(Ce=(Ee=n.copy)==null?void 0:Ee.sendButtonLabel)!=null?Ce:"Send"),Q.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Q.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Qn=null,cs=()=>{Qn==null&&(Qn=setInterval(()=>{let l=ie.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Qn),Qn=null;return}let m=Date.now();l.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=da(m-A))})},100))};if(N=new lo(n,{onMessagesChanged(l){Rr(ie,l,O),cs(),N&&(l.some(L=>L.role==="user")?zn.render([],N,Q,l):zn.render(n.suggestionChips,N,Q,l,n.suggestionChipsConfig)),wr(!qn),ls(l);let m=[...l].reverse().find(A=>A.role==="user"),y=Qe.lastUserMessageId;m&&m.id!==y&&(Qe.lastUserMessageId=m.id,o.emit("user:message",m)),Qe.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Co(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};ft(Bt,(L=>{var W,H,U,F;return L==="idle"?(W=m.idleText)!=null?W:ln.idle:L==="connecting"?(H=m.connectingText)!=null?H:ln.connecting:L==="connected"?(U=m.connectedText)!=null?U:ln.connected:L==="error"?(F=m.errorText)!=null?F:ln.error:ln[L]})(l),m,l)},onStreamingChanged(l){qn=l,eo(l),N&&Rr(ie,N.getMessages(),O),l||wr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":rt(),Rt();break;case"speaking":rt(),xt();break;default:l==="idle"&&N.isBargeInActive()?(rt(),Ve(),z==null||z.setAttribute("aria-label","End voice session")):(Qe.active=!1,rt(),Dn("system"),hn());break}},onArtifactsState(l){jn=l,En()}}),hr.current=N,((Wi=(Pi=n.voiceRecognition)==null?void 0:Pi.provider)==null?void 0:Wi.type)==="runtype")try{N.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&N.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),le&&N.setSSEEventCallback((l,m)=>{le==null||le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=Ha(l.metadata),T.syncFromMetadata()),(m=l.messages)!=null&&m.length&&N.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Eo=l=>{var L;l.preventDefault();let m=Q.value.trim(),y=(L=He==null?void 0:He.hasAttachments())!=null?L:!1;if(!m&&!y)return;let A;y&&(A=[],A.push(...He.getContentParts()),m&&A.push(No(m))),Q.value="",Q.style.height="auto",N.sendMessage(m,{contentParts:A}),y&&He.clearAttachments()},To=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),se.click())},Mo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!He)return;let m=Xu(l.clipboardData);m.length!==0&&(l.preventDefault(),await He.handleFiles(m))},pn=null,Ln=!1,lr=null,qe=null,ko=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Br=(l="user")=>{var W,H,U,F,he,Se,Ee;if(Ln||N.isStreaming())return;let m=ko();if(!m)return;pn=new m;let A=(H=((W=n.voiceRecognition)!=null?W:{}).pauseDuration)!=null?H:2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let L=Q.value;pn.onresult=Ce=>{let Me="",ze="";for(let Ke=0;Ke<Ce.results.length;Ke++){let _=Ce.results[Ke],Pe=_[0].transcript;_.isFinal?Me+=Pe+" ":ze=Pe}let ut=L+Me+ze;Q.value=ut,lr&&clearTimeout(lr),(Me||ze)&&(lr=window.setTimeout(()=>{let Ke=Q.value.trim();Ke&&pn&&Ln&&(Un(),Q.value="",Q.style.height="auto",N.sendMessage(Ke,{viaVoice:!0}))},A))},pn.onerror=Ce=>{Ce.error!=="no-speech"&&Un()},pn.onend=()=>{if(Ln){let Ce=Q.value.trim();Ce&&Ce!==L.trim()&&(Q.value="",Q.style.height="auto",N.sendMessage(Ce,{viaVoice:!0})),Un()}};try{if(pn.start(),Ln=!0,Qe.active=!0,l!=="system"&&(Qe.manuallyDeactivated=!1),Dn(l),hn(),z){let Ce=(U=n.voiceRecognition)!=null?U:{};qe={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(F=Ce.iconName)!=null?F:"mic",iconSize:parseFloat((Ee=(Se=Ce.iconSize)!=null?Se:(he=n.sendButton)==null?void 0:he.size)!=null?Ee:"40")||24};let Me=Ce.recordingBackgroundColor,ze=Ce.recordingIconColor,ut=Ce.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Me!=null?Me:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=ze!=null?ze:"var(--persona-voice-recording-indicator, #ffffff)",ze){let Ke=z.querySelector("svg");Ke&&Ke.setAttribute("stroke",ze)}ut&&(z.style.borderColor=ut),z.setAttribute("aria-label","Stop voice recognition")}}catch{Un("system")}},Un=(l="user")=>{if(Ln){if(Ln=!1,lr&&(clearTimeout(lr),lr=null),pn){try{pn.stop()}catch{}pn=null}if(Qe.active=!1,Dn(l),hn(),z){if(z.classList.remove("persona-voice-recording"),qe){z.style.backgroundColor=qe.backgroundColor,z.style.color=qe.color,z.style.borderColor=qe.borderColor;let m=z.querySelector("svg");m&&m.setAttribute("stroke",qe.color||"currentColor"),qe=null}z.setAttribute("aria-label","Start voice recognition")}}},ds=(l,m)=>{var _,Pe,Re,be,Be,At,Ct,Jt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((_=l==null?void 0:l.provider)==null?void 0:_.type)==="runtype";if(!(y||A))return null;let W=h("div","persona-send-button-wrapper"),H=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");H.type="button",H.setAttribute("aria-label","Start voice recognition");let U=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",F=(Re=m==null?void 0:m.size)!=null?Re:"40px",he=(be=l==null?void 0:l.iconSize)!=null?be:F,Se=parseFloat(he)||24,Ee=(Be=l==null?void 0:l.backgroundColor)!=null?Be:m==null?void 0:m.backgroundColor,Ce=(At=l==null?void 0:l.iconColor)!=null?At:m==null?void 0:m.textColor;H.style.width=he,H.style.height=he,H.style.minWidth=he,H.style.minHeight=he,H.style.fontSize="18px",H.style.lineHeight="1",Ce?H.style.color=Ce:H.style.color="var(--persona-text, #111827)";let ze=fe(U,Se,Ce||"currentColor",1.5);ze?H.appendChild(ze):H.textContent="\u{1F3A4}",Ee?H.style.backgroundColor=Ee:H.style.backgroundColor="",l!=null&&l.borderWidth&&(H.style.borderWidth=l.borderWidth,H.style.borderStyle="solid"),l!=null&&l.borderColor&&(H.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(H.style.paddingLeft=l.paddingX,H.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(H.style.paddingTop=l.paddingY,H.style.paddingBottom=l.paddingY),W.appendChild(H);let ut=(Ct=l==null?void 0:l.tooltipText)!=null?Ct:"Start voice recognition";if(((Jt=l==null?void 0:l.showTooltip)!=null?Jt:!1)&&ut){let on=h("div","persona-send-button-tooltip");on.textContent=ut,W.appendChild(on)}return{micButton:H,micButtonWrapper:W}},no=()=>{var m,y,A,L,W;if(!z||qe)return;let l=(m=n.voiceRecognition)!=null?m:{};qe={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((W=(L=l.iconSize)!=null?L:(A=n.sendButton)==null?void 0:A.size)!=null?W:"40")||24}},X=(l,m)=>{var W,H,U,F,he;if(!z)return;let y=z.querySelector("svg");y&&y.remove();let A=(he=qe==null?void 0:qe.iconSize)!=null?he:parseFloat((F=(U=(W=n.voiceRecognition)==null?void 0:W.iconSize)!=null?U:(H=n.sendButton)==null?void 0:H.size)!=null?F:"40")||24,L=fe(l,A,m,1.5);L&&z.appendChild(L)},je=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ve=()=>{var L;if(!z)return;no();let l=(L=n.voiceRecognition)!=null?L:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,A=l.recordingBorderColor;if(je(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let W=z.querySelector("svg");W&&W.setAttribute("stroke",y)}A&&(z.style.borderColor=A),z.setAttribute("aria-label","Stop voice recognition")},Rt=()=>{var U,F,he,Se,Ee,Ce,Me,ze;if(!z)return;no();let l=(U=n.voiceRecognition)!=null?U:{},m=N.getVoiceInterruptionMode(),y=(F=l.processingIconName)!=null?F:"loader",A=(Se=(he=l.processingIconColor)!=null?he:qe==null?void 0:qe.color)!=null?Se:"",L=(Ce=(Ee=l.processingBackgroundColor)!=null?Ee:qe==null?void 0:qe.backgroundColor)!=null?Ce:"",W=(ze=(Me=l.processingBorderColor)!=null?Me:qe==null?void 0:qe.borderColor)!=null?ze:"";je(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=L,z.style.borderColor=W;let H=A||"currentColor";z.style.color=H,X(y,H),z.setAttribute("aria-label","Processing voice input"),m==="none"&&(z.style.cursor="default")},xt=()=>{var he,Se,Ee,Ce,Me,ze,ut,Ke,_,Pe,Re,be;if(!z)return;no();let l=(he=n.voiceRecognition)!=null?he:{},m=N.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(Se=l.speakingIconName)!=null?Se:y,L=(ze=l.speakingIconColor)!=null?ze:m==="barge-in"?(Ce=(Ee=l.recordingIconColor)!=null?Ee:qe==null?void 0:qe.color)!=null?Ce:"":(Me=qe==null?void 0:qe.color)!=null?Me:"",W=(_=l.speakingBackgroundColor)!=null?_:m==="barge-in"?(ut=l.recordingBackgroundColor)!=null?ut:"var(--persona-voice-recording-bg, #ef4444)":(Ke=qe==null?void 0:qe.backgroundColor)!=null?Ke:"",H=(be=l.speakingBorderColor)!=null?be:m==="barge-in"?(Pe=l.recordingBorderColor)!=null?Pe:"":(Re=qe==null?void 0:qe.borderColor)!=null?Re:"";je(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=W,z.style.borderColor=H;let U=L||"currentColor";z.style.color=U,X(A,U);let F=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",F),m==="none"&&(z.style.cursor="default"),m==="barge-in"&&z.classList.add("persona-voice-recording")},rt=()=>{var l,m,y;z&&(je(),qe&&(z.style.backgroundColor=(l=qe.backgroundColor)!=null?l:"",z.style.color=(m=qe.color)!=null?m:"",z.style.borderColor=(y=qe.borderColor)!=null?y:"",X(qe.iconName,qe.color||"currentColor"),qe=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},lt=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=N.getVoiceStatus(),A=N.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){N.stopVoicePlayback();return}if(N.isBargeInActive()){N.stopVoicePlayback(),N.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,hn(),Dn("user"),rt()});return}N.toggleVoice().then(()=>{Qe.active=N.isVoiceActive(),Qe.manuallyDeactivated=!N.isVoiceActive(),hn(),Dn("user"),N.isVoiceActive()?Ve():rt()});return}if(Ln){let y=Q.value.trim();Qe.manuallyDeactivated=!0,hn(),Un("user"),y&&(Q.value="",Q.style.height="auto",N.sendMessage(y))}else Qe.manuallyDeactivated=!1,hn(),Br("user")};qt=lt,z&&(z.addEventListener("click",lt),St.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(N.isVoiceActive()&&N.toggleVoice(),rt()):Un("system"),z&&z.removeEventListener("click",lt)}));let b=o.on("assistant:complete",()=>{vo&&(Qe.active||Qe.manuallyDeactivated||vo==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!Qe.active&&!Qe.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?N.toggleVoice().then(()=>{Qe.active=N.isVoiceActive(),Dn("auto"),N.isVoiceActive()&&Ve()}):Br("auto"))},600))});St.push(b);let Te=o.on("action:resubmit",()=>{setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)});St.push(Te);let I=()=>{Wt(!E,"user")},x=null,$=null;if(C){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>Jo(n,I).element,onToggle:I});m&&($=m)}$||(x=Jo(n,I))}x?e.appendChild(x.element):$&&e.appendChild($),Hr(),zn.render(n.suggestionChips,N,Q,void 0,n.suggestionChipsConfig),Ao(),eo(N.isStreaming()),wr(!0),os(),M&&(C?E&&setTimeout(()=>to(),200):setTimeout(()=>to(),0));let B=()=>{var F,he,Se,Ee,Ce,Me,ze,ut,Ke,_,Pe,Re,be,Be,At,Ct,Jt,on,Ae,yn,sn,Vn;let l=Gt(n),m=(he=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?he:!1,y=l||m||((Ee=(Se=n.launcher)==null?void 0:Se.fullHeight)!=null?Ee:!1),A=(Ce=e.ownerDocument.defaultView)!=null?Ce:window,L=(ze=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?ze:!0,W=(Ke=(ut=n.launcher)==null?void 0:ut.mobileBreakpoint)!=null?Ke:640,H=A.innerWidth<=W,U=L&&H&&C;try{if(U){Zn(),Er(e,n);return}if(P&&(P=!1,Zn(),Er(e,n)),!C&&!l){D.style.height="",D.style.width="";return}if(!m&&!l){let ot=(Pe=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?Pe:n==null?void 0:n.launcherWidth,mt=ot!=null?ot:Wn;D.style.width=mt,D.style.maxWidth=mt}if(Kn(),!y){let ot=A.innerHeight,mt=64,bn=(be=(Re=n.launcher)==null?void 0:Re.heightOffset)!=null?be:0,cr=Math.max(200,ot-mt),Je=Math.min(640,cr),Tt=Math.max(200,Je-bn);D.style.height=`${Tt}px`}}finally{if(Ze(),Hr(),E&&C){let mt=((Be=e.ownerDocument.defaultView)!=null?Be:window).innerWidth<=((Ct=(At=n.launcher)==null?void 0:At.mobileBreakpoint)!=null?Ct:640),bn=(on=(Jt=n.launcher)==null?void 0:Jt.sidebarMode)!=null?on:!1,cr=(yn=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?yn:!0,Je=Gt(n)&&cr&&mt,Tt=bn||cr&&mt&&C||Je;if(Tt&&!Ft){let Dr=e.getRootNode(),Nr=Dr instanceof ShadowRoot?Dr.host:e.closest(".persona-host");Nr&&!Nt&&(Nt=xa(Nr,(Vn=(sn=n.launcher)==null?void 0:sn.zIndex)!=null?Vn:Cn)),Ft=va(e.ownerDocument)}else Tt||(Nt==null||Nt(),Nt=null,Ft==null||Ft(),Ft=null)}}};B();let ue=(Ri=e.ownerDocument.defaultView)!=null?Ri:window;if(ue.addEventListener("resize",B),St.push(()=>ue.removeEventListener("resize",B)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ze()});l.observe(at),St.push(()=>l.disconnect())}fn=J.scrollTop;let Ue=()=>{let l=J.scrollTop,{action:m,nextLastScrollTop:y}=Ds({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:fn,nearBottom:Uo(J,xo),userScrollThreshold:ns,isAutoScrolling:kn||sr,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fn=y,m==="resume"){Cr();return}m==="pause"&&So()};J.addEventListener("scroll",Ue,{passive:!0}),St.push(()=>J.removeEventListener("scroll",Ue));let tt=l=>{let m=Ns({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Uo(J,xo),resumeWhenNearBottom:!0});m==="pause"?So():m==="resume"&&Cr()};J.addEventListener("wheel",tt,{passive:!0}),St.push(()=>J.removeEventListener("wheel",tt)),dt.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,fn=J.scrollTop,Cr(),wr(!0)}),St.push(()=>dt.remove()),St.push(()=>{wo()});let Ot=()=>{de&&(Mn&&(de.removeEventListener("click",Mn),Mn=null),C?(de.style.display="",Mn=()=>{Wt(!1,"user")},de.addEventListener("click",Mn)):de.style.display="none")};Ot(),(()=>{let{clearChatButton:l}=ce;l&&l.addEventListener("click",()=>{N.clearMessages(),Bn.clear(),Cr();try{localStorage.removeItem(bo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bo}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==bo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},T.syncFromMetadata(),le==null||le.clear(),K==null||K.update()})})(),ct&&ct.addEventListener("submit",Eo),Q==null||Q.addEventListener("keydown",To),Q==null||Q.addEventListener("paste",Mo);let Kt="persona-attachment-drop-active",$t=0,Ge=()=>{$t=0,j.classList.remove(Kt)},vt=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&He!==null},Zt=l=>{!Xs(l.dataTransfer)||!vt()||($t++,$t===1&&j.classList.add(Kt))},rn=l=>{!Xs(l.dataTransfer)||!vt()||($t--,$t<=0&&Ge())},Dt=l=>{!Xs(l.dataTransfer)||!vt()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},In=l=>{var y;if(!Xs(l.dataTransfer)||!vt())return;l.preventDefault(),l.stopPropagation(),Ge();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&He.handleFiles(m)},Sr=!0;j.addEventListener("dragenter",Zt,Sr),j.addEventListener("dragleave",rn,Sr),e.addEventListener("dragover",Dt,Sr),e.addEventListener("drop",In,Sr);let ps=e.ownerDocument,Za=l=>{vt()&&l.preventDefault()},Qa=l=>{vt()&&l.preventDefault()};ps.addEventListener("dragover",Za),ps.addEventListener("drop",Qa),St.push(()=>{ct&&ct.removeEventListener("submit",Eo),Q==null||Q.removeEventListener("keydown",To),Q==null||Q.removeEventListener("paste",Mo)}),St.push(()=>{j.removeEventListener("dragenter",Zt,Sr),j.removeEventListener("dragleave",rn,Sr),e.removeEventListener("dragover",Dt,Sr),e.removeEventListener("drop",In,Sr),ps.removeEventListener("dragover",Za),ps.removeEventListener("drop",Qa),Ge()}),St.push(()=>{N.cancel()}),x?St.push(()=>{x==null||x.destroy()}):$&&St.push(()=>{$==null||$.remove()});let Vt={update(l){var $i,_i,ji,zi,qi,Ui,Vi,Ji,Yi,Gi,Xi,Ki,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Yl,Gl,Xl,Kl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Sc,Ac,Ec,Tc,Mc,kc,Lc,Ic,Pc,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c;let m=n.toolCall,y=n.messageActions,A=($i=n.layout)==null?void 0:$i.messages,L=n.colorScheme,W=n.loadingIndicator,H=n.iterationDisplay,U=(_i=n.features)==null?void 0:_i.showReasoning,F=(ji=n.features)==null?void 0:ji.showToolCalls,he=(zi=n.features)==null?void 0:zi.toolCallDisplay,Se=(qi=n.features)==null?void 0:qi.reasoningDisplay;n={...n,...l},Zn(),Er(e,n),_s(e,n),js(e,n),En(),n.colorScheme!==L&&xr();let Ee=Zo.getForInstance(n.plugins);s.length=0,s.push(...Ee),C=(Vi=(Ui=n.launcher)==null?void 0:Ui.enabled)!=null?Vi:!0,S=(Yi=(Ji=n.launcher)==null?void 0:Ji.autoExpand)!=null?Yi:!1,ee=(Xi=(Gi=n.features)==null?void 0:Gi.showReasoning)!=null?Xi:!0,xe=(Zi=(Ki=n.features)==null?void 0:Ki.showToolCalls)!=null?Zi:!0,we=(el=(Qi=n.features)==null?void 0:Qi.scrollToBottom)!=null?el:{},bt(),ir();let Ce=ne;if(ne=(nl=(tl=n.features)==null?void 0:tl.showEventStreamToggle)!=null?nl:!1,ne&&!Ce){if(le||(ke=new Ko(me),le=new Xo(Le,ke),ke.open().then(()=>le==null?void 0:le.restore()).catch(()=>{}),N.setSSEEventCallback((Y,pt)=>{le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(pt)})})),!et&&st){let Y=(ol=(rl=n.features)==null?void 0:rl.eventStream)==null?void 0:ol.classNames,pt="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"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");et=h("button",pt),et.style.width="28px",et.style.height="28px",et.style.color=wn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Ht=fe("activity","18px","currentColor",1.5);Ht&&et.appendChild(Ht);let Ye=ce.clearChatButtonWrapper,gt=ce.closeButtonWrapper,Yt=Ye||gt;Yt&&Yt.parentNode===st?st.insertBefore(et,Yt):st.appendChild(et),et.addEventListener("click",()=>{pe?_n():nr()})}}else!ne&&Ce&&(_n(),et&&(et.remove(),et=null),le==null||le.clear(),ke==null||ke.destroy(),le=null,ke=null);if(((sl=n.launcher)==null?void 0:sl.enabled)===!1&&x&&(x.destroy(),x=null),((al=n.launcher)==null?void 0:al.enabled)===!1&&$&&($.remove(),$=null),((il=n.launcher)==null?void 0:il.enabled)!==!1&&!x&&!$){let Y=s.find(pt=>pt.renderLauncher);if(Y!=null&&Y.renderLauncher){let pt=Y.renderLauncher({config:n,defaultRenderer:()=>Jo(n,I).element,onToggle:I});pt&&($=pt,e.appendChild($))}$||(x=Jo(n,I),e.appendChild(x.element))}x&&x.update(n),It&&((ll=n.launcher)==null?void 0:ll.title)!==void 0&&(It.textContent=n.launcher.title),Pt&&((cl=n.launcher)==null?void 0:cl.subtitle)!==void 0&&(Pt.textContent=n.launcher.subtitle);let Me=(dl=n.layout)==null?void 0:dl.header;if((Me==null?void 0:Me.layout)!==k&&st){let Y=Me?po(n,Me,{showClose:C,onClose:()=>Wt(!1,"user")}):ur({config:n,showClose:C,onClose:()=>Wt(!1,"user")});st.replaceWith(Y.header),st=Y.header,Ne=Y.iconHolder,It=Y.headerTitle,Pt=Y.headerSubtitle,de=Y.closeButton,k=Me==null?void 0:Me.layout}else if(Me&&(Ne&&(Ne.style.display=Me.showIcon===!1?"none":""),It&&(It.style.display=Me.showTitle===!1?"none":""),Pt&&(Pt.style.display=Me.showSubtitle===!1?"none":""),de&&(de.style.display=Me.showCloseButton===!1?"none":""),ce.clearChatButtonWrapper)){let Y=Me.showClearChat;if(Y!==void 0){ce.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:pt}=ce;pt&&!pt.classList.contains("persona-absolute")&&(Y?pt.classList.remove("persona-ml-auto"):pt.classList.add("persona-ml-auto"))}}let ut=((pl=n.layout)==null?void 0:pl.showHeader)!==!1;st&&(st.style.display=ut?"":"none");let Ke=((ul=n.layout)==null?void 0:ul.showFooter)!==!1;at&&(at.style.display=Ke?"":"none"),Ze(),ir(),C!==w?C?Wt(S,"auto"):(E=!0,Hr()):S!==R&&Wt(S,"auto"),R=S,w=C,B(),Ot();let Re=JSON.stringify(l.toolCall)!==JSON.stringify(m),be=JSON.stringify(n.messageActions)!==JSON.stringify(y),Be=JSON.stringify((ml=n.layout)==null?void 0:ml.messages)!==JSON.stringify(A),At=((gl=n.loadingIndicator)==null?void 0:gl.render)!==(W==null?void 0:W.render)||((fl=n.loadingIndicator)==null?void 0:fl.renderIdle)!==(W==null?void 0:W.renderIdle)||((hl=n.loadingIndicator)==null?void 0:hl.showBubble)!==(W==null?void 0:W.showBubble),Ct=n.iterationDisplay!==H,Jt=((bl=(yl=n.features)==null?void 0:yl.showReasoning)!=null?bl:!0)!==(U!=null?U:!0)||((vl=(xl=n.features)==null?void 0:xl.showToolCalls)!=null?vl:!0)!==(F!=null?F:!0)||JSON.stringify((Cl=n.features)==null?void 0:Cl.toolCallDisplay)!==JSON.stringify(he)||JSON.stringify((wl=n.features)==null?void 0:wl.reasoningDisplay)!==JSON.stringify(Se);(Re||be||Be||At||Ct||Jt)&&N&&(vr++,Rr(ie,N.getMessages(),O));let Ae=(Sl=n.launcher)!=null?Sl:{},yn=(Al=Ae.headerIconHidden)!=null?Al:!1,sn=(Tl=(El=n.layout)==null?void 0:El.header)==null?void 0:Tl.showIcon,Vn=yn||sn===!1,ot=Ae.headerIconName,mt=(Ml=Ae.headerIconSize)!=null?Ml:"48px";if(Ne){let Y=j.querySelector(".persona-border-b-persona-divider"),pt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(Vn)Ne.style.display="none",Y&&pt&&!Y.contains(pt)&&Y.insertBefore(pt,Y.firstChild);else{if(Ne.style.display="",Ne.style.height=mt,Ne.style.width=mt,Y&&pt&&(Y.contains(Ne)?Ne.nextSibling!==pt&&(Ne.remove(),Y.insertBefore(Ne,pt)):Y.insertBefore(Ne,pt)),ot){let Ye=parseFloat(mt)||24,gt=fe(ot,Ye*.6,"#ffffff",2);gt?Ne.replaceChildren(gt):Ne.textContent=(kl=Ae.agentIconText)!=null?kl:"\u{1F4AC}"}else if(Ae.iconUrl){let Ye=Ne.querySelector("img");if(Ye)Ye.src=Ae.iconUrl,Ye.style.height=mt,Ye.style.width=mt;else{let gt=document.createElement("img");gt.src=Ae.iconUrl,gt.alt="",gt.className="persona-rounded-xl persona-object-cover",gt.style.height=mt,gt.style.width=mt,Ne.replaceChildren(gt)}}else{let Ye=Ne.querySelector("svg"),gt=Ne.querySelector("img");(Ye||gt)&&Ne.replaceChildren(),Ne.textContent=(Ll=Ae.agentIconText)!=null?Ll:"\u{1F4AC}"}let Ht=Ne.querySelector("img");Ht&&(Ht.style.height=mt,Ht.style.width=mt)}}let bn=(Pl=(Il=n.layout)==null?void 0:Il.header)==null?void 0:Pl.showTitle,cr=(Rl=(Wl=n.layout)==null?void 0:Wl.header)==null?void 0:Rl.showSubtitle;if(It&&(It.style.display=bn===!1?"none":""),Pt&&(Pt.style.display=cr===!1?"none":""),de){((Bl=(Hl=n.layout)==null?void 0:Hl.header)==null?void 0:Bl.showCloseButton)===!1?de.style.display="none":de.style.display="";let pt=(Dl=Ae.closeButtonSize)!=null?Dl:"32px",Ht=(Nl=Ae.closeButtonPlacement)!=null?Nl:"inline";de.style.height=pt,de.style.width=pt;let{closeButtonWrapper:Ye}=ce,gt=Ht==="top-right",Yt=Ye==null?void 0:Ye.classList.contains("persona-absolute");if(Ye&&gt!==Yt)if(Ye.remove(),gt)Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(Ye);else{let nt=(Ol=(Fl=Ae.clearChat)==null?void 0:Fl.placement)!=null?Ol:"inline",Qt=(_l=($l=Ae.clearChat)==null?void 0:$l.enabled)!=null?_l:!0;Ye.className=Qt&&nt==="inline"?"":"persona-ml-auto";let vn=j.querySelector(".persona-border-b-persona-divider");vn&&vn.appendChild(Ye)}if(de.style.color=Ae.closeButtonColor||wn.actionIconColor,Ae.closeButtonBackgroundColor?(de.style.backgroundColor=Ae.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),Ae.closeButtonBorderWidth||Ae.closeButtonBorderColor){let nt=Ae.closeButtonBorderWidth||"0px",Qt=Ae.closeButtonBorderColor||"transparent";de.style.border=`${nt} solid ${Qt}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");Ae.closeButtonBorderRadius?(de.style.borderRadius=Ae.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),Ae.closeButtonPaddingX?(de.style.paddingLeft=Ae.closeButtonPaddingX,de.style.paddingRight=Ae.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Ae.closeButtonPaddingY?(de.style.paddingTop=Ae.closeButtonPaddingY,de.style.paddingBottom=Ae.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let an=(jl=Ae.closeButtonIconName)!=null?jl:"x",Jn=(zl=Ae.closeButtonIconText)!=null?zl:"\xD7";de.innerHTML="";let mn=fe(an,"20px","currentColor",2);mn?de.appendChild(mn):de.textContent=Jn;let _t=(ql=Ae.closeButtonTooltipText)!=null?ql:"Close chat",Pn=(Ul=Ae.closeButtonShowTooltip)!=null?Ul:!0;if(de.setAttribute("aria-label",_t),Ye&&(Ye._cleanupTooltip&&(Ye._cleanupTooltip(),delete Ye._cleanupTooltip),Pn&&_t)){let nt=null,Qt=()=>{if(nt||!de)return;let Or=de.ownerDocument,Wo=Or.body;if(!Wo)return;nt=er(Or,"div","persona-clear-chat-tooltip"),nt.textContent=_t;let Ro=er(Or,"div");Ro.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ro);let $r=de.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Tr),nt.style.left=`${$r.left+$r.width/2}px`,nt.style.top=`${$r.top-8}px`,nt.style.transform="translate(-50%, -100%)",Wo.appendChild(nt)},vn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Ye.addEventListener("mouseenter",Qt),Ye.addEventListener("mouseleave",vn),de.addEventListener("focus",Qt),de.addEventListener("blur",vn),Ye._cleanupTooltip=()=>{vn(),Ye&&(Ye.removeEventListener("mouseenter",Qt),Ye.removeEventListener("mouseleave",vn)),de&&(de.removeEventListener("focus",Qt),de.removeEventListener("blur",vn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Tt}=ce;if(Je){let Y=(Vl=Ae.clearChat)!=null?Vl:{},pt=(Jl=Y.enabled)!=null?Jl:!0,Ht=(Gl=(Yl=n.layout)==null?void 0:Yl.header)==null?void 0:Gl.showClearChat,Ye=Ht!==void 0?Ht:pt,gt=(Xl=Y.placement)!=null?Xl:"inline";if(Tt){Tt.style.display=Ye?"":"none";let{closeButtonWrapper:Yt}=ce;Yt&&!Yt.classList.contains("persona-absolute")&&(Ye?Yt.classList.remove("persona-ml-auto"):Yt.classList.add("persona-ml-auto"));let an=gt==="top-right",Jn=Tt.classList.contains("persona-absolute");if(an!==Jn&&Ye){if(Tt.remove(),an)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",j.style.position="relative",j.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let _t=j.querySelector(".persona-border-b-persona-divider"),Pn=ce.closeButtonWrapper;_t&&Pn&&Pn.parentElement===_t?_t.insertBefore(Tt,Pn):_t&&_t.appendChild(Tt)}let mn=ce.closeButtonWrapper;mn&&!mn.classList.contains("persona-absolute")&&(an?mn.classList.add("persona-ml-auto"):mn.classList.remove("persona-ml-auto"))}}if(Ye){let Yt=(Kl=Y.size)!=null?Kl:"32px";Je.style.height=Yt,Je.style.width=Yt;let an=(Zl=Y.iconName)!=null?Zl:"refresh-cw",Jn=(Ql=Y.iconColor)!=null?Ql:"";Je.style.color=Jn||wn.actionIconColor,Je.innerHTML="";let mn=fe(an,"20px","currentColor",2);if(mn&&Je.appendChild(mn),Y.backgroundColor?(Je.style.backgroundColor=Y.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let nt=Y.borderWidth||"0px",Qt=Y.borderColor||"transparent";Je.style.border=`${nt} solid ${Qt}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");Y.borderRadius?(Je.style.borderRadius=Y.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),Y.paddingX?(Je.style.paddingLeft=Y.paddingX,Je.style.paddingRight=Y.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),Y.paddingY?(Je.style.paddingTop=Y.paddingY,Je.style.paddingBottom=Y.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let _t=(ec=Y.tooltipText)!=null?ec:"Clear chat",Pn=(tc=Y.showTooltip)!=null?tc:!0;if(Je.setAttribute("aria-label",_t),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),Pn&&_t)){let nt=null,Qt=()=>{if(nt||!Je)return;let Or=Je.ownerDocument,Wo=Or.body;if(!Wo)return;nt=er(Or,"div","persona-clear-chat-tooltip"),nt.textContent=_t;let Ro=er(Or,"div");Ro.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ro);let $r=Je.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Tr),nt.style.left=`${$r.left+$r.width/2}px`,nt.style.top=`${$r.top-8}px`,nt.style.transform="translate(-50%, -100%)",Wo.appendChild(nt)},vn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Tt.addEventListener("mouseenter",Qt),Tt.addEventListener("mouseleave",vn),Je.addEventListener("focus",Qt),Je.addEventListener("blur",vn),Tt._cleanupTooltip=()=>{vn(),Tt&&(Tt.removeEventListener("mouseenter",Qt),Tt.removeEventListener("mouseleave",vn)),Je&&(Je.removeEventListener("focus",Qt),Je.removeEventListener("blur",vn))}}}}let Dr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Qo],Nr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Xr.message,Xr.messageAndClick];T=es({parsers:Dr,handlers:Nr,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),O=Jd(n,T,Z),N.updateConfig(n),Rr(ie,N.getMessages(),O),zn.render(n.suggestionChips,N,Q,void 0,n.suggestionChipsConfig),Ao(),eo(N.isStreaming());let us=((nc=n.voiceRecognition)==null?void 0:nc.enabled)===!0,ms=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gs=((oc=(rc=n.voiceRecognition)==null?void 0:rc.provider)==null?void 0:oc.type)==="runtype";if(us&&(ms||gs))if(!z||!We){let Y=ds(n.voiceRecognition,n.sendButton);Y&&(z=Y.micButton,We=Y.micButtonWrapper,nn.insertBefore(We,kt),z.addEventListener("click",lt),z.disabled=N.isStreaming())}else{let Y=(sc=n.voiceRecognition)!=null?sc:{},pt=(ac=n.sendButton)!=null?ac:{},Ht=(ic=Y.iconName)!=null?ic:"mic",Ye=(lc=pt.size)!=null?lc:"40px",gt=(cc=Y.iconSize)!=null?cc:Ye,Yt=parseFloat(gt)||24;z.style.width=gt,z.style.height=gt,z.style.minWidth=gt,z.style.minHeight=gt;let an=(pc=(dc=Y.iconColor)!=null?dc:pt.textColor)!=null?pc:"currentColor";z.innerHTML="";let Jn=fe(Ht,Yt,an,2);Jn?z.appendChild(Jn):z.textContent="\u{1F3A4}";let mn=(uc=Y.backgroundColor)!=null?uc:pt.backgroundColor;mn?z.style.backgroundColor=mn:z.style.backgroundColor="",an?z.style.color=an:z.style.color="var(--persona-text, #111827)",Y.borderWidth?(z.style.borderWidth=Y.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),Y.borderColor?z.style.borderColor=Y.borderColor:z.style.borderColor="",Y.paddingX?(z.style.paddingLeft=Y.paddingX,z.style.paddingRight=Y.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),Y.paddingY?(z.style.paddingTop=Y.paddingY,z.style.paddingBottom=Y.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let _t=We==null?void 0:We.querySelector(".persona-send-button-tooltip"),Pn=(mc=Y.tooltipText)!=null?mc:"Start voice recognition";if(((gc=Y.showTooltip)!=null?gc:!1)&&Pn)if(_t)_t.textContent=Pn,_t.style.display="";else{let Qt=document.createElement("div");Qt.className="persona-send-button-tooltip",Qt.textContent=Pn,We==null||We.insertBefore(Qt,z)}else _t&&(_t.style.display="none");We.style.display="",z.disabled=N.isStreaming()}else z&&We&&(We.style.display="none",((hc=(fc=n.voiceRecognition)==null?void 0:fc.provider)==null?void 0:hc.type)==="runtype"?N.isVoiceActive()&&N.toggleVoice():Ln&&Un());if(((yc=n.attachments)==null?void 0:yc.enabled)===!0)if(!ht||!ge){let Y=(bc=n.attachments)!=null?bc:{},Ht=(vc=((xc=n.sendButton)!=null?xc:{}).size)!=null?vc:"40px";ae||(ae=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ae.style.display="none",ct.insertBefore(ae,Q)),Oe||(Oe=document.createElement("input"),Oe.type="file",Oe.accept=((Cc=Y.allowedTypes)!=null?Cc:pr).join(","),Oe.multiple=((wc=Y.maxFiles)!=null?wc:4)>1,Oe.style.display="none",Oe.setAttribute("aria-label","Attach files"),ct.insertBefore(Oe,Q)),ht=h("div","persona-send-button-wrapper"),ge=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ge.type="button",ge.setAttribute("aria-label",(Sc=Y.buttonTooltipText)!=null?Sc:"Attach file");let Ye=(Ac=Y.buttonIconName)!=null?Ac:"paperclip",gt=Ht,Yt=parseFloat(gt)||40,an=Math.round(Yt*.6);ge.style.width=gt,ge.style.height=gt,ge.style.minWidth=gt,ge.style.minHeight=gt,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.style.backgroundColor="transparent",ge.style.color="var(--persona-primary, #111827)",ge.style.border="none",ge.style.borderRadius="6px",ge.style.transition="background-color 0.15s ease",ge.addEventListener("mouseenter",()=>{ge.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ge.addEventListener("mouseleave",()=>{ge.style.backgroundColor="transparent"});let Jn=fe(Ye,an,"currentColor",1.5);Jn?ge.appendChild(Jn):ge.textContent="\u{1F4CE}",ge.addEventListener("click",Pn=>{Pn.preventDefault(),Oe==null||Oe.click()}),ht.appendChild(ge);let mn=(Ec=Y.buttonTooltipText)!=null?Ec:"Attach file",_t=h("div","persona-send-button-tooltip");_t.textContent=mn,ht.appendChild(_t),en.append(ht),!He&&Oe&&ae&&(He=Jr.fromConfig(Y),He.setPreviewsContainer(ae),Oe.addEventListener("change",async()=>{He&&(Oe!=null&&Oe.files)&&(await He.handleFileSelect(Oe.files),Oe.value="")})),j.querySelector(".persona-attachment-drop-overlay")||j.appendChild(Yd(Y.dropOverlay))}else{ht.style.display="";let Y=(Tc=n.attachments)!=null?Tc:{};Oe&&(Oe.accept=((Mc=Y.allowedTypes)!=null?Mc:pr).join(","),Oe.multiple=((kc=Y.maxFiles)!=null?kc:4)>1),He&&He.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else ht&&(ht.style.display="none"),He&&He.clearAttachments(),(Lc=j.querySelector(".persona-attachment-drop-overlay"))==null||Lc.remove();let Ut=(Ic=n.sendButton)!=null?Ic:{},fs=(Pc=Ut.useIcon)!=null?Pc:!1,Lo=(Wc=Ut.iconText)!=null?Wc:"\u2191",xn=Ut.iconName,Fn=(Rc=Ut.tooltipText)!=null?Rc:"Send message",ro=(Hc=Ut.showTooltip)!=null?Hc:!1,Io=(Bc=Ut.size)!=null?Bc:"40px",hs=Ut.backgroundColor,Fr=Ut.textColor;if(fs){if(se.style.width=Io,se.style.height=Io,se.style.minWidth=Io,se.style.minHeight=Io,se.style.fontSize="18px",se.style.lineHeight="1",se.innerHTML="",Fr?se.style.color=Fr:se.style.color="var(--persona-button-primary-fg, #ffffff)",xn){let Y=parseFloat(Io)||24,pt=(Fr==null?void 0:Fr.trim())||"currentColor",Ht=fe(xn,Y,pt,2);Ht?se.appendChild(Ht):se.textContent=Lo}else se.textContent=Lo;se.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",hs?(se.style.backgroundColor=hs,se.classList.remove("persona-bg-persona-primary")):(se.style.backgroundColor="",se.classList.add("persona-bg-persona-primary"))}else se.textContent=(Nc=(Dc=n.copy)==null?void 0:Dc.sendButtonLabel)!=null?Nc:"Send",se.style.width="",se.style.height="",se.style.minWidth="",se.style.minHeight="",se.style.fontSize="",se.style.lineHeight="",se.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",hs?(se.style.backgroundColor=hs,se.classList.remove("persona-bg-persona-accent")):se.classList.add("persona-bg-persona-accent"),Fr?se.style.color=Fr:se.classList.add("persona-text-white");Ut.borderWidth?(se.style.borderWidth=Ut.borderWidth,se.style.borderStyle="solid"):(se.style.borderWidth="",se.style.borderStyle=""),Ut.borderColor?se.style.borderColor=Ut.borderColor:se.style.borderColor="",Ut.paddingX?(se.style.paddingLeft=Ut.paddingX,se.style.paddingRight=Ut.paddingX):(se.style.paddingLeft="",se.style.paddingRight=""),Ut.paddingY?(se.style.paddingTop=Ut.paddingY,se.style.paddingBottom=Ut.paddingY):(se.style.paddingTop="",se.style.paddingBottom="");let Po=kt==null?void 0:kt.querySelector(".persona-send-button-tooltip");if(ro&&Fn)if(Po)Po.textContent=Fn,Po.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=Fn,kt==null||kt.insertBefore(Y,se)}else Po&&(Po.style.display="none");let ys=(Fc=n.layout)==null?void 0:Fc.contentMaxWidth;ys?(ie.style.maxWidth=ys,ie.style.marginLeft="auto",ie.style.marginRight="auto",ie.style.width="100%",ct&&(ct.style.maxWidth=ys,ct.style.marginLeft="auto",ct.style.marginRight="auto"),$e&&($e.style.maxWidth=ys,$e.style.marginLeft="auto",$e.style.marginRight="auto")):(ie.style.maxWidth="",ie.style.marginLeft="",ie.style.marginRight="",ie.style.width="",ct&&(ct.style.maxWidth="",ct.style.marginLeft="",ct.style.marginRight=""),$e&&($e.style.maxWidth="",$e.style.marginLeft="",$e.style.marginRight=""));let Ar=(Oc=n.statusIndicator)!=null?Oc:{},Rp=($c=Ar.visible)!=null?$c:!0;if(Bt.style.display=Rp?"":"none",N){let Y=N.getStatus();ft(Bt,(Ht=>{var Ye,gt,Yt,an;return Ht==="idle"?(Ye=Ar.idleText)!=null?Ye:ln.idle:Ht==="connecting"?(gt=Ar.connectingText)!=null?gt:ln.connecting:Ht==="connected"?(Yt=Ar.connectedText)!=null?Yt:ln.connected:Ht==="error"?(an=Ar.errorText)!=null?an:ln.error:ln[Ht]})(Y),Ar,Y)}Bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Hp=Ar.align==="left"?"persona-text-left":Ar.align==="center"?"persona-text-center":"persona-text-right";Bt.classList.add(Hp)},open(){C&&Wt(!0,"api")},close(){C&&Wt(!1,"api")},toggle(){C&&Wt(!E,"api")},clearChat(){cn=!1,N.clearMessages(),Bn.clear(),Cr();try{localStorage.removeItem(bo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bo}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==bo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},T.syncFromMetadata(),le==null||le.clear(),K==null||K.update()},setMessage(l){return!Q||N.isStreaming()?!1:(!E&&C&&Wt(!0,"system"),Q.value=l,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(N.isStreaming())return!1;let m=(l==null?void 0:l.trim())||Q.value.trim();return m?(!E&&C&&Wt(!0,"system"),Q.value="",Q.style.height="auto",N.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return N.isStreaming()?!1:((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(N.isVoiceActive()||(!E&&C&&Wt(!0,"system"),Qe.manuallyDeactivated=!1,hn(),N.toggleVoice().then(()=>{Qe.active=N.isVoiceActive(),Dn("user"),N.isVoiceActive()&&Ve()})),!0):Ln?!0:ko()?(!E&&C&&Wt(!0,"system"),Qe.manuallyDeactivated=!1,hn(),Br("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?N.isVoiceActive()?(N.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,hn(),Dn("user"),rt()}),!0):!1:Ln?(Qe.manuallyDeactivated=!0,hn(),Un("user"),!0):!1},injectMessage(l){return!E&&C&&Wt(!0,"system"),N.injectMessage(l)},injectAssistantMessage(l){!E&&C&&Wt(!0,"system");let m=N.injectAssistantMessage(l);return V&&(V=!1,te&&(clearTimeout(te),te=null),setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)),m},injectUserMessage(l){return!E&&C&&Wt(!0,"system"),N.injectUserMessage(l)},injectSystemMessage(l){return!E&&C&&Wt(!0,"system"),N.injectSystemMessage(l)},injectMessageBatch(l){return!E&&C&&Wt(!0,"system"),N.injectMessageBatch(l)},injectTestMessage(l){!E&&C&&Wt(!0,"system"),N.injectTestEvent(l)},async connectStream(l,m){return N.connectStream(l,m)},__pushEventStreamEvent(l){le&&le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ne||!le||nr()},hideEventStream(){pe&&_n()},isEventStreamVisible(){return pe},showArtifacts(){$n(n)&&(cn=!1,En(),it==null||it.setMobileOpen(!0))},hideArtifacts(){$n(n)&&(cn=!0,En())},upsertArtifact(l){return $n(n)?(cn=!1,N.upsertArtifact(l)):null},selectArtifact(l){$n(n)&&N.selectArtifact(l)},clearArtifacts(){$n(n)&&N.clearArtifacts()},focusInput(){return C&&!E||!Q?!1:(Q.focus(),!0)},async resolveApproval(l,m){let A=N.getMessages().find(L=>{var W;return L.variant==="approval"&&((W=L.approval)==null?void 0:W.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return N.resolveApproval(A.approval,m)},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return C&&E},isVoiceActive(){return Qe.active},getState(){return{open:C&&E,launcherEnabled:C,voiceActive:Qe.active,streaming:N.isStreaming()}},showCSATFeedback(l){!E&&C&&Wt(!0,"system");let m=ie.querySelector(".persona-feedback-container");m&&m.remove();let y=Ys({onSubmit:async(A,L)=>{var W;N.isClientTokenMode()&&await N.submitCSATFeedback(A,L),(W=l==null?void 0:l.onSubmit)==null||W.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});ie.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&C&&Wt(!0,"system");let m=ie.querySelector(".persona-feedback-container");m&&m.remove();let y=Gs({onSubmit:async(A,L)=>{var W;N.isClientTokenMode()&&await N.submitNPSFeedback(A,L),(W=l==null?void 0:l.onSubmit)==null||W.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});ie.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return N.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return N.submitNPSFeedback(l,m)},destroy(){Qn!=null&&(clearInterval(Qn),Qn=null),St.forEach(l=>l()),q.remove(),x==null||x.destroy(),$==null||$.remove(),Mn&&de.removeEventListener("click",Mn)}};if((((Hi=t==null?void 0:t.debugTools)!=null?Hi:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:Vt,getMessages:Vt.getMessages,getStatus:Vt.getStatus,getMetadata:Vt.getPersistentMetadata,updateMetadata:Vt.updatePersistentMetadata,clearHistory:()=>Vt.clearChat(),setVoiceActive:y=>y?Vt.startVoiceRecognition():Vt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,St.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=U=>{let F=U.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Vt.focusInput()};if(window.addEventListener("persona:focusInput",m),St.push(()=>{window.removeEventListener("persona:focusInput",m)}),ne){let U=he=>{let Se=he.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===l)&&Vt.showEventStream()},F=he=>{let Se=he.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===l)&&Vt.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",F),St.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",F)})}let y=U=>{let F=U.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Vt.showArtifacts()},A=U=>{let F=U.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Vt.hideArtifacts()},L=U=>{let F=U.detail;F!=null&&F.instanceId&&F.instanceId!==l||F!=null&&F.artifact&&Vt.upsertArtifact(F.artifact)},W=U=>{let F=U.detail;F!=null&&F.instanceId&&F.instanceId!==l||typeof(F==null?void 0:F.id)=="string"&&Vt.selectArtifact(F.id)},H=U=>{let F=U.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Vt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",H),St.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",H)})}let Nn=Ku(n.persistState);if(Nn&&C){let l=Zu(Nn.storage),m=`${Nn.keyPrefix}widget-open`,y=`${Nn.keyPrefix}widget-voice`,A=`${Nn.keyPrefix}widget-voice-mode`;if(l){let L=((Bi=Nn.persist)==null?void 0:Bi.openState)&&l.getItem(m)==="true",W=((Di=Nn.persist)==null?void 0:Di.voiceState)&&l.getItem(y)==="true",H=((Ni=Nn.persist)==null?void 0:Ni.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{Vt.open(),setTimeout(()=>{var U;if(W||H)Vt.startVoiceRecognition();else if((U=Nn.persist)!=null&&U.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Fi=Nn.persist)!=null&&Fi.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(Oi=Nn.persist)!=null&&Oi.voiceState&&(o.on("voice:state",U=>{l.setItem(y,U.active?"true":"false")}),o.on("user:message",U=>{l.setItem(A,U.viaVoice?"true":"false")})),Nn.clearOnChatClear){let U=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(A)},F=()=>U();window.addEventListener("persona:clear-chat",F),St.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return c&&C&&setTimeout(()=>{Vt.open()},0),Vt};var Qu=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},Gd=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.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"},Fa=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=""},Xd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Fa(e)},Ba=e=>{e.style.transition=""},Da=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=""},Na=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Zs=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},em=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},tm=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},Kd=(e,r,t,n,s,o,a)=>{var v,T,C,S,M,R;let i=On(o),u=i.reveal==="push";em(e,r,t,n,u),tm(e,r,t,n,i.side,u),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 c=e.ownerDocument.defaultView,d=(T=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?T:!0,p=(S=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=p:!1;if(d&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Da(r),Ba(n),Xd(n),Na(t),Zs(s,n),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",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((R=(M=o==null?void 0:o.launcher)==null?void 0:M.zIndex)!=null?R:Cn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.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"),Xd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Da(r),Ba(n),Na(t),Zs(s,n);let w=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":k;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=P,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.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",Ba(n),Fa(n),Zs(s,n);let w=Qu(i.width,e.clientWidth),k=Math.max(0,e.clientWidth),P=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${k+w}px`,r.style.transition=P,r.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${k}px`,t.style.maxWidth=`${k}px`,t.style.minWidth=`${k}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Da(r),Fa(n),Na(t),Zs(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",P=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${k}`,n.style.width=k,n.style.maxWidth=k,n.style.minWidth=k,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||E?"hidden":"visible",n.style.transition=P,w&&(n.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")}},nm=(e,r)=>{let t=e.ownerDocument.createElement("div");return Gd(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Gd(t,n)},destroy(){t.remove()}}},rm=(e,r)=>{var M,R,w,k;let{ownerDocument:t}=e,n=e.parentElement;if(!n)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"),u=t.createElement("div"),c=t.createElement("aside"),d=t.createElement("div"),p=(R=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||R?(k=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?k:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),n.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),On(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Kd(a,i,u,c,d,r,p)}),f.observe(a))},T=()=>{Kd(a,i,u,c,d,r,p),v()},C=a.ownerDocument.defaultView,S=()=>{T()};return C==null||C.addEventListener("resize",S),On(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),T(),{mode:"docked",host:d,shell:a,syncWidgetState(P){let E=P.launcherEnabled?P.open:!0;p!==E&&(p=E,T())},updateConfig(P){var E,V;r=P,((V=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?V:!0)===!1&&(p=!0),T()},destroy(){C==null||C.removeEventListener("resize",S),g(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},ts=(e,r)=>Gt(r)?rm(e,r):nm(e,r);var Oa={},om=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 r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},sm=()=>{try{if(typeof Oa!="undefined"&&Oa.url)return new URL("../widget.css",Oa.url).href}catch{}return null},Zd=(e,r)=>{let t=sm(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.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=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},$a=e=>{var C;let r=om(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=ts(r,s),a,i=[],u=(S,M)=>{var P,E;let w=!((E=(P=M==null?void 0:M.launcher)==null?void 0:P.enabled)!=null?E:!0)||Gt(M),k=n.createElement("div");if(k.setAttribute("data-persona-root","true"),w&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),t){let V=S.attachShadow({mode:"open"});V.appendChild(k),Zd(V,n)}else S.appendChild(k),Zd(S,n);return r.id&&k.setAttribute("data-persona-instance",r.id),k},c=()=>{o.syncWidgetState(a.getState())},d=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let S=u(o.host,s);a=Ks(S,s,{debugTools:e.debugTools}),d()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};p(),(C=e.onReady)==null||C.call(e);let g=S=>{f(),o.destroy(),o=ts(r,S),s=S,p()},v={update(S){var k,P,E,V,te,Z;let M={...s,...S,launcher:{...(k=s==null?void 0:s.launcher)!=null?k:{},...(P=S==null?void 0:S.launcher)!=null?P:{},dock:{...(V=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?V:{},...(Z=(te=S==null?void 0:S.launcher)==null?void 0:te.dock)!=null?Z:{}}}},R=Gt(s),w=Gt(M);if(R!==w){g(M);return}s=M,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},T=new Proxy(v,{get(S,M,R){if(M==="host")return o.host;if(M in S)return Reflect.get(S,M,R);let w=a[M];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=T),T};var rp=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),am=new Set(["button","a","input","select","textarea","details","summary"]),im=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),_a=/\b(product|card|item|listing|result)\b/i,za=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,lm=3e3,cm=100;function op(e){let r=typeof e.className=="string"?e.className:"";if(_a.test(r)||e.id&&_a.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&_a.test(n.value))return!0}return!1}function sp(e){var r;return za.test(((r=e.textContent)!=null?r:"").trim())}function ap(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function dm(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Qd(e){let r=e.match(za);return r?r[0]:null}function ep(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.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 pm(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var um="commerce-card",mm="result-card";function tp(e){return!op(e)||!sp(e)||!ap(e)&&!dm(e)?0:5200}function np(e){var n;return!op(e)||sp(e)||!ap(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var qa=[{id:um,scoreElement(e){return tp(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||za.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,d;if(tp(e)===0)return null;let{title:t,href:n}=ep(e),s=(d=(c=Qd(((u=e.textContent)!=null?u:"").trim()))!=null?c:Qd(r.text))!=null?d:"",o=pm(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
100
- `)}},{id:mm,scoreElement(e){return np(e)},formatSummary(e,r){if(np(e)===0)return null;let{title:t,href:n}=ep(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
101
- `)}}];function gm(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function fm(e){var d,p,f,g,v,T,C,S,M,R,w,k,P;let r=(d=e.options)!=null?d:{},t=(f=(p=r.maxElements)!=null?p:e.maxElements)!=null?f:80,n=(v=(g=r.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",s=(C=(T=r.maxTextLength)!=null?T:e.maxTextLength)!=null?C:200,o=(M=(S=r.visibleOnly)!=null?S:e.visibleOnly)!=null?M:!0,a=(R=r.root)!=null?R:e.root,i=(w=r.mode)!=null?w:"structured",u=(k=r.maxCandidates)!=null?k:Math.max(500,t*10),c=(P=e.rules)!=null?P:qa;return i==="simple"&&e.rules&&e.rules.length>0?(gm(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function ja(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var hm=["data-testid","data-product","data-action","data-id","data-name","data-type"];function ym(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||am.has(r)||t&&im.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function ip(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function bm(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let u=e.getAttribute("role");u&&(r.role=u);for(let c=0;c<e.attributes.length;c++){let d=e.attributes[c];d.name.startsWith("data-")&&(r[d.name]=d.value)}return r}function Ua(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${ja(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of hm){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${ja(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=`${r}.${t.map(a=>ja(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 > ${r}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function xm(e){return e==="static"?cm:lm}function lp(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:Ua(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:ym(e),attributes:bm(e)}}function vm(e,r,t,n){let s=xm(r.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,r,n);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Cm(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function wm(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,d=c.tagName.toLowerCase();if(rp.has(d)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!ip(c)){i=a.nextNode();continue}let p=lp(c,e.maxTextLength),f=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(C=>C==="role");if(!f&&!g){i=a.nextNode();continue}if(n.has(p.selector)){i=a.nextNode();continue}n.add(p.selector);let{score:v,formattingRule:T}=vm(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:v,formattingRule:T}),o+=1}i=a.nextNode()}s.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return p!==f?p-f:d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;Cm(u,c)||u.push(c)}return u.sort((c,d)=>{let p=c.enriched.interactivity==="static"?1:0,f=d.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex}),u.map(c=>{var f;let d;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,t);g&&(d=g)}let p={...c.enriched};return d&&(p.formattedSummary=d),p})}function Sm(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(rp.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!ip(u)){o=s.nextNode();continue}let d=lp(u,e.maxTextLength),p=d.text.length>0,f=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(g=>g==="role");if(!p&&!f){o=s.nextNode();continue}n.has(d.selector)||(n.add(d.selector),t.push(d))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function cp(e={}){var n;let r=fm(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?Sm(r,t):wm(r,t):[]}var Qs=100;function dp(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
99
+ `}if(!A&&!l){let xn="max-height: -moz-available !important; max-height: stretch !important;",Nn=m?"":"padding-top: 1.25em !important;",ro=m?"":`z-index: ${(Lo=(fs=n.launcher)==null?void 0:fs.zIndex)!=null?Lo:Cn} !important;`;z.style.cssText+=xn+Nn+ro}};Zn(),Er(e,n),qs(e,n),Us(e,n);let St=[],Ft=null,Nt=null;St.push(()=>{Ft==null||Ft(),Ft=null,Nt==null||Nt(),Nt=null}),Sn&&St.push(()=>{Sn==null||Sn.disconnect(),Sn=null}),St.push(()=>{dn==null||dn(),dn=null,or(),Et&&(Et.remove(),Et=null),lt==null||lt.element.style.removeProperty("width"),lt==null||lt.element.style.removeProperty("maxWidth")}),re&&St.push(()=>{V!==null&&(cancelAnimationFrame(V),V=null),X==null||X.destroy(),X=null,oe==null||oe.destroy(),oe=null,Me=null});let Tn=null,xr=()=>{Tn&&(Tn(),Tn=null),n.colorScheme==="auto"&&(Tn=Fs(()=>{Er(e,n)}))};xr(),St.push(()=>{Tn&&(Tn(),Tn=null)});let zn=Wd(_e),Mn=null,F,qn=!1,Bn=wd(),vr=0,gn=Ns(),fn=0,ae=null,kn=!1,sr=!1,ns=4,xo=24,rs=80,Qr=new Map,et={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},vo=(Wi=(Pi=n.voiceRecognition)==null?void 0:Pi.autoResume)!=null?Wi:!1,Dn=l=>{o.emit("voice:state",{active:et.active,source:l,timestamp:Date.now()})},hn=()=>{f(l=>({...l,voiceState:{active:et.active,timestamp:Date.now(),manuallyDeactivated:et.manuallyDeactivated}}))},os=()=>{var A,L;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Da(i.voiceState),m=!!l.active,y=Number((L=l.timestamp)!=null?L:0);et.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Gu&&setTimeout(()=>{var R,B;et.active||(et.manuallyDeactivated=!1,((B=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:B.type)==="runtype"?F.toggleVoice().then(()=>{et.active=F.isVoiceActive(),Dn("restore"),F.isVoiceActive()&&Je()}):Br("restore"))},1e3)},ss=()=>F?Jd(F.getMessages()).filter(l=>!l.__skipPersist):[];function Co(l){if(!(a!=null&&a.save))return;let y={messages:l?Jd(l):F?ss():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let ar=null,as=()=>z.querySelector("#persona-scroll-container")||U,Wr=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null),kn=!1},wo=()=>{ae!==null&&(cancelAnimationFrame(ae),ae=null),sr=!1,Wr()},ir=()=>{if(!jt()||pe){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==$&&$.appendChild(pt),Qe();let l=qo(U)>0;pt.style.display=gn.isFollowing()||!l?"none":""},So=()=>{gn.pause()&&(wo(),ir())},Cr=()=>{gn.resume(),ir()},wr=(l=!1)=>{gn.isFollowing()&&(!l&&!qn||(ae!==null&&(cancelAnimationFrame(ae),ae=null),sr=!0,ae=requestAnimationFrame(()=>{ae=null,sr=!1,gn.isFollowing()&&is(as(),l?220:140)})))},is=(l,m=500)=>{let y=l.scrollTop,A=qo(l),L=A-y;if(Math.abs(L)<1){fn=l.scrollTop;return}if(Math.abs(L)>=rs){Wr(),kn=!0,l.scrollTop=A,fn=l.scrollTop,kn=!1;return}Wr();let R=performance.now();kn=!0;let B=N=>1-Math.pow(1-N,3),J=N=>{if(!gn.isFollowing()){Wr();return}let be=qo(l);be!==A&&(A=be,L=A-y);let Ae=N-R,Te=Math.min(Ae/m,1),Se=B(Te),Ie=y+L*Se;l.scrollTop=Ie,fn=l.scrollTop,Te<1?ar=requestAnimationFrame(J):(l.scrollTop=A,fn=l.scrollTop,ar=null,kn=!1)};ar=requestAnimationFrame(J)},ls=l=>{let m=new Map;l.forEach(y=>{let A=Qr.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Qr.clear(),m.forEach((y,A)=>{Qr.set(A,y)})},Rr=(l,m,y)=>{var Te,Se,Ie,qe,mt,Xe;let A=document.createElement("div"),R=(()=>{var Pe;let j=s.find(Be=>Be.renderLoadingIndicator);if(j!=null&&j.renderLoadingIndicator)return j.renderLoadingIndicator;if((Pe=n.loadingIndicator)!=null&&Pe.render)return n.loadingIndicator.render})(),B=(j,Pe)=>Pe==null?!1:typeof Pe=="string"?(j.textContent=Pe,!0):(j.appendChild(Pe),!0),J=new Set;if(m.forEach(j=>{var Jt,on;J.add(j.id);let Pe=Cd(j,vr),Be=Sd(Bn,j.id,Pe);if(Be){A.appendChild(Be.cloneNode(!0));return}let ve=null,Fe=s.find(Ee=>!!(j.variant==="reasoning"&&Ee.renderReasoning||j.variant==="tool"&&Ee.renderToolCall||j.variant==="approval"&&Ee.renderApproval||!j.variant&&Ee.renderMessage)),At=(Jt=n.layout)==null?void 0:Jt.messages;if(Fe)if(j.variant==="reasoning"&&j.reasoning&&Fe.renderReasoning){if(!ne)return;ve=Fe.renderReasoning({message:j,defaultRenderer:()=>ka(j,n),config:n})}else if(j.variant==="tool"&&j.toolCall&&Fe.renderToolCall){if(!Ce)return;ve=Fe.renderToolCall({message:j,defaultRenderer:()=>La(j,n),config:n})}else if(j.variant==="approval"&&j.approval&&Fe.renderApproval){if(n.approval===!1)return;ve=Fe.renderApproval({message:j,defaultRenderer:()=>Ia(j,n),config:n})}else Fe.renderMessage&&(ve=Fe.renderMessage({message:j,defaultRenderer:()=>{let Ee=mo(j,y,At,n.messageActions,ge,{loadingIndicatorRenderer:R,widgetConfig:n});return j.role!=="user"&&Ra(Ee,j,n,F),Ee},config:n}));if(!ve&&j.role==="assistant"&&!j.variant&&n.enableComponentStreaming!==!1&&Gs(j)){let yn=Ks(j);if(yn){let sn=Ys(yn,{config:n,message:j,transform:y});if(sn)if(n.wrapComponentDirectiveInBubble!==!1){let st=document.createElement("div");if(st.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),st.id=`bubble-${j.id}`,st.setAttribute("data-message-id",j.id),j.content&&j.content.trim()){let gt=document.createElement("div");gt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gt.innerHTML=y({text:j.content,message:j,streaming:!!j.streaming,raw:j.rawContent}),st.appendChild(gt)}st.appendChild(sn),ve=st}else{let st=document.createElement("div");if(st.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",st.id=`bubble-${j.id}`,st.setAttribute("data-message-id",j.id),st.setAttribute("data-persona-component-directive","true"),j.content&&j.content.trim()){let gt=document.createElement("div");gt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gt.innerHTML=y({text:j.content,message:j,streaming:!!j.streaming,raw:j.rawContent}),st.appendChild(gt)}st.appendChild(sn),ve=st}}}if(!ve)if(j.variant==="reasoning"&&j.reasoning){if(!ne)return;ve=ka(j,n)}else if(j.variant==="tool"&&j.toolCall){if(!Ce)return;ve=La(j,n)}else if(j.variant==="approval"&&j.approval){if(n.approval===!1)return;ve=Ia(j,n)}else{let Ee=(on=n.layout)==null?void 0:on.messages;Ee!=null&&Ee.renderUserMessage&&j.role==="user"?ve=Ee.renderUserMessage({message:j,config:n,streaming:!!j.streaming}):Ee!=null&&Ee.renderAssistantMessage&&j.role==="assistant"?ve=Ee.renderAssistantMessage({message:j,config:n,streaming:!!j.streaming}):ve=mo(j,y,Ee,n.messageActions,ge,{loadingIndicatorRenderer:R,widgetConfig:n}),j.role!=="user"&&ve&&Ra(ve,j,n,F)}let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id=`wrapper-${j.id}`,Ct.setAttribute("data-wrapper-id",j.id),j.role==="user"&&Ct.classList.add("persona-justify-end"),(ve==null?void 0:ve.getAttribute("data-persona-component-directive"))==="true"&&Ct.classList.add("persona-w-full"),Ct.appendChild(ve),Ad(Bn,j.id,Pe,Ct),A.appendChild(Ct)}),(Se=(Te=n.features)==null?void 0:Te.toolCallDisplay)!=null&&Se.grouped){let j=[],Pe=[];m.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&Ce){Pe.push(Be);return}Pe.length>1&&j.push(Pe),Pe=[]}),Pe.length>1&&j.push(Pe),j.forEach((Be,ve)=>{var sn,Vn;let Fe=Be.map(st=>Array.from(A.children).find(gt=>gt instanceof HTMLElement&&gt.getAttribute("data-wrapper-id")===st.id)).filter(st=>!!st);if(Fe.length<2)return;let At=document.createElement("div");At.className="persona-flex",At.id=`wrapper-tool-group-${ve}-${Be[0].id}`,At.setAttribute("data-wrapper-id",`tool-group-${ve}-${Be[0].id}`);let Ct=document.createElement("div");Ct.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ct.setAttribute("data-persona-tool-group","true");let Jt=document.createElement("div");Jt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let on=`Called ${Be.length} tools`,Ee=(Vn=(sn=n.toolCall)==null?void 0:sn.renderGroupedSummary)==null?void 0:Vn.call(sn,{messages:Be,toolCalls:Be.map(st=>st.toolCall).filter(st=>!!st),defaultSummary:on,config:n});B(Jt,Ee)||(Jt.textContent=on);let yn=document.createElement("div");yn.className="persona-tool-group-stack persona-flex persona-flex-col",Ct.append(Jt,yn),At.appendChild(Ct),Fe[0].before(At),Fe.forEach((st,gt)=>{let bn=document.createElement("div");bn.className="persona-tool-group-item persona-relative",bn.setAttribute("data-persona-tool-group-item","true"),gt<Fe.length-1&&bn.setAttribute("data-persona-tool-group-connector","true"),bn.appendChild(st),yn.appendChild(bn)})})}Ed(Bn,J);let N=m.some(j=>j.role==="assistant"&&j.streaming),be=m[m.length-1],Ae=(be==null?void 0:be.role)==="assistant"&&!be.streaming&&be.variant!=="approval";if(qn&&m.some(j=>j.role==="user")&&!N&&!Ae){let j={config:n,streaming:!0,location:"standalone",defaultRenderer:Gr},Pe=s.find(ve=>ve.renderLoadingIndicator),Be=null;if(Pe!=null&&Pe.renderLoadingIndicator&&(Be=Pe.renderLoadingIndicator(j)),Be===null&&((Ie=n.loadingIndicator)!=null&&Ie.render)&&(Be=n.loadingIndicator.render(j)),Be===null&&(Be=Gr()),Be){let ve=document.createElement("div"),Fe=((qe=n.loadingIndicator)==null?void 0:qe.showBubble)!==!1;ve.className=Fe?["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(" "),ve.setAttribute("data-typing-indicator","true"),ve.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ve.appendChild(Be);let At=document.createElement("div");At.className="persona-flex",At.id="wrapper-typing-indicator",At.setAttribute("data-wrapper-id","typing-indicator"),At.appendChild(ve),A.appendChild(At)}}if(!qn&&m.length>0){let j=m[m.length-1],Pe={config:n,lastMessage:j,messageCount:m.length},Be=s.find(Fe=>Fe.renderIdleIndicator),ve=null;if(Be!=null&&Be.renderIdleIndicator&&(ve=Be.renderIdleIndicator(Pe)),ve===null&&((mt=n.loadingIndicator)!=null&&mt.renderIdle)&&(ve=n.loadingIndicator.renderIdle(Pe)),ve){let Fe=document.createElement("div"),At=((Xe=n.loadingIndicator)==null?void 0:Xe.showBubble)!==!1;Fe.className=At?["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(" "),Fe.setAttribute("data-idle-indicator","true"),Fe.appendChild(ve);let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id="wrapper-idle-indicator",Ct.setAttribute("data-wrapper-id","idle-indicator"),Ct.appendChild(Fe),A.appendChild(Ct)}}vd(l,A)},Hr=()=>{var N,be,Ae,Te,Se;if(!C)return;let l=Gt(n),m=(N=e.ownerDocument.defaultView)!=null?N:window,y=(Ae=(be=n.launcher)==null?void 0:be.mobileBreakpoint)!=null?Ae:640,A=(Se=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?Se:!0,L=m.innerWidth<=y,R=A&&L&&C,B=On(n).reveal;E?(z.style.removeProperty("display"),z.style.display=l?"flex":"",z.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-95","persona-opacity-0"),W.classList.add("persona-scale-100","persona-opacity-100"),x?x.element.style.display="none":_&&(_.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!R?(z.style.removeProperty("display"),z.style.display="flex",z.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(z.style.setProperty("display","none","important"),z.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(z.style.display="",z.classList.add("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100"),W.classList.add("persona-scale-95","persona-opacity-0")),x?x.element.style.display=l?"none":"":_&&(_.style.display=l?"none":""))},Wt=(l,m="user")=>{var R,B;if(!C||E===l)return;let y=E;E=l,Hr();let A=(()=>{var Ie,qe,mt,Xe,j,Pe,Be;let J=(qe=(Ie=n.launcher)==null?void 0:Ie.sidebarMode)!=null?qe:!1,N=(mt=e.ownerDocument.defaultView)!=null?mt:window,be=(j=(Xe=n.launcher)==null?void 0:Xe.mobileFullscreen)!=null?j:!0,Ae=(Be=(Pe=n.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Be:640,Te=N.innerWidth<=Ae,Se=Gt(n)&&be&&Te;return J||be&&Te&&C||Se})();if(E&&A){if(!Ft){let J=e.getRootNode(),N=J instanceof ShadowRoot?J.host:e.closest(".persona-host");N&&(Ft=Ca(N,(B=(R=n.launcher)==null?void 0:R.zIndex)!=null?B:Cn))}Nt||(Nt=wa(e.ownerDocument))}else E||(Ft==null||Ft(),Ft=null,Nt==null||Nt(),Nt=null);E&&(D(),wr(!0));let L={open:E,source:m,timestamp:Date.now()};E&&!y?o.emit("widget:opened",L):!E&&y&&o.emit("widget:closed",L),o.emit("widget:state",{open:E,launcherEnabled:C,voiceActive:et.active,streaming:F.isStreaming()})},eo=l=>{ie.disabled=l,q&&(q.disabled=l),zn.buttons.forEach(m=>{m.disabled=l}),it.dataset.personaComposerStreaming=l?"true":"false",it.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},to=()=>{et.active||ee&&ee.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>to(),200)});let Ao=()=>{var y,A,L,R,B,J,N,be,Ae,Te,Se;Kt.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",je.textContent=(R=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",ee.placeholder=(J=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?J:"How can I help...";let l=U.querySelector("[data-persona-intro-card]");if(l){let Ie=((N=n.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Ie?"":"none",Ie?(U.classList.remove("persona-gap-3"),U.classList.add("persona-gap-6")):(U.classList.remove("persona-gap-6"),U.classList.add("persona-gap-3"))}(Ae=(be=n.sendButton)==null?void 0:be.useIcon)!=null&&Ae||(ie.textContent=(Se=(Te=n.copy)==null?void 0:Te.sendButtonLabel)!=null?Se:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Qn=null,cs=()=>{Qn==null&&(Qn=setInterval(()=>{let l=ce.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Qn),Qn=null;return}let m=Date.now();l.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=vs(m-A))})},100))};if(F=new lo(n,{onMessagesChanged(l){Rr(ce,l,O),cs(),F&&(l.some(L=>L.role==="user")?zn.render([],F,ee,l):zn.render(n.suggestionChips,F,ee,l,n.suggestionChipsConfig)),wr(!qn),ls(l);let m=[...l].reverse().find(A=>A.role==="user"),y=et.lastUserMessageId;m&&m.id!==y&&(et.lastUserMessageId=m.id,o.emit("user:message",m)),et.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Co(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};Ze(Bt,(L=>{var R,B,J,N;return L==="idle"?(R=m.idleText)!=null?R:ln.idle:L==="connecting"?(B=m.connectingText)!=null?B:ln.connecting:L==="connected"?(J=m.connectedText)!=null?J:ln.connected:L==="error"?(N=m.errorText)!=null?N:ln.error:ln[L]})(l),m,l)},onStreamingChanged(l){qn=l,eo(l),F&&Rr(ce,F.getMessages(),O),l||wr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":ot(),Rt();break;case"speaking":ot(),xt();break;default:l==="idle"&&F.isBargeInActive()?(ot(),Je(),q==null||q.setAttribute("aria-label","End voice session")):(et.active=!1,ot(),Dn("system"),hn());break}},onArtifactsState(l){jn=l,En()}}),hr.current=F,((Hi=(Ri=n.voiceRecognition)==null?void 0:Ri.provider)==null?void 0:Hi.type)==="runtype")try{F.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&F.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),oe&&F.setSSEEventCallback((l,m)=>{oe==null||oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=Da(l.metadata),T.syncFromMetadata()),(m=l.messages)!=null&&m.length&&F.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Eo=l=>{var L;l.preventDefault();let m=ee.value.trim(),y=(L=De==null?void 0:De.hasAttachments())!=null?L:!1;if(!m&&!y)return;let A;y&&(A=[],A.push(...De.getContentParts()),m&&A.push(Fo(m))),ee.value="",ee.style.height="auto",F.sendMessage(m,{contentParts:A}),y&&De.clearAttachments()},To=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),ie.click())},Mo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!De)return;let m=Xu(l.clipboardData);m.length!==0&&(l.preventDefault(),await De.handleFiles(m))},pn=null,Ln=!1,lr=null,Ue=null,ko=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Br=(l="user")=>{var R,B,J,N,be,Ae,Te;if(Ln||F.isStreaming())return;let m=ko();if(!m)return;pn=new m;let A=(B=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?B:2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let L=ee.value;pn.onresult=Se=>{let Ie="",qe="";for(let Xe=0;Xe<Se.results.length;Xe++){let j=Se.results[Xe],Pe=j[0].transcript;j.isFinal?Ie+=Pe+" ":qe=Pe}let mt=L+Ie+qe;ee.value=mt,lr&&clearTimeout(lr),(Ie||qe)&&(lr=window.setTimeout(()=>{let Xe=ee.value.trim();Xe&&pn&&Ln&&(Un(),ee.value="",ee.style.height="auto",F.sendMessage(Xe,{viaVoice:!0}))},A))},pn.onerror=Se=>{Se.error!=="no-speech"&&Un()},pn.onend=()=>{if(Ln){let Se=ee.value.trim();Se&&Se!==L.trim()&&(ee.value="",ee.style.height="auto",F.sendMessage(Se,{viaVoice:!0})),Un()}};try{if(pn.start(),Ln=!0,et.active=!0,l!=="system"&&(et.manuallyDeactivated=!1),Dn(l),hn(),q){let Se=(J=n.voiceRecognition)!=null?J:{};Ue={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(N=Se.iconName)!=null?N:"mic",iconSize:parseFloat((Te=(Ae=Se.iconSize)!=null?Ae:(be=n.sendButton)==null?void 0:be.size)!=null?Te:"40")||24};let Ie=Se.recordingBackgroundColor,qe=Se.recordingIconColor,mt=Se.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Ie!=null?Ie:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=qe!=null?qe:"var(--persona-voice-recording-indicator, #ffffff)",qe){let Xe=q.querySelector("svg");Xe&&Xe.setAttribute("stroke",qe)}mt&&(q.style.borderColor=mt),q.setAttribute("aria-label","Stop voice recognition")}}catch{Un("system")}},Un=(l="user")=>{if(Ln){if(Ln=!1,lr&&(clearTimeout(lr),lr=null),pn){try{pn.stop()}catch{}pn=null}if(et.active=!1,Dn(l),hn(),q){if(q.classList.remove("persona-voice-recording"),Ue){q.style.backgroundColor=Ue.backgroundColor,q.style.color=Ue.color,q.style.borderColor=Ue.borderColor;let m=q.querySelector("svg");m&&m.setAttribute("stroke",Ue.color||"currentColor"),Ue=null}q.setAttribute("aria-label","Start voice recognition")}}},ds=(l,m)=>{var j,Pe,Be,ve,Fe,At,Ct,Jt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((j=l==null?void 0:l.provider)==null?void 0:j.type)==="runtype";if(!(y||A))return null;let R=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let J=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",N=(Be=m==null?void 0:m.size)!=null?Be:"40px",be=(ve=l==null?void 0:l.iconSize)!=null?ve:N,Ae=parseFloat(be)||24,Te=(Fe=l==null?void 0:l.backgroundColor)!=null?Fe:m==null?void 0:m.backgroundColor,Se=(At=l==null?void 0:l.iconColor)!=null?At:m==null?void 0:m.textColor;B.style.width=be,B.style.height=be,B.style.minWidth=be,B.style.minHeight=be,B.style.fontSize="18px",B.style.lineHeight="1",Se?B.style.color=Se:B.style.color="var(--persona-text, #111827)";let qe=ye(J,Ae,Se||"currentColor",1.5);qe?B.appendChild(qe):B.textContent="\u{1F3A4}",Te?B.style.backgroundColor=Te:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),R.appendChild(B);let mt=(Ct=l==null?void 0:l.tooltipText)!=null?Ct:"Start voice recognition";if(((Jt=l==null?void 0:l.showTooltip)!=null?Jt:!1)&&mt){let on=h("div","persona-send-button-tooltip");on.textContent=mt,R.appendChild(on)}return{micButton:B,micButtonWrapper:R}},no=()=>{var m,y,A,L,R;if(!q||Ue)return;let l=(m=n.voiceRecognition)!=null?m:{};Ue={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((R=(L=l.iconSize)!=null?L:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},Z=(l,m)=>{var R,B,J,N,be;if(!q)return;let y=q.querySelector("svg");y&&y.remove();let A=(be=Ue==null?void 0:Ue.iconSize)!=null?be:parseFloat((N=(J=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?J:(B=n.sendButton)==null?void 0:B.size)!=null?N:"40")||24,L=ye(l,A,m,1.5);L&&q.appendChild(L)},ze=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Je=()=>{var L;if(!q)return;no();let l=(L=n.voiceRecognition)!=null?L:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,A=l.recordingBorderColor;if(ze(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let R=q.querySelector("svg");R&&R.setAttribute("stroke",y)}A&&(q.style.borderColor=A),q.setAttribute("aria-label","Stop voice recognition")},Rt=()=>{var J,N,be,Ae,Te,Se,Ie,qe;if(!q)return;no();let l=(J=n.voiceRecognition)!=null?J:{},m=F.getVoiceInterruptionMode(),y=(N=l.processingIconName)!=null?N:"loader",A=(Ae=(be=l.processingIconColor)!=null?be:Ue==null?void 0:Ue.color)!=null?Ae:"",L=(Se=(Te=l.processingBackgroundColor)!=null?Te:Ue==null?void 0:Ue.backgroundColor)!=null?Se:"",R=(qe=(Ie=l.processingBorderColor)!=null?Ie:Ue==null?void 0:Ue.borderColor)!=null?qe:"";ze(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=L,q.style.borderColor=R;let B=A||"currentColor";q.style.color=B,Z(y,B),q.setAttribute("aria-label","Processing voice input"),m==="none"&&(q.style.cursor="default")},xt=()=>{var be,Ae,Te,Se,Ie,qe,mt,Xe,j,Pe,Be,ve;if(!q)return;no();let l=(be=n.voiceRecognition)!=null?be:{},m=F.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(Ae=l.speakingIconName)!=null?Ae:y,L=(qe=l.speakingIconColor)!=null?qe:m==="barge-in"?(Se=(Te=l.recordingIconColor)!=null?Te:Ue==null?void 0:Ue.color)!=null?Se:"":(Ie=Ue==null?void 0:Ue.color)!=null?Ie:"",R=(j=l.speakingBackgroundColor)!=null?j:m==="barge-in"?(mt=l.recordingBackgroundColor)!=null?mt:"var(--persona-voice-recording-bg, #ef4444)":(Xe=Ue==null?void 0:Ue.backgroundColor)!=null?Xe:"",B=(ve=l.speakingBorderColor)!=null?ve:m==="barge-in"?(Pe=l.recordingBorderColor)!=null?Pe:"":(Be=Ue==null?void 0:Ue.borderColor)!=null?Be:"";ze(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=R,q.style.borderColor=B;let J=L||"currentColor";q.style.color=J,Z(A,J);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",N),m==="none"&&(q.style.cursor="default"),m==="barge-in"&&q.classList.add("persona-voice-recording")},ot=()=>{var l,m,y;q&&(ze(),Ue&&(q.style.backgroundColor=(l=Ue.backgroundColor)!=null?l:"",q.style.color=(m=Ue.color)!=null?m:"",q.style.borderColor=(y=Ue.borderColor)!=null?y:"",Z(Ue.iconName,Ue.color||"currentColor"),Ue=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},ct=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=F.getVoiceStatus(),A=F.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{et.active=!1,et.manuallyDeactivated=!0,hn(),Dn("user"),ot()});return}F.toggleVoice().then(()=>{et.active=F.isVoiceActive(),et.manuallyDeactivated=!F.isVoiceActive(),hn(),Dn("user"),F.isVoiceActive()?Je():ot()});return}if(Ln){let y=ee.value.trim();et.manuallyDeactivated=!0,hn(),Un("user"),y&&(ee.value="",ee.style.height="auto",F.sendMessage(y))}else et.manuallyDeactivated=!1,hn(),Br("user")};qt=ct,q&&(q.addEventListener("click",ct),St.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),ot()):Un("system"),q&&q.removeEventListener("click",ct)}));let b=o.on("assistant:complete",()=>{vo&&(et.active||et.manuallyDeactivated||vo==="assistant"&&!et.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!et.active&&!et.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.toggleVoice().then(()=>{et.active=F.isVoiceActive(),Dn("auto"),F.isVoiceActive()&&Je()}):Br("auto"))},600))});St.push(b);let Le=o.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});St.push(Le);let I=()=>{Wt(!E,"user")},x=null,_=null;if(C){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>Jo(n,I).element,onToggle:I});m&&(_=m)}_||(x=Jo(n,I))}x?e.appendChild(x.element):_&&e.appendChild(_),Hr(),zn.render(n.suggestionChips,F,ee,void 0,n.suggestionChipsConfig),Ao(),eo(F.isStreaming()),wr(!0),os(),M&&(C?E&&setTimeout(()=>to(),200):setTimeout(()=>to(),0));let D=()=>{var N,be,Ae,Te,Se,Ie,qe,mt,Xe,j,Pe,Be,ve,Fe,At,Ct,Jt,on,Ee,yn,sn,Vn;let l=Gt(n),m=(be=(N=n.launcher)==null?void 0:N.sidebarMode)!=null?be:!1,y=l||m||((Te=(Ae=n.launcher)==null?void 0:Ae.fullHeight)!=null?Te:!1),A=(Se=e.ownerDocument.defaultView)!=null?Se:window,L=(qe=(Ie=n.launcher)==null?void 0:Ie.mobileFullscreen)!=null?qe:!0,R=(Xe=(mt=n.launcher)==null?void 0:mt.mobileBreakpoint)!=null?Xe:640,B=A.innerWidth<=R,J=L&&B&&C;try{if(J){Zn(),Er(e,n);return}if(P&&(P=!1,Zn(),Er(e,n)),!C&&!l){W.style.height="",W.style.width="";return}if(!m&&!l){let st=(Pe=(j=n==null?void 0:n.launcher)==null?void 0:j.width)!=null?Pe:n==null?void 0:n.launcherWidth,gt=st!=null?st:Wn;W.style.width=gt,W.style.maxWidth=gt}if(Xn(),!y){let st=A.innerHeight,gt=64,bn=(ve=(Be=n.launcher)==null?void 0:Be.heightOffset)!=null?ve:0,cr=Math.max(200,st-gt),Ye=Math.min(640,cr),Tt=Math.max(200,Ye-bn);W.style.height=`${Tt}px`}}finally{if(Qe(),Hr(),E&&C){let gt=((Fe=e.ownerDocument.defaultView)!=null?Fe:window).innerWidth<=((Ct=(At=n.launcher)==null?void 0:At.mobileBreakpoint)!=null?Ct:640),bn=(on=(Jt=n.launcher)==null?void 0:Jt.sidebarMode)!=null?on:!1,cr=(yn=(Ee=n.launcher)==null?void 0:Ee.mobileFullscreen)!=null?yn:!0,Ye=Gt(n)&&cr&&gt,Tt=bn||cr&&gt&&C||Ye;if(Tt&&!Nt){let Dr=e.getRootNode(),Fr=Dr instanceof ShadowRoot?Dr.host:e.closest(".persona-host");Fr&&!Ft&&(Ft=Ca(Fr,(Vn=(sn=n.launcher)==null?void 0:sn.zIndex)!=null?Vn:Cn)),Nt=wa(e.ownerDocument)}else Tt||(Ft==null||Ft(),Ft=null,Nt==null||Nt(),Nt=null)}}};D();let fe=(Bi=e.ownerDocument.defaultView)!=null?Bi:window;if(fe.addEventListener("resize",D),St.push(()=>fe.removeEventListener("resize",D)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Qe()});l.observe(it),St.push(()=>l.disconnect())}fn=U.scrollTop;let Ve=()=>{let l=U.scrollTop,{action:m,nextLastScrollTop:y}=Os({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:fn,nearBottom:Uo(U,xo),userScrollThreshold:ns,isAutoScrolling:kn||sr,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(fn=y,m==="resume"){Cr();return}m==="pause"&&So()};U.addEventListener("scroll",Ve,{passive:!0}),St.push(()=>U.removeEventListener("scroll",Ve));let nt=l=>{let m=$s({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Uo(U,xo),resumeWhenNearBottom:!0});m==="pause"?So():m==="resume"&&Cr()};U.addEventListener("wheel",nt,{passive:!0}),St.push(()=>U.removeEventListener("wheel",nt)),pt.addEventListener("click",()=>{U.scrollTop=U.scrollHeight,fn=U.scrollTop,Cr(),wr(!0)}),St.push(()=>pt.remove()),St.push(()=>{wo()});let Ot=()=>{ue&&(Mn&&(ue.removeEventListener("click",Mn),Mn=null),C?(ue.style.display="",Mn=()=>{Wt(!1,"user")},ue.addEventListener("click",Mn)):ue.style.display="none")};Ot(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{F.clearMessages(),Bn.clear(),Cr();try{localStorage.removeItem(bo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bo}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==bo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},T.syncFromMetadata(),oe==null||oe.clear(),X==null||X.update()})})(),dt&&dt.addEventListener("submit",Eo),ee==null||ee.addEventListener("keydown",To),ee==null||ee.addEventListener("paste",Mo);let Xt="persona-attachment-drop-active",$t=0,Ke=()=>{$t=0,$.classList.remove(Xt)},vt=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&De!==null},Zt=l=>{!Qs(l.dataTransfer)||!vt()||($t++,$t===1&&$.classList.add(Xt))},rn=l=>{!Qs(l.dataTransfer)||!vt()||($t--,$t<=0&&Ke())},Dt=l=>{!Qs(l.dataTransfer)||!vt()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},In=l=>{var y;if(!Qs(l.dataTransfer)||!vt())return;l.preventDefault(),l.stopPropagation(),Ke();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&De.handleFiles(m)},Sr=!0;$.addEventListener("dragenter",Zt,Sr),$.addEventListener("dragleave",rn,Sr),e.addEventListener("dragover",Dt,Sr),e.addEventListener("drop",In,Sr);let ps=e.ownerDocument,ei=l=>{vt()&&l.preventDefault()},ti=l=>{vt()&&l.preventDefault()};ps.addEventListener("dragover",ei),ps.addEventListener("drop",ti),St.push(()=>{dt&&dt.removeEventListener("submit",Eo),ee==null||ee.removeEventListener("keydown",To),ee==null||ee.removeEventListener("paste",Mo)}),St.push(()=>{$.removeEventListener("dragenter",Zt,Sr),$.removeEventListener("dragleave",rn,Sr),e.removeEventListener("dragover",Dt,Sr),e.removeEventListener("drop",In,Sr),ps.removeEventListener("dragover",ei),ps.removeEventListener("drop",ti),Ke()}),St.push(()=>{F.cancel()}),x?St.push(()=>{x==null||x.destroy()}):_&&St.push(()=>{_==null||_.remove()});let Vt={update(l){var ji,zi,qi,Ui,Vi,Ji,Yi,Gi,Ki,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Fl,Nl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Yl,Gl,Kl,Xl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Sc,Ac,Ec,Tc,Mc,kc,Lc,Ic,Pc,Wc,Rc,Hc,Bc,Dc,Fc,Nc,Oc,$c,_c,jc;let m=n.toolCall,y=n.messageActions,A=(ji=n.layout)==null?void 0:ji.messages,L=n.colorScheme,R=n.loadingIndicator,B=n.iterationDisplay,J=(zi=n.features)==null?void 0:zi.showReasoning,N=(qi=n.features)==null?void 0:qi.showToolCalls,be=(Ui=n.features)==null?void 0:Ui.toolCallDisplay,Ae=(Vi=n.features)==null?void 0:Vi.reasoningDisplay;n={...n,...l},Zn(),Er(e,n),qs(e,n),Us(e,n),En(),n.colorScheme!==L&&xr();let Te=Zo.getForInstance(n.plugins);s.length=0,s.push(...Te),C=(Yi=(Ji=n.launcher)==null?void 0:Ji.enabled)!=null?Yi:!0,S=(Ki=(Gi=n.launcher)==null?void 0:Gi.autoExpand)!=null?Ki:!1,ne=(Zi=(Xi=n.features)==null?void 0:Xi.showReasoning)!=null?Zi:!0,Ce=(el=(Qi=n.features)==null?void 0:Qi.showToolCalls)!=null?el:!0,xe=(nl=(tl=n.features)==null?void 0:tl.scrollToBottom)!=null?nl:{},bt(),ir();let Se=re;if(re=(ol=(rl=n.features)==null?void 0:rl.showEventStreamToggle)!=null?ol:!1,re&&!Se){if(oe||(Me=new Xo(me),oe=new Ko(ke,Me),Me.open().then(()=>oe==null?void 0:oe.restore()).catch(()=>{}),F.setSSEEventCallback((Y,ut)=>{oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(ut)})})),!tt&&at){let Y=(al=(sl=n.features)==null?void 0:sl.eventStream)==null?void 0:al.classNames,ut="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"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");tt=h("button",ut),tt.style.width="28px",tt.style.height="28px",tt.style.color=wn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Ht=ye("activity","18px","currentColor",1.5);Ht&&tt.appendChild(Ht);let Ge=se.clearChatButtonWrapper,ft=se.closeButtonWrapper,Yt=Ge||ft;Yt&&Yt.parentNode===at?at.insertBefore(tt,Yt):at.appendChild(tt),tt.addEventListener("click",()=>{pe?_n():nr()})}}else!re&&Se&&(_n(),tt&&(tt.remove(),tt=null),oe==null||oe.clear(),Me==null||Me.destroy(),oe=null,Me=null);if(((il=n.launcher)==null?void 0:il.enabled)===!1&&x&&(x.destroy(),x=null),((ll=n.launcher)==null?void 0:ll.enabled)===!1&&_&&(_.remove(),_=null),((cl=n.launcher)==null?void 0:cl.enabled)!==!1&&!x&&!_){let Y=s.find(ut=>ut.renderLauncher);if(Y!=null&&Y.renderLauncher){let ut=Y.renderLauncher({config:n,defaultRenderer:()=>Jo(n,I).element,onToggle:I});ut&&(_=ut,e.appendChild(_))}_||(x=Jo(n,I),e.appendChild(x.element))}x&&x.update(n),It&&((dl=n.launcher)==null?void 0:dl.title)!==void 0&&(It.textContent=n.launcher.title),Pt&&((pl=n.launcher)==null?void 0:pl.subtitle)!==void 0&&(Pt.textContent=n.launcher.subtitle);let Ie=(ul=n.layout)==null?void 0:ul.header;if((Ie==null?void 0:Ie.layout)!==k&&at){let Y=Ie?po(n,Ie,{showClose:C,onClose:()=>Wt(!1,"user")}):ur({config:n,showClose:C,onClose:()=>Wt(!1,"user")});at.replaceWith(Y.header),at=Y.header,Ne=Y.iconHolder,It=Y.headerTitle,Pt=Y.headerSubtitle,ue=Y.closeButton,k=Ie==null?void 0:Ie.layout}else if(Ie&&(Ne&&(Ne.style.display=Ie.showIcon===!1?"none":""),It&&(It.style.display=Ie.showTitle===!1?"none":""),Pt&&(Pt.style.display=Ie.showSubtitle===!1?"none":""),ue&&(ue.style.display=Ie.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let Y=Ie.showClearChat;if(Y!==void 0){se.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:ut}=se;ut&&!ut.classList.contains("persona-absolute")&&(Y?ut.classList.remove("persona-ml-auto"):ut.classList.add("persona-ml-auto"))}}let mt=((ml=n.layout)==null?void 0:ml.showHeader)!==!1;at&&(at.style.display=mt?"":"none");let Xe=((gl=n.layout)==null?void 0:gl.showFooter)!==!1;it&&(it.style.display=Xe?"":"none"),Qe(),ir(),C!==w?C?Wt(S,"auto"):(E=!0,Hr()):S!==H&&Wt(S,"auto"),H=S,w=C,D(),Ot();let Be=JSON.stringify(l.toolCall)!==JSON.stringify(m),ve=JSON.stringify(n.messageActions)!==JSON.stringify(y),Fe=JSON.stringify((fl=n.layout)==null?void 0:fl.messages)!==JSON.stringify(A),At=((hl=n.loadingIndicator)==null?void 0:hl.render)!==(R==null?void 0:R.render)||((yl=n.loadingIndicator)==null?void 0:yl.renderIdle)!==(R==null?void 0:R.renderIdle)||((bl=n.loadingIndicator)==null?void 0:bl.showBubble)!==(R==null?void 0:R.showBubble),Ct=n.iterationDisplay!==B,Jt=((vl=(xl=n.features)==null?void 0:xl.showReasoning)!=null?vl:!0)!==(J!=null?J:!0)||((wl=(Cl=n.features)==null?void 0:Cl.showToolCalls)!=null?wl:!0)!==(N!=null?N:!0)||JSON.stringify((Sl=n.features)==null?void 0:Sl.toolCallDisplay)!==JSON.stringify(be)||JSON.stringify((Al=n.features)==null?void 0:Al.reasoningDisplay)!==JSON.stringify(Ae);(Be||ve||Fe||At||Ct||Jt)&&F&&(vr++,Rr(ce,F.getMessages(),O));let Ee=(El=n.launcher)!=null?El:{},yn=(Tl=Ee.headerIconHidden)!=null?Tl:!1,sn=(kl=(Ml=n.layout)==null?void 0:Ml.header)==null?void 0:kl.showIcon,Vn=yn||sn===!1,st=Ee.headerIconName,gt=(Ll=Ee.headerIconSize)!=null?Ll:"48px";if(Ne){let Y=$.querySelector(".persona-border-b-persona-divider"),ut=Y==null?void 0:Y.querySelector(".persona-flex-col");if(Vn)Ne.style.display="none",Y&&ut&&!Y.contains(ut)&&Y.insertBefore(ut,Y.firstChild);else{if(Ne.style.display="",Ne.style.height=gt,Ne.style.width=gt,Y&&ut&&(Y.contains(Ne)?Ne.nextSibling!==ut&&(Ne.remove(),Y.insertBefore(Ne,ut)):Y.insertBefore(Ne,ut)),st){let Ge=parseFloat(gt)||24,ft=ye(st,Ge*.6,"#ffffff",2);ft?Ne.replaceChildren(ft):Ne.textContent=(Il=Ee.agentIconText)!=null?Il:"\u{1F4AC}"}else if(Ee.iconUrl){let Ge=Ne.querySelector("img");if(Ge)Ge.src=Ee.iconUrl,Ge.style.height=gt,Ge.style.width=gt;else{let ft=document.createElement("img");ft.src=Ee.iconUrl,ft.alt="",ft.className="persona-rounded-xl persona-object-cover",ft.style.height=gt,ft.style.width=gt,Ne.replaceChildren(ft)}}else{let Ge=Ne.querySelector("svg"),ft=Ne.querySelector("img");(Ge||ft)&&Ne.replaceChildren(),Ne.textContent=(Pl=Ee.agentIconText)!=null?Pl:"\u{1F4AC}"}let Ht=Ne.querySelector("img");Ht&&(Ht.style.height=gt,Ht.style.width=gt)}}let bn=(Rl=(Wl=n.layout)==null?void 0:Wl.header)==null?void 0:Rl.showTitle,cr=(Bl=(Hl=n.layout)==null?void 0:Hl.header)==null?void 0:Bl.showSubtitle;if(It&&(It.style.display=bn===!1?"none":""),Pt&&(Pt.style.display=cr===!1?"none":""),ue){((Fl=(Dl=n.layout)==null?void 0:Dl.header)==null?void 0:Fl.showCloseButton)===!1?ue.style.display="none":ue.style.display="";let ut=(Nl=Ee.closeButtonSize)!=null?Nl:"32px",Ht=(Ol=Ee.closeButtonPlacement)!=null?Ol:"inline";ue.style.height=ut,ue.style.width=ut;let{closeButtonWrapper:Ge}=se,ft=Ht==="top-right",Yt=Ge==null?void 0:Ge.classList.contains("persona-absolute");if(Ge&&ft!==Yt)if(Ge.remove(),ft)Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",$.style.position="relative",$.appendChild(Ge);else{let rt=(_l=($l=Ee.clearChat)==null?void 0:$l.placement)!=null?_l:"inline",Qt=(zl=(jl=Ee.clearChat)==null?void 0:jl.enabled)!=null?zl:!0;Ge.className=Qt&&rt==="inline"?"":"persona-ml-auto";let vn=$.querySelector(".persona-border-b-persona-divider");vn&&vn.appendChild(Ge)}if(ue.style.color=Ee.closeButtonColor||wn.actionIconColor,Ee.closeButtonBackgroundColor?(ue.style.backgroundColor=Ee.closeButtonBackgroundColor,ue.classList.remove("hover:persona-bg-gray-100")):(ue.style.backgroundColor="",ue.classList.add("hover:persona-bg-gray-100")),Ee.closeButtonBorderWidth||Ee.closeButtonBorderColor){let rt=Ee.closeButtonBorderWidth||"0px",Qt=Ee.closeButtonBorderColor||"transparent";ue.style.border=`${rt} solid ${Qt}`,ue.classList.remove("persona-border-none")}else ue.style.border="",ue.classList.add("persona-border-none");Ee.closeButtonBorderRadius?(ue.style.borderRadius=Ee.closeButtonBorderRadius,ue.classList.remove("persona-rounded-full")):(ue.style.borderRadius="",ue.classList.add("persona-rounded-full")),Ee.closeButtonPaddingX?(ue.style.paddingLeft=Ee.closeButtonPaddingX,ue.style.paddingRight=Ee.closeButtonPaddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Ee.closeButtonPaddingY?(ue.style.paddingTop=Ee.closeButtonPaddingY,ue.style.paddingBottom=Ee.closeButtonPaddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let an=(ql=Ee.closeButtonIconName)!=null?ql:"x",Jn=(Ul=Ee.closeButtonIconText)!=null?Ul:"\xD7";ue.innerHTML="";let mn=ye(an,"20px","currentColor",2);mn?ue.appendChild(mn):ue.textContent=Jn;let _t=(Vl=Ee.closeButtonTooltipText)!=null?Vl:"Close chat",Pn=(Jl=Ee.closeButtonShowTooltip)!=null?Jl:!0;if(ue.setAttribute("aria-label",_t),Ge&&(Ge._cleanupTooltip&&(Ge._cleanupTooltip(),delete Ge._cleanupTooltip),Pn&&_t)){let rt=null,Qt=()=>{if(rt||!ue)return;let Or=ue.ownerDocument,Wo=Or.body;if(!Wo)return;rt=er(Or,"div","persona-clear-chat-tooltip"),rt.textContent=_t;let Ro=er(Or,"div");Ro.className="persona-clear-chat-tooltip-arrow",rt.appendChild(Ro);let $r=ue.getBoundingClientRect();rt.style.position="fixed",rt.style.zIndex=String(Tr),rt.style.left=`${$r.left+$r.width/2}px`,rt.style.top=`${$r.top-8}px`,rt.style.transform="translate(-50%, -100%)",Wo.appendChild(rt)},vn=()=>{rt&&rt.parentNode&&(rt.parentNode.removeChild(rt),rt=null)};Ge.addEventListener("mouseenter",Qt),Ge.addEventListener("mouseleave",vn),ue.addEventListener("focus",Qt),ue.addEventListener("blur",vn),Ge._cleanupTooltip=()=>{vn(),Ge&&(Ge.removeEventListener("mouseenter",Qt),Ge.removeEventListener("mouseleave",vn)),ue&&(ue.removeEventListener("focus",Qt),ue.removeEventListener("blur",vn))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Tt}=se;if(Ye){let Y=(Yl=Ee.clearChat)!=null?Yl:{},ut=(Gl=Y.enabled)!=null?Gl:!0,Ht=(Xl=(Kl=n.layout)==null?void 0:Kl.header)==null?void 0:Xl.showClearChat,Ge=Ht!==void 0?Ht:ut,ft=(Zl=Y.placement)!=null?Zl:"inline";if(Tt){Tt.style.display=Ge?"":"none";let{closeButtonWrapper:Yt}=se;Yt&&!Yt.classList.contains("persona-absolute")&&(Ge?Yt.classList.remove("persona-ml-auto"):Yt.classList.add("persona-ml-auto"));let an=ft==="top-right",Jn=Tt.classList.contains("persona-absolute");if(an!==Jn&&Ge){if(Tt.remove(),an)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",$.style.position="relative",$.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let _t=$.querySelector(".persona-border-b-persona-divider"),Pn=se.closeButtonWrapper;_t&&Pn&&Pn.parentElement===_t?_t.insertBefore(Tt,Pn):_t&&_t.appendChild(Tt)}let mn=se.closeButtonWrapper;mn&&!mn.classList.contains("persona-absolute")&&(an?mn.classList.add("persona-ml-auto"):mn.classList.remove("persona-ml-auto"))}}if(Ge){let Yt=(Ql=Y.size)!=null?Ql:"32px";Ye.style.height=Yt,Ye.style.width=Yt;let an=(ec=Y.iconName)!=null?ec:"refresh-cw",Jn=(tc=Y.iconColor)!=null?tc:"";Ye.style.color=Jn||wn.actionIconColor,Ye.innerHTML="";let mn=ye(an,"20px","currentColor",2);if(mn&&Ye.appendChild(mn),Y.backgroundColor?(Ye.style.backgroundColor=Y.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let rt=Y.borderWidth||"0px",Qt=Y.borderColor||"transparent";Ye.style.border=`${rt} solid ${Qt}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");Y.borderRadius?(Ye.style.borderRadius=Y.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),Y.paddingX?(Ye.style.paddingLeft=Y.paddingX,Ye.style.paddingRight=Y.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),Y.paddingY?(Ye.style.paddingTop=Y.paddingY,Ye.style.paddingBottom=Y.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let _t=(nc=Y.tooltipText)!=null?nc:"Clear chat",Pn=(rc=Y.showTooltip)!=null?rc:!0;if(Ye.setAttribute("aria-label",_t),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),Pn&&_t)){let rt=null,Qt=()=>{if(rt||!Ye)return;let Or=Ye.ownerDocument,Wo=Or.body;if(!Wo)return;rt=er(Or,"div","persona-clear-chat-tooltip"),rt.textContent=_t;let Ro=er(Or,"div");Ro.className="persona-clear-chat-tooltip-arrow",rt.appendChild(Ro);let $r=Ye.getBoundingClientRect();rt.style.position="fixed",rt.style.zIndex=String(Tr),rt.style.left=`${$r.left+$r.width/2}px`,rt.style.top=`${$r.top-8}px`,rt.style.transform="translate(-50%, -100%)",Wo.appendChild(rt)},vn=()=>{rt&&rt.parentNode&&(rt.parentNode.removeChild(rt),rt=null)};Tt.addEventListener("mouseenter",Qt),Tt.addEventListener("mouseleave",vn),Ye.addEventListener("focus",Qt),Ye.addEventListener("blur",vn),Tt._cleanupTooltip=()=>{vn(),Tt&&(Tt.removeEventListener("mouseenter",Qt),Tt.removeEventListener("mouseleave",vn)),Ye&&(Ye.removeEventListener("focus",Qt),Ye.removeEventListener("blur",vn))}}}}let Dr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Qo],Fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Kr.message,Kr.messageAndClick];T=es({parsers:Dr,handlers:Fr,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),O=Yd(n,T,K),F.updateConfig(n),Rr(ce,F.getMessages(),O),zn.render(n.suggestionChips,F,ee,void 0,n.suggestionChipsConfig),Ao(),eo(F.isStreaming());let us=((oc=n.voiceRecognition)==null?void 0:oc.enabled)===!0,ms=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gs=((ac=(sc=n.voiceRecognition)==null?void 0:sc.provider)==null?void 0:ac.type)==="runtype";if(us&&(ms||gs))if(!q||!He){let Y=ds(n.voiceRecognition,n.sendButton);Y&&(q=Y.micButton,He=Y.micButtonWrapper,nn.insertBefore(He,kt),q.addEventListener("click",ct),q.disabled=F.isStreaming())}else{let Y=(ic=n.voiceRecognition)!=null?ic:{},ut=(lc=n.sendButton)!=null?lc:{},Ht=(cc=Y.iconName)!=null?cc:"mic",Ge=(dc=ut.size)!=null?dc:"40px",ft=(pc=Y.iconSize)!=null?pc:Ge,Yt=parseFloat(ft)||24;q.style.width=ft,q.style.height=ft,q.style.minWidth=ft,q.style.minHeight=ft;let an=(mc=(uc=Y.iconColor)!=null?uc:ut.textColor)!=null?mc:"currentColor";q.innerHTML="";let Jn=ye(Ht,Yt,an,2);Jn?q.appendChild(Jn):q.textContent="\u{1F3A4}";let mn=(gc=Y.backgroundColor)!=null?gc:ut.backgroundColor;mn?q.style.backgroundColor=mn:q.style.backgroundColor="",an?q.style.color=an:q.style.color="var(--persona-text, #111827)",Y.borderWidth?(q.style.borderWidth=Y.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),Y.borderColor?q.style.borderColor=Y.borderColor:q.style.borderColor="",Y.paddingX?(q.style.paddingLeft=Y.paddingX,q.style.paddingRight=Y.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),Y.paddingY?(q.style.paddingTop=Y.paddingY,q.style.paddingBottom=Y.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let _t=He==null?void 0:He.querySelector(".persona-send-button-tooltip"),Pn=(fc=Y.tooltipText)!=null?fc:"Start voice recognition";if(((hc=Y.showTooltip)!=null?hc:!1)&&Pn)if(_t)_t.textContent=Pn,_t.style.display="";else{let Qt=document.createElement("div");Qt.className="persona-send-button-tooltip",Qt.textContent=Pn,He==null||He.insertBefore(Qt,q)}else _t&&(_t.style.display="none");He.style.display="",q.disabled=F.isStreaming()}else q&&He&&(He.style.display="none",((bc=(yc=n.voiceRecognition)==null?void 0:yc.provider)==null?void 0:bc.type)==="runtype"?F.isVoiceActive()&&F.toggleVoice():Ln&&Un());if(((xc=n.attachments)==null?void 0:xc.enabled)===!0)if(!ht||!he){let Y=(vc=n.attachments)!=null?vc:{},Ht=(wc=((Cc=n.sendButton)!=null?Cc:{}).size)!=null?wc:"40px";le||(le=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),le.style.display="none",dt.insertBefore(le,ee)),$e||($e=document.createElement("input"),$e.type="file",$e.accept=((Sc=Y.allowedTypes)!=null?Sc:pr).join(","),$e.multiple=((Ac=Y.maxFiles)!=null?Ac:4)>1,$e.style.display="none",$e.setAttribute("aria-label","Attach files"),dt.insertBefore($e,ee)),ht=h("div","persona-send-button-wrapper"),he=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),he.type="button",he.setAttribute("aria-label",(Ec=Y.buttonTooltipText)!=null?Ec:"Attach file");let Ge=(Tc=Y.buttonIconName)!=null?Tc:"paperclip",ft=Ht,Yt=parseFloat(ft)||40,an=Math.round(Yt*.6);he.style.width=ft,he.style.height=ft,he.style.minWidth=ft,he.style.minHeight=ft,he.style.fontSize="18px",he.style.lineHeight="1",he.style.backgroundColor="transparent",he.style.color="var(--persona-primary, #111827)",he.style.border="none",he.style.borderRadius="6px",he.style.transition="background-color 0.15s ease",he.addEventListener("mouseenter",()=>{he.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),he.addEventListener("mouseleave",()=>{he.style.backgroundColor="transparent"});let Jn=ye(Ge,an,"currentColor",1.5);Jn?he.appendChild(Jn):he.textContent="\u{1F4CE}",he.addEventListener("click",Pn=>{Pn.preventDefault(),$e==null||$e.click()}),ht.appendChild(he);let mn=(Mc=Y.buttonTooltipText)!=null?Mc:"Attach file",_t=h("div","persona-send-button-tooltip");_t.textContent=mn,ht.appendChild(_t),en.append(ht),!De&&$e&&le&&(De=Jr.fromConfig(Y),De.setPreviewsContainer(le),$e.addEventListener("change",async()=>{De&&($e!=null&&$e.files)&&(await De.handleFileSelect($e.files),$e.value="")})),$.querySelector(".persona-attachment-drop-overlay")||$.appendChild(Gd(Y.dropOverlay))}else{ht.style.display="";let Y=(kc=n.attachments)!=null?kc:{};$e&&($e.accept=((Lc=Y.allowedTypes)!=null?Lc:pr).join(","),$e.multiple=((Ic=Y.maxFiles)!=null?Ic:4)>1),De&&De.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else ht&&(ht.style.display="none"),De&&De.clearAttachments(),(Pc=$.querySelector(".persona-attachment-drop-overlay"))==null||Pc.remove();let Ut=(Wc=n.sendButton)!=null?Wc:{},fs=(Rc=Ut.useIcon)!=null?Rc:!1,Lo=(Hc=Ut.iconText)!=null?Hc:"\u2191",xn=Ut.iconName,Nn=(Bc=Ut.tooltipText)!=null?Bc:"Send message",ro=(Dc=Ut.showTooltip)!=null?Dc:!1,Io=(Fc=Ut.size)!=null?Fc:"40px",hs=Ut.backgroundColor,Nr=Ut.textColor;if(fs){if(ie.style.width=Io,ie.style.height=Io,ie.style.minWidth=Io,ie.style.minHeight=Io,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.innerHTML="",Nr?ie.style.color=Nr:ie.style.color="var(--persona-button-primary-fg, #ffffff)",xn){let Y=parseFloat(Io)||24,ut=(Nr==null?void 0:Nr.trim())||"currentColor",Ht=ye(xn,Y,ut,2);Ht?ie.appendChild(Ht):ie.textContent=Lo}else ie.textContent=Lo;ie.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",hs?(ie.style.backgroundColor=hs,ie.classList.remove("persona-bg-persona-primary")):(ie.style.backgroundColor="",ie.classList.add("persona-bg-persona-primary"))}else ie.textContent=(Oc=(Nc=n.copy)==null?void 0:Nc.sendButtonLabel)!=null?Oc:"Send",ie.style.width="",ie.style.height="",ie.style.minWidth="",ie.style.minHeight="",ie.style.fontSize="",ie.style.lineHeight="",ie.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",hs?(ie.style.backgroundColor=hs,ie.classList.remove("persona-bg-persona-accent")):ie.classList.add("persona-bg-persona-accent"),Nr?ie.style.color=Nr:ie.classList.add("persona-text-white");Ut.borderWidth?(ie.style.borderWidth=Ut.borderWidth,ie.style.borderStyle="solid"):(ie.style.borderWidth="",ie.style.borderStyle=""),Ut.borderColor?ie.style.borderColor=Ut.borderColor:ie.style.borderColor="",Ut.paddingX?(ie.style.paddingLeft=Ut.paddingX,ie.style.paddingRight=Ut.paddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),Ut.paddingY?(ie.style.paddingTop=Ut.paddingY,ie.style.paddingBottom=Ut.paddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let Po=kt==null?void 0:kt.querySelector(".persona-send-button-tooltip");if(ro&&Nn)if(Po)Po.textContent=Nn,Po.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=Nn,kt==null||kt.insertBefore(Y,ie)}else Po&&(Po.style.display="none");let ys=($c=n.layout)==null?void 0:$c.contentMaxWidth;ys?(ce.style.maxWidth=ys,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",dt&&(dt.style.maxWidth=ys,dt.style.marginLeft="auto",dt.style.marginRight="auto"),_e&&(_e.style.maxWidth=ys,_e.style.marginLeft="auto",_e.style.marginRight="auto")):(ce.style.maxWidth="",ce.style.marginLeft="",ce.style.marginRight="",ce.style.width="",dt&&(dt.style.maxWidth="",dt.style.marginLeft="",dt.style.marginRight=""),_e&&(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight=""));let Ar=(_c=n.statusIndicator)!=null?_c:{},Hp=(jc=Ar.visible)!=null?jc:!0;if(Bt.style.display=Hp?"":"none",F){let Y=F.getStatus();Ze(Bt,(Ht=>{var Ge,ft,Yt,an;return Ht==="idle"?(Ge=Ar.idleText)!=null?Ge:ln.idle:Ht==="connecting"?(ft=Ar.connectingText)!=null?ft:ln.connecting:Ht==="connected"?(Yt=Ar.connectedText)!=null?Yt:ln.connected:Ht==="error"?(an=Ar.errorText)!=null?an:ln.error:ln[Ht]})(Y),Ar,Y)}Bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Bp=Ar.align==="left"?"persona-text-left":Ar.align==="center"?"persona-text-center":"persona-text-right";Bt.classList.add(Bp)},open(){C&&Wt(!0,"api")},close(){C&&Wt(!1,"api")},toggle(){C&&Wt(!E,"api")},clearChat(){cn=!1,F.clearMessages(),Bn.clear(),Cr();try{localStorage.removeItem(bo),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bo}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==bo)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},T.syncFromMetadata(),oe==null||oe.clear(),X==null||X.update()},setMessage(l){return!ee||F.isStreaming()?!1:(!E&&C&&Wt(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let m=(l==null?void 0:l.trim())||ee.value.trim();return m?(!E&&C&&Wt(!0,"system"),ee.value="",ee.style.height="auto",F.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return F.isStreaming()?!1:((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(F.isVoiceActive()||(!E&&C&&Wt(!0,"system"),et.manuallyDeactivated=!1,hn(),F.toggleVoice().then(()=>{et.active=F.isVoiceActive(),Dn("user"),F.isVoiceActive()&&Je()})),!0):Ln?!0:ko()?(!E&&C&&Wt(!0,"system"),et.manuallyDeactivated=!1,hn(),Br("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{et.active=!1,et.manuallyDeactivated=!0,hn(),Dn("user"),ot()}),!0):!1:Ln?(et.manuallyDeactivated=!0,hn(),Un("user"),!0):!1},injectMessage(l){return!E&&C&&Wt(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!E&&C&&Wt(!0,"system");let m=F.injectAssistantMessage(l);return G&&(G=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),m},injectUserMessage(l){return!E&&C&&Wt(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!E&&C&&Wt(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!E&&C&&Wt(!0,"system"),F.injectMessageBatch(l)},injectTestMessage(l){!E&&C&&Wt(!0,"system"),F.injectTestEvent(l)},async connectStream(l,m){return F.connectStream(l,m)},__pushEventStreamEvent(l){oe&&oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!re||!oe||nr()},hideEventStream(){pe&&_n()},isEventStreamVisible(){return pe},showArtifacts(){$n(n)&&(cn=!1,En(),lt==null||lt.setMobileOpen(!0))},hideArtifacts(){$n(n)&&(cn=!0,En())},upsertArtifact(l){return $n(n)?(cn=!1,F.upsertArtifact(l)):null},selectArtifact(l){$n(n)&&F.selectArtifact(l)},clearArtifacts(){$n(n)&&F.clearArtifacts()},focusInput(){return C&&!E||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,m){let A=F.getMessages().find(L=>{var R;return L.variant==="approval"&&((R=L.approval)==null?void 0:R.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return F.resolveApproval(A.approval,m)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return C&&E},isVoiceActive(){return et.active},getState(){return{open:C&&E,launcherEnabled:C,voiceActive:et.active,streaming:F.isStreaming()}},showCSATFeedback(l){!E&&C&&Wt(!0,"system");let m=ce.querySelector(".persona-feedback-container");m&&m.remove();let y=Xs({onSubmit:async(A,L)=>{var R;F.isClientTokenMode()&&await F.submitCSATFeedback(A,L),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});ce.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&C&&Wt(!0,"system");let m=ce.querySelector(".persona-feedback-container");m&&m.remove();let y=Zs({onSubmit:async(A,L)=>{var R;F.isClientTokenMode()&&await F.submitNPSFeedback(A,L),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});ce.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return F.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return F.submitNPSFeedback(l,m)},destroy(){Qn!=null&&(clearInterval(Qn),Qn=null),St.forEach(l=>l()),z.remove(),x==null||x.destroy(),_==null||_.remove(),Mn&&ue.removeEventListener("click",Mn)}};if((((Di=t==null?void 0:t.debugTools)!=null?Di:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:Vt,getMessages:Vt.getMessages,getStatus:Vt.getStatus,getMetadata:Vt.getPersistentMetadata,updateMetadata:Vt.updatePersistentMetadata,clearHistory:()=>Vt.clearChat(),setVoiceActive:y=>y?Vt.startVoiceRecognition():Vt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,St.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=J=>{let N=J.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Vt.focusInput()};if(window.addEventListener("persona:focusInput",m),St.push(()=>{window.removeEventListener("persona:focusInput",m)}),re){let J=be=>{let Ae=be.detail;(!(Ae!=null&&Ae.instanceId)||Ae.instanceId===l)&&Vt.showEventStream()},N=be=>{let Ae=be.detail;(!(Ae!=null&&Ae.instanceId)||Ae.instanceId===l)&&Vt.hideEventStream()};window.addEventListener("persona:showEventStream",J),window.addEventListener("persona:hideEventStream",N),St.push(()=>{window.removeEventListener("persona:showEventStream",J),window.removeEventListener("persona:hideEventStream",N)})}let y=J=>{let N=J.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Vt.showArtifacts()},A=J=>{let N=J.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Vt.hideArtifacts()},L=J=>{let N=J.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&Vt.upsertArtifact(N.artifact)},R=J=>{let N=J.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&Vt.selectArtifact(N.id)},B=J=>{let N=J.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Vt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",B),St.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",B)})}let Fn=Zu(n.persistState);if(Fn&&C){let l=Qu(Fn.storage),m=`${Fn.keyPrefix}widget-open`,y=`${Fn.keyPrefix}widget-voice`,A=`${Fn.keyPrefix}widget-voice-mode`;if(l){let L=((Fi=Fn.persist)==null?void 0:Fi.openState)&&l.getItem(m)==="true",R=((Ni=Fn.persist)==null?void 0:Ni.voiceState)&&l.getItem(y)==="true",B=((Oi=Fn.persist)==null?void 0:Oi.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{Vt.open(),setTimeout(()=>{var J;if(R||B)Vt.startVoiceRecognition();else if((J=Fn.persist)!=null&&J.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),($i=Fn.persist)!=null&&$i.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(_i=Fn.persist)!=null&&_i.voiceState&&(o.on("voice:state",J=>{l.setItem(y,J.active?"true":"false")}),o.on("user:message",J=>{l.setItem(A,J.viaVoice?"true":"false")})),Fn.clearOnChatClear){let J=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(A)},N=()=>J();window.addEventListener("persona:clear-chat",N),St.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return c&&C&&setTimeout(()=>{Vt.open()},0),Vt};var em=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},Kd=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.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"},$a=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=""},Xd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",$a(e)},Fa=e=>{e.style.transition=""},Na=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=""},Oa=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ta=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},tm=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},nm=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},Zd=(e,r,t,n,s,o,a)=>{var v,T,C,S,M,H;let i=On(o),u=i.reveal==="push";tm(e,r,t,n,u),nm(e,r,t,n,i.side,u),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 c=e.ownerDocument.defaultView,p=(T=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?T:!0,d=(S=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=d:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Na(r),Fa(n),Xd(n),Oa(t),ta(s,n),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",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((H=(M=o==null?void 0:o.launcher)==null?void 0:M.zIndex)!=null?H:Cn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.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"),Xd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Na(r),Fa(n),Oa(t),ta(s,n);let w=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":k;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=P,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.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",Fa(n),$a(n),ta(s,n);let w=em(i.width,e.clientWidth),k=Math.max(0,e.clientWidth),P=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${k+w}px`,r.style.transition=P,r.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${k}px`,t.style.maxWidth=`${k}px`,t.style.minWidth=`${k}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Na(r),$a(n),Oa(t),ta(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",P=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${k}`,n.style.width=k,n.style.maxWidth=k,n.style.minWidth=k,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||E?"hidden":"visible",n.style.transition=P,w&&(n.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")}},rm=(e,r)=>{let t=e.ownerDocument.createElement("div");return Kd(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Kd(t,n)},destroy(){t.remove()}}},om=(e,r)=>{var M,H,w,k;let{ownerDocument:t}=e,n=e.parentElement;if(!n)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"),u=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),d=(H=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||H?(k=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?k:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),On(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Zd(a,i,u,c,p,r,d)}),f.observe(a))},T=()=>{Zd(a,i,u,c,p,r,d),v()},C=a.ownerDocument.defaultView,S=()=>{T()};return C==null||C.addEventListener("resize",S),On(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),T(),{mode:"docked",host:p,shell:a,syncWidgetState(P){let E=P.launcherEnabled?P.open:!0;d!==E&&(d=E,T())},updateConfig(P){var E,G;r=P,((G=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?G:!0)===!1&&(d=!0),T()},destroy(){C==null||C.removeEventListener("resize",S),g(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},ts=(e,r)=>Gt(r)?om(e,r):rm(e,r);var _a={},sm=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 r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},am=()=>{try{if(typeof _a!="undefined"&&_a.url)return new URL("../widget.css",_a.url).href}catch{}return null},Qd=(e,r)=>{let t=am(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.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=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},ja=e=>{var C;let r=sm(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=ts(r,s),a,i=[],u=(S,M)=>{var P,E;let w=!((E=(P=M==null?void 0:M.launcher)==null?void 0:P.enabled)!=null?E:!0)||Gt(M),k=n.createElement("div");if(k.setAttribute("data-persona-root","true"),w&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),t){let G=S.attachShadow({mode:"open"});G.appendChild(k),Qd(G,n)}else S.appendChild(k),Qd(S,n);return r.id&&k.setAttribute("data-persona-instance",r.id),k},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let S=u(o.host,s);a=ea(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};d(),(C=e.onReady)==null||C.call(e);let g=S=>{f(),o.destroy(),o=ts(r,S),s=S,d()},v={update(S){var k,P,E,G,Q,K;let M={...s,...S,launcher:{...(k=s==null?void 0:s.launcher)!=null?k:{},...(P=S==null?void 0:S.launcher)!=null?P:{},dock:{...(G=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?G:{},...(K=(Q=S==null?void 0:S.launcher)==null?void 0:Q.dock)!=null?K:{}}}},H=Gt(s),w=Gt(M);if(H!==w){g(M);return}s=M,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},T=new Proxy(v,{get(S,M,H){if(M==="host")return o.host;if(M in S)return Reflect.get(S,M,H);let w=a[M];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=T),T};var op=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),im=new Set(["button","a","input","select","textarea","details","summary"]),lm=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),za=/\b(product|card|item|listing|result)\b/i,Ua=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,cm=3e3,dm=100;function sp(e){let r=typeof e.className=="string"?e.className:"";if(za.test(r)||e.id&&za.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&za.test(n.value))return!0}return!1}function ap(e){var r;return Ua.test(((r=e.textContent)!=null?r:"").trim())}function ip(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function pm(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ep(e){let r=e.match(Ua);return r?r[0]:null}function tp(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.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 um(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var mm="commerce-card",gm="result-card";function np(e){return!sp(e)||!ap(e)||!ip(e)&&!pm(e)?0:5200}function rp(e){var n;return!sp(e)||ap(e)||!ip(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Va=[{id:mm,scoreElement(e){return np(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Ua.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,p;if(np(e)===0)return null;let{title:t,href:n}=tp(e),s=(p=(c=ep(((u=e.textContent)!=null?u:"").trim()))!=null?c:ep(r.text))!=null?p:"",o=um(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
100
+ `)}},{id:gm,scoreElement(e){return rp(e)},formatSummary(e,r){if(rp(e)===0)return null;let{title:t,href:n}=tp(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
101
+ `)}}];function fm(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function hm(e){var p,d,f,g,v,T,C,S,M,H,w,k,P;let r=(p=e.options)!=null?p:{},t=(f=(d=r.maxElements)!=null?d:e.maxElements)!=null?f:80,n=(v=(g=r.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",s=(C=(T=r.maxTextLength)!=null?T:e.maxTextLength)!=null?C:200,o=(M=(S=r.visibleOnly)!=null?S:e.visibleOnly)!=null?M:!0,a=(H=r.root)!=null?H:e.root,i=(w=r.mode)!=null?w:"structured",u=(k=r.maxCandidates)!=null?k:Math.max(500,t*10),c=(P=e.rules)!=null?P:Va;return i==="simple"&&e.rules&&e.rules.length>0?(fm(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function qa(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var ym=["data-testid","data-product","data-action","data-id","data-name","data-type"];function bm(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||im.has(r)||t&&lm.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function lp(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function xm(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let u=e.getAttribute("role");u&&(r.role=u);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(r[p.name]=p.value)}return r}function Ja(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${qa(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of ym){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${qa(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=`${r}.${t.map(a=>qa(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 > ${r}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function vm(e){return e==="static"?dm:cm}function cp(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:Ja(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:bm(e),attributes:xm(e)}}function Cm(e,r,t,n){let s=vm(r.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,r,n);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function wm(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function Sm(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(op.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!lp(c)){i=a.nextNode();continue}let d=cp(c,e.maxTextLength),f=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(C=>C==="role");if(!f&&!g){i=a.nextNode();continue}if(n.has(d.selector)){i=a.nextNode();continue}n.add(d.selector);let{score:v,formattingRule:T}=Cm(c,d,e.rules,t);s.push({el:c,domIndex:o,enriched:d,score:v,formattingRule:T}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;wm(u,c)||u.push(c)}return u.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:d===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),u.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,t);g&&(p=g)}let d={...c.enriched};return p&&(d.formattedSummary=p),d})}function Am(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(op.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!lp(u)){o=s.nextNode();continue}let p=cp(u,e.maxTextLength),d=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!d&&!f){o=s.nextNode();continue}n.has(p.selector)||(n.add(p.selector),t.push(p))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function dp(e={}){var n;let r=hm(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?Am(r,t):Sm(r,t):[]}var na=100;function pp(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
102
102
  ${a.map(i=>`- ${i.split(`
103
103
  `).join(`
104
104
  `)}`).join(`
105
- `)}`)}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,Qs)}" (clickable)`);n.push(`Interactive elements:
105
+ `)}`)}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,na)}" (clickable)`);n.push(`Interactive elements:
106
106
  ${a.join(`
107
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Qs)}" (navigable)`);n.push(`Navigation links:
107
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,na)}" (navigable)`);n.push(`Navigation links:
108
108
  ${a.join(`
109
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Qs)}" (input)`);n.push(`Form inputs:
109
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,na)}" (input)`);n.push(`Form inputs:
110
110
  ${a.join(`
111
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Qs)}"`);n.push(`Content:
111
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,na)}"`);n.push(`Content:
112
112
  ${a.join(`
113
113
  `)}`)}return n.join(`
114
114
 
115
- `)}var pp={name:"@runtypelabs/persona",version:"3.11.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"},"./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","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --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,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Kr=pp.version;function gr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function Em(e){if(e)return{getHeaders:gr(e.getHeaders),onFeedback:gr(e.onFeedback),onCopy:gr(e.onCopy),requestMiddleware:gr(e.requestMiddleware),actionHandlers:gr(e.actionHandlers),actionParsers:gr(e.actionParsers),postprocessMessage:gr(e.postprocessMessage),contextProviders:gr(e.contextProviders),streamParser:gr(e.streamParser)}}var up=`({ text, message }: any) => {
115
+ `)}var up={name:"@runtypelabs/persona",version:"3.13.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"},"./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","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --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,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Xr=up.version;function gr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function Tm(e){if(e)return{getHeaders:gr(e.getHeaders),onFeedback:gr(e.onFeedback),onCopy:gr(e.onCopy),requestMiddleware:gr(e.requestMiddleware),actionHandlers:gr(e.actionHandlers),actionParsers:gr(e.actionParsers),postprocessMessage:gr(e.postprocessMessage),contextProviders:gr(e.contextProviders),streamParser:gr(e.streamParser)}}var mp=`({ text, message }: any) => {
116
116
  const jsonSource = (message as any).rawContent || text || message.content;
117
117
  if (!jsonSource || typeof jsonSource !== 'string') return null;
118
118
  let cleanJson = jsonSource
@@ -125,7 +125,7 @@ ${a.join(`
125
125
  if (parsed.action) return { type: parsed.action, payload: parsed };
126
126
  } catch (e) { return null; }
127
127
  return null;
128
- }`,mp=`function(ctx) {
128
+ }`,gp=`function(ctx) {
129
129
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
130
130
  if (!jsonSource || typeof jsonSource !== 'string') return null;
131
131
  var cleanJson = jsonSource
@@ -138,7 +138,7 @@ ${a.join(`
138
138
  if (parsed.action) return { type: parsed.action, payload: parsed };
139
139
  } catch (e) { return null; }
140
140
  return null;
141
- }`,gp=`(action: any, context: any) => {
141
+ }`,fp=`(action: any, context: any) => {
142
142
  if (action.type !== 'nav_then_click') return;
143
143
  const payload = action.payload || action.raw || {};
144
144
  const url = payload?.page;
@@ -155,7 +155,7 @@ ${a.join(`
155
155
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
156
156
  window.location.href = targetUrl;
157
157
  return { handled: true, displayText: text };
158
- }`,fp=`function(action, context) {
158
+ }`,hp=`function(action, context) {
159
159
  if (action.type !== 'nav_then_click') return;
160
160
  var payload = action.payload || action.raw || {};
161
161
  var url = payload.page;
@@ -172,26 +172,26 @@ ${a.join(`
172
172
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
173
173
  window.location.href = targetUrl;
174
174
  return { handled: true, displayText: text };
175
- }`,Tm=`(parsed: any) => {
175
+ }`,Mm=`(parsed: any) => {
176
176
  if (!parsed || typeof parsed !== 'object') return null;
177
177
  if (parsed.action === 'nav_then_click') return 'Navigating...';
178
178
  if (parsed.action === 'message') return parsed.text || '';
179
179
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
180
180
  return parsed.text || null;
181
- }`,Mm=`function(parsed) {
181
+ }`,km=`function(parsed) {
182
182
  if (!parsed || typeof parsed !== 'object') return null;
183
183
  if (parsed.action === 'nav_then_click') return 'Navigating...';
184
184
  if (parsed.action === 'message') return parsed.text || '';
185
185
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
186
186
  return parsed.text || null;
187
- }`;function km(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function ea(e){var r,t;return(t=(r=e.parserType)!=null?r:km(e.streamParser))!=null?t:"plain"}function ta(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,s])=>{typeof s=="string"&&t.push(`${r} ${n}: "${s}",`)}),t.push(`${r}},`)),t}function na(e,r,t){let n=[],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)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${r} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${a}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function ra(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(n||s)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`)}),t.push(`${r} },`)),s&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function oa(e,r){let t=[];if(e.layout){let n=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");(n||s)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),s&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${r} avatar: {`),Object.entries(a).forEach(([i,u])=>{typeof u=="string"?t.push(`${r} ${i}: "${u}",`):typeof u=="boolean"&&t.push(`${r} ${i}: ${u},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([u])=>u!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?t.push(`${r} ${u}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${u}: ${c},`))}),t.push(`${r} },`)):typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function Va(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function hp(e,r,t){Object.entries(r).forEach(([n,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${n}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${n}: {`),hp(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Lr(e,r,t,n){t&&(e.push(`${n}${r}: {`),hp(e,t,`${n} `),e.push(`${n}},`))}function yp(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:Em(t.hooks)}:void 0;return r==="esm"?Lm(n,s):r==="script-installer"?Wm(n):r==="script-advanced"?Hm(n,s):r==="react-component"?Im(n,s):r==="react-advanced"?Pm(n,s):Rm(n,s)}function Lm(e,r){let t=r==null?void 0:r.hooks,n=ea(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(o,"theme",e.theme," "),e.launcher&&Lr(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(...ta(e," ")),o.push(...na(e," ",t)),o.push(...ra(e," ")),o.push(...oa(e," ")),o.push(...Va(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(`
188
- `)}function Im(e,r){let t=r==null?void 0:r.hooks,n=ea(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(o,"theme",e.theme," "),e.launcher&&Lr(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(...ta(e," ")),o.push(...na(e," ",t)),o.push(...ra(e," ")),o.push(...oa(e," ")),o.push(...Va(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(`
189
- `)}function Pm(e,r){let t=r==null?void 0:r.hooks,n=["// 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&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(n,"theme",e.theme," "),e.launcher&&Lr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...ta(e," ")),n.push(...na(e," ",t)),n.push(...ra(e," ")),n.push(...oa(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${Tm}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${up}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${up}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${gp}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${gp}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
190
- `)}function bp(e){var s;let r=ea(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.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&&(n.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&&(n.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&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,u])=>{i!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,u])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof u=="object"&&u!==null)a.avatar=u;else if(i==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[d]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Wm(e){let r=bp(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Kr}/dist/install.global.js" data-config='${t}'></script>`}function Rm(e,r){let t=r==null?void 0:r.hooks,n=ea(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Kr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Kr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(o,"theme",e.theme," "),e.launcher&&Lr(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(...ta(e," ")),o.push(...na(e," ",t)),o.push(...ra(e," ")),o.push(...oa(e," ")),o.push(...Va(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(`
191
- `)}function Hm(e,r){let t=r==null?void 0:r.hooks,n=bp(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
187
+ }`;function Lm(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function ra(e){var r,t;return(t=(r=e.parserType)!=null?r:Lm(e.streamParser))!=null?t:"plain"}function oa(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,s])=>{typeof s=="string"&&t.push(`${r} ${n}: "${s}",`)}),t.push(`${r}},`)),t}function sa(e,r,t){let n=[],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)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${r} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${a}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function aa(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(n||s)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`)}),t.push(`${r} },`)),s&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function ia(e,r){let t=[];if(e.layout){let n=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");(n||s)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),s&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${r} avatar: {`),Object.entries(a).forEach(([i,u])=>{typeof u=="string"?t.push(`${r} ${i}: "${u}",`):typeof u=="boolean"&&t.push(`${r} ${i}: ${u},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([u])=>u!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?t.push(`${r} ${u}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${u}: ${c},`))}),t.push(`${r} },`)):typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function Ya(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function yp(e,r,t){Object.entries(r).forEach(([n,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${n}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${n}: {`),yp(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Lr(e,r,t,n){t&&(e.push(`${n}${r}: {`),yp(e,t,`${n} `),e.push(`${n}},`))}function bp(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:Tm(t.hooks)}:void 0;return r==="esm"?Im(n,s):r==="script-installer"?Rm(n,s):r==="script-advanced"?Bm(n,s):r==="react-component"?Pm(n,s):r==="react-advanced"?Wm(n,s):Hm(n,s)}function Im(e,r){let t=r==null?void 0:r.hooks,n=ra(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(o,"theme",e.theme," "),e.launcher&&Lr(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(...oa(e," ")),o.push(...sa(e," ",t)),o.push(...aa(e," ")),o.push(...ia(e," ")),o.push(...Ya(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(`
188
+ `)}function Pm(e,r){let t=r==null?void 0:r.hooks,n=ra(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(o,"theme",e.theme," "),e.launcher&&Lr(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(...oa(e," ")),o.push(...sa(e," ",t)),o.push(...aa(e," ")),o.push(...ia(e," ")),o.push(...Ya(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(`
189
+ `)}function Wm(e,r){let t=r==null?void 0:r.hooks,n=["// 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&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(n,"theme",e.theme," "),e.launcher&&Lr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...oa(e," ")),n.push(...sa(e," ",t)),n.push(...aa(e," ")),n.push(...ia(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${Mm}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${mp}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${mp}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${fp}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${fp}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
190
+ `)}function xp(e){var s;let r=ra(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.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&&(n.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&&(n.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&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,u])=>{i!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,u])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof u=="object"&&u!==null)a.avatar=u;else if(i==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[p]=d)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Rm(e,r){let t=xp(e),n=r!=null&&r.windowKey?{config:t,windowKey:r.windowKey}:t,s=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/dist/install.global.js" data-config='${s}'></script>`}function Hm(e,r){let t=r==null?void 0:r.hooks,n=ra(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...r!=null&&r.windowKey?[` windowKey: '${r.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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Lr(o,"theme",e.theme," "),e.launcher&&Lr(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(...oa(e," ")),o.push(...sa(e," ",t)),o.push(...aa(e," ")),o.push(...ia(e," ")),o.push(...Ya(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(`
191
+ `)}function Bm(e,r){let t=r==null?void 0:r.hooks,n=xp(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
192
192
  `).map((a,i)=>i===0?a:" "+a).join(`
193
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Kr}/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(${Mm});`),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(` ${mp}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${mp}`),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(` ${fp}`),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(` ${fp}`),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,"," 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(`
194
- `)}var xp={desktop:{w:1280,h:800},mobile:{w:390,h:844}},vp=.1,Cp=.15,wp=1.5,Ja=24,Sp=40,Bm=`
193
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Xr}/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(${km});`),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(` ${gp}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${gp}`),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(` ${hp}`),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(` ${hp}`),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,",...r!=null&&r.windowKey?[` windowKey: '${r.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(`
194
+ `)}var vp={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Cp=.1,wp=.15,Sp=1.5,Ga=24,Ap=40,Dm=`
195
195
  /* \u2500\u2500 Root \u2500\u2500 */
196
196
  .persona-dc-root {
197
197
  display: flex;
@@ -342,7 +342,7 @@ ${a.join(`
342
342
  .persona-dc-stage {
343
343
  height: 550px;
344
344
  min-height: 400px;
345
- padding: ${Ja}px;
345
+ padding: ${Ga}px;
346
346
  overflow: auto;
347
347
  background: #f0f1f3;
348
348
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -432,5 +432,5 @@ ${a.join(`
432
432
  min-height: 300px;
433
433
  }
434
434
  }
435
- `;function Dm(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Bm,document.head.appendChild(e)}function Nm(e,r){let t=e.clientWidth-Ja*2-Sp,n=e.clientHeight-Ja*2-Sp;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Fm(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Ap(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Dm();let d=Math.max(0,Math.min(n,t.length-1)),p=s,f=o,g=null,v=1,T=!1,C=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),M=h("div","persona-dc-toolbar-lead"),R=h("div","persona-dc-toolbar-trail"),w=Lt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Xe(-1)}),k=h("div");k.style.position="relative";let P=h("button","persona-dc-title-btn");P.type="button",P.setAttribute("aria-expanded","false"),P.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),V=h("span","persona-dc-title-chevron"),te=fe("chevron-down",12,"currentColor",2);te&&V.appendChild(te),P.append(E,V);let Z=h("div","persona-dc-dropdown");Z.setAttribute("role","listbox"),Z.style.display="none";let O=!1;function ee(){Z.innerHTML="";for(let j=0;j<t.length;j++){let J=t[j],ie=h("button","persona-dc-dropdown-item");ie.type="button",ie.setAttribute("role","option"),ie.setAttribute("aria-current",j===d?"true":"false");let $e=h("span");if($e.textContent=J.title,ie.appendChild($e),J.description){let Q=h("span","persona-dc-dropdown-desc");Q.textContent=J.description,ie.appendChild(Q)}ie.addEventListener("click",()=>{ne(),ft(j)}),Z.appendChild(ie)}}function xe(){O=!O,Z.style.display=O?"":"none",P.setAttribute("aria-expanded",O?"true":"false"),O&&ee()}function ne(){O&&(O=!1,Z.style.display="none",P.setAttribute("aria-expanded","false"))}P.addEventListener("click",j=>{j.stopPropagation(),xe()});let we=()=>ne();document.addEventListener("click",we),k.append(P,Z);let De=Lt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Xe(1)}),me=h("span","persona-dc-counter");M.append(w,k,De,me);let ke=null;i&&(ke=Go({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:j=>{p=j,G.dataset.device=p,g=null,q()}}),R.appendChild(ke.element));let Le=null;if(a){let j=h("div","persona-dc-zoom-controls"),J=Lt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Q=g!=null?g:v;g=Math.max(Cp,Q-vp),q()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{g=1,q()});let ie=Lt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Q=g!=null?g:v;g=Math.min(wp,Q+vp),q()}}),$e=Lt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,q()}});j.append(J,Le,ie,$e),R.appendChild(j)}if(u){let j=h("div","persona-dc-separator");R.appendChild(j);let J=Go({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ie=>{f=ie,G.dataset.colorScheme=f,ye()}});R.appendChild(J.element)}let le=h("div","persona-dc-separator");R.appendChild(le);let K=Lt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[d].url,"_blank")}});R.appendChild(K),S.append(M,R);let pe=h("div","persona-dc-stage"),G=h("div","persona-dc-iframe-wrapper");G.dataset.device=p,G.dataset.colorScheme=f;let oe=h("iframe","persona-dc-iframe");oe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),oe.setAttribute("loading","lazy"),oe.title=t[d].title,G.appendChild(oe),pe.appendChild(G),C.append(S,pe),e.appendChild(C);function ye(){var j;try{let J=(j=oe.contentDocument)==null?void 0:j.body;if(!J)return;f==="dark"?J.classList.add("theme-dark"):J.classList.remove("theme-dark")}catch{}}oe.addEventListener("load",()=>ye());function Ie(){let j=t[d];E.textContent=j.title,me.textContent=`${d+1} / ${t.length}`,oe.title=j.title}function Xe(j){let J=((d+j)%t.length+t.length)%t.length;ft(J)}function ft(j){j<0||j>=t.length||(d=j,oe.src=t[d].url,Ie(),c==null||c(d,t[d]))}function q(){var ie;if(T)return;let j=(ie=xp[p])!=null?ie:xp.desktop;v=Nm(pe,j);let J=Math.max(Cp,Math.min(wp,g!=null?g:v));Fm(G,oe,j,J,p),Le&&(Le.textContent=`${Math.round(J*100)}%`)}let D=new ResizeObserver(()=>q());D.observe(pe),Ie(),oe.src=t[d].url,requestAnimationFrame(()=>q());function ce(){T||(T=!0,D.disconnect(),document.removeEventListener("click",we),C.remove())}return{element:C,goTo:ft,next:()=>Xe(1),prev:()=>Xe(-1),getIndex:()=>d,setDevice(j){p=j,G.dataset.device=j,ke==null||ke.setSelected(j),g=null,q()},setColorScheme(j){f=j,G.dataset.colorScheme=j},setZoom(j){g=j,q()},destroy:ce}}function Ep(){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 Tp(){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 Mp(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.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)}}),{...r,palette:t}}}}function kp(){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 Lp(){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,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Ip(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Om={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"}}},Pp={components:{panel:{borderRadius:"0",shadow:"none"}}},Ya={id:"shop",label:"Shopping Assistant",config:{theme:Om,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Wn},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?"]}},Ga={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Pp}},Xa={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Pp}},Ka={shop:Ya,minimal:Ga,fullscreen:Xa};function Wp(e){return Ka[e]}var $m=$a;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultParseRules,detectColorScheme,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,reducedMotionPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,validateImageFile,validateTheme});
435
+ `;function Fm(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Dm,document.head.appendChild(e)}function Nm(e,r){let t=e.clientWidth-Ga*2-Ap,n=e.clientHeight-Ga*2-Ap;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Om(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Ep(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Fm();let p=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,g=null,v=1,T=!1,C=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),M=h("div","persona-dc-toolbar-lead"),H=h("div","persona-dc-toolbar-trail"),w=Lt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Re(-1)}),k=h("div");k.style.position="relative";let P=h("button","persona-dc-title-btn");P.type="button",P.setAttribute("aria-expanded","false"),P.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),G=h("span","persona-dc-title-chevron"),Q=ye("chevron-down",12,"currentColor",2);Q&&G.appendChild(Q),P.append(E,G);let K=h("div","persona-dc-dropdown");K.setAttribute("role","listbox"),K.style.display="none";let O=!1;function ne(){K.innerHTML="";for(let $=0;$<t.length;$++){let U=t[$],ce=h("button","persona-dc-dropdown-item");ce.type="button",ce.setAttribute("role","option"),ce.setAttribute("aria-current",$===p?"true":"false");let _e=h("span");if(_e.textContent=U.title,ce.appendChild(_e),U.description){let ee=h("span","persona-dc-dropdown-desc");ee.textContent=U.description,ce.appendChild(ee)}ce.addEventListener("click",()=>{re(),Ze($)}),K.appendChild(ce)}}function Ce(){O=!O,K.style.display=O?"":"none",P.setAttribute("aria-expanded",O?"true":"false"),O&&ne()}function re(){O&&(O=!1,K.style.display="none",P.setAttribute("aria-expanded","false"))}P.addEventListener("click",$=>{$.stopPropagation(),Ce()});let xe=()=>re();document.addEventListener("click",xe),k.append(P,K);let We=Lt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Re(1)}),me=h("span","persona-dc-counter");M.append(w,k,We,me);let Me=null;i&&(Me=Go({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:$=>{d=$,V.dataset.device=d,g=null,z()}}),H.appendChild(Me.element));let ke=null;if(a){let $=h("div","persona-dc-zoom-controls"),U=Lt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.max(wp,ee-Cp),z()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{g=1,z()});let ce=Lt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.min(Sp,ee+Cp),z()}}),_e=Lt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,z()}});$.append(U,ke,ce,_e),H.appendChild($)}if(u){let $=h("div","persona-dc-separator");H.appendChild($);let U=Go({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ce=>{f=ce,V.dataset.colorScheme=f,ge()}});H.appendChild(U.element)}let oe=h("div","persona-dc-separator");H.appendChild(oe);let X=Lt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});H.appendChild(X),S.append(M,H);let pe=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=d,V.dataset.colorScheme=f;let te=h("iframe","persona-dc-iframe");te.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),te.setAttribute("loading","lazy"),te.title=t[p].title,V.appendChild(te),pe.appendChild(V),C.append(S,pe),e.appendChild(C);function ge(){var $;try{let U=($=te.contentDocument)==null?void 0:$.body;if(!U)return;f==="dark"?U.classList.add("theme-dark"):U.classList.remove("theme-dark")}catch{}}te.addEventListener("load",()=>ge());function de(){let $=t[p];E.textContent=$.title,me.textContent=`${p+1} / ${t.length}`,te.title=$.title}function Re($){let U=((p+$)%t.length+t.length)%t.length;Ze(U)}function Ze($){$<0||$>=t.length||(p=$,te.src=t[p].url,de(),c==null||c(p,t[p]))}function z(){var ce;if(T)return;let $=(ce=vp[d])!=null?ce:vp.desktop;v=Nm(pe,$);let U=Math.max(wp,Math.min(Sp,g!=null?g:v));Om(V,te,$,U,d),ke&&(ke.textContent=`${Math.round(U*100)}%`)}let W=new ResizeObserver(()=>z());W.observe(pe),de(),te.src=t[p].url,requestAnimationFrame(()=>z());function se(){T||(T=!0,W.disconnect(),document.removeEventListener("click",xe),C.remove())}return{element:C,goTo:Ze,next:()=>Re(1),prev:()=>Re(-1),getIndex:()=>p,setDevice($){d=$,V.dataset.device=$,Me==null||Me.setSelected($),g=null,z()},setColorScheme($){f=$,V.dataset.colorScheme=$},setZoom($){g=$,z()},destroy:se}}function Tp(){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 Mp(){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 kp(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.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)}}),{...r,palette:t}}}}function Lp(){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 Ip(){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,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Pp(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var $m={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"}}},Wp={components:{panel:{borderRadius:"0",shadow:"none"}}},Ka={id:"shop",label:"Shopping Assistant",config:{theme:$m,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Wn},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?"]}},Xa={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Wp}},Za={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Wp}},Qa={shop:Ka,minimal:Xa,fullscreen:Za};function Rp(e){return Qa[e]}var _m=ja;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultParseRules,detectColorScheme,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,reducedMotionPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,validateImageFile,validateTheme});
436
436
  //# sourceMappingURL=index.cjs.map